Source: blog.brainztorm.com


          Pesticide-Free Spaces: Lessons in Communication, Community and Change        

The Center for Energy and Environmental Eduation and students in the Department of Communication Studies are working together to reduce the amount of lawn pesticides used in Iowa. The meeting is open to the public.

Meetings
Location: 
Wesley Foundation (Treehouse)
Tuesday, November 15, 2016 - 7:00 pm
Enter Your Email: 
Share/Save
          Besplatna lutka        


 

 Odi na jedan od ovih proxy-a:
dutchproxyserver.com ili dutchproxy.nu ili teleport.to/Netherlands/
Zalijepi ovu adresu:
http://stardoll.com/en/contest
Ulogiraj se na stardoll i to je to :)

          Î— Adobe καταργεί οριστικά το Flash στα τέλη του 2020        

Ο θάνατος του Flash έχει προβλεφθεί εδώ και αρκετό καιρό, ειδικά μετά τις κινήσεις της Adobe τα τελευταία χρόνια, όμως σήμερα γνωρίζουμε και την ακριβή ημερομηνία που η πάλαι ποτέ δημοφιλής τεχνολογία του Internet, θα αφήσει την τελευταία της πνοή.
Αυτή δεν είναι άλλη από την 31η Δεκεμβρίου του 2020 σύμφωνα με σημερινή ανακοίνωση της Adobe, όταν και η εταιρεία θα σταματήσει να κυκλοφορεί αναβαθμίσεις για το Flash αλλά και να το διαθέτει στην αγορά σε οποιαδήποτε έκδοσή του. Στην ανακοίνωση η εταιρεία αναφέρει και ενδιαφέροντα στατιστικά στοιχεία που δείχνουν τη σημαντική πτώση στη χρήση ιστοσελίδων που χρησιμοποιούν την τεχνολογία. Συγκεκριμένα το 2014, το 80% των χρηστών του Chrome browser επισκεπτόντουσαν καθημερινά τουλάχιστον μία ιστοσελίδα με Flash περιεχόμενο, ένα ποσοστό που κατακρημνίστηκε στο 17% στις μέρες μας.

Μέχρι το τέλος του 2020, η Adobe θα κυκλοφορεί αναβαθμίσεις ασφάλειας σε συνεργασία με την Apple, τη Mozilla, τη Microsoft και τη Google προκειμένου να υπάρχει τυπική υποστήριξη στους browsers των συγκεκριμένων εταιρειών. Ήδη οι περισσότερες από αυτές τις εταιρείες έχουν προχωρήσει εδώ και αρκετό καιρό σε απενεργοποίηση του Flash περιεχομένου από τις ιστοσελίδες που φορτώνει ο χρήστης, και ο οποίος θα πρέπει να κάνει κλικ προκειμένου να εμφανίσει το σχετικό περιεχόμενο.

Η τεχνολογία Flash αν και δεν έκανε εύκολη τη ζωή των προγραμματιστών, εντούτοις έδινε τη δυνατότητα δημιουργίας εντυπωσιακών ιστοσελίδων, οι οποίες όμως δεν μπορούσαν σε καμία περίπτωση να είναι εξίσου εντυπωσιακές και σε φορητές συσκευές και ειδικότερα στα smartphones. Στην ιστορία έχει περάσει άλλωστε η απόφαση του Steve Jobs που από την πρώτη στιγμή είχε αποκλείσει την παρουσία του περιεχομένου Flash στο iPhone εξαιτίας των προβλημάτων που δημιουργούσε με την αυτονομία της συσκευής.

Επιπλέον τα τελευταία χρόνια, η άνοδος των ανοιχτών προτύπων HTML 5, WebGL, CSS και Javascript, δίνει την ευκαιρία στους προγραμματιστές να δημιουργήσουν εξίσου εντυπωσιακές ιστοσελίδες και web υπηρεσίες, με τη δυνατότητα αυτές να τρέχουν σε διαφορετικών ειδών συσκευές με ελάχιστες αλλαγές.

[via]

          Comment on Javascript array definition problem on Internet Explorer 6 (and 7) by sailfish        
I have fun with, cause I discovered exactly what I used to be taking a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye
          Albany and Water park        
This Tuesday, we went off to see a tour of the State Capitol building in Albany followed by a trip to a nearby water park.
Here are some pictures


























          Protecting Our Houses of Worship: Guest Column by Security Expert / Retired NYPD Detective Sergeant         

By ALAN SCHISSEL

Founder & Chief Executive Officer

  • Integrated Security Services

  • According to the Washington Post, “it’s been a bad 2017 for Jews.” During the month of January, 48 bomb threats were called in to Jewish community centers across the country. Also last month, a neo-Nazi made national news by promising to hold a march in Whitefish, Montana to intimidate the town’s small Jewish population.

    This, of course, was followed by another unprecedented press conference by our President during which two reporters were moved to ask Mr. Trump about the rise in anti-Semitism. Many of us were aghast at the President’s rude and dismissive response, and his unwillingness to address the question seriously. The fact is, the country is experiencing an alarming increase of anti-Semitic incidents, and this has been trending upward since 2015. A security report issued by the Department of Homeland Security on protecting houses of worship stated that the United States has approximately 345,000 religious congregations representing 230 denominational groups and roughly 150 million members. Despite being sanctuaries from the troubles of the world, houses of worship have also been targets as violence has spiked across the country in recent years. The killing of nine people at Emanuel A.M.E. Church in Charleston, South Carolina was the largest mass shooting in a house of worship since 1991, when nine people were shot at the Wat Promkunaram Buddhist temple in Waddell, Arizona, northwest of Phoenix.

    [Under relentless pressure, the President subsequently denounced anti-Semitism.]

  • Empathy and action: Muslims unite to help fix vandalized Jewish cemeteries


  • The intent of this column is to generate awareness and provide a short guide which contains security practices for religious institutions, parishioners and our non religious communities to help deter threats, mitigate hazards and risks, and minimize the damage caused by an incident in or around a house of worship, including mass casualty events.

    I preface with the word “short” because there is a wide range of methods from programmatic and procedural considerations to technological enhancements that religious facilities and their leadership may consider implementing based upon the most likely threats to their facilities and their available resources. Basic security principals would suggest taking a blended approach to security and safety with the goal of hardening the facility to deter, detect and/or delay a criminal occurrence before it happens. The next steps are equally important and this is where lives are saved and mass casualties are reduced. Selecting the appropriate response to a threat or armed intrusion will help facilitate a safe transition into an effective recovery and restoration of services mode.

    Identifying Your Threats & Vulnerabilities

    Identifying and evaluating a known or potential threat to a given facility is the first step of a security assessment. The results of which will guide the process of developing a security plan. A proper readiness plan will aim to deter a threat or mitigate a threat by reducing the religious facility’s vulnerability to those threats.

    Natural Hazards vs. Targeted Violence

    As stated before, all life safety solutions should be designed using a blended approach to managing risk. Protecting a religious facility means your emergency management plan(s) must address an all-hazard approach to both natural hazards, e.g., infectious diseases and illnesses, fire, and seismic and weather-related events (hurricanes, tornadoes, flash floods) as well as targeted attacks. Spontaneous and pre-planned attacks are likely to occur by individual(s) who use firearms; improvised explosive devices (IEDs); vehicle-borne improvised explosive devices (VBIEDs); chemical, biological, or radiological attacks; or arson in order to inflict a number of casualties and damage to religious facilities.

    Protective Measures

    As previously mentioned earlier, a house of worship environment is managed by creating layers of protective measures in collaboration with state and local partners that allow religious institutions to deter, detect and delay threats. These layers also allow an institution to consider a threat as soon as possible and to more effectively respond to, further deter, eliminate or mitigate that threat.

    • Technological sensors such as CCTV surveillance cameras or alarms (fire, smoke, wind, and intrusion detection) will trigger informed decision-making.

    • Barriers, such as locked doors or fixed barriers or uniform security personnel should be in place to deter or delay a threat and afford more time for effective decision making.

    • Having the correct inbound and outbound communication network in place will influence a number key decisions. Time, or the lack of time, is a principle disrupter of effective decision-making. Sound communication strategies such as emergency email blasts, voice activated alert systems, and silent alert systems help to improve response to and during a crisis. An effective communication protocol should expand the window of time available to leaders to make sound decisions.

    Additional Measures to Consider:

    • Reporting Procedures

    • Establishing Collaborative Planning Teams

    • Starting an Emergency Operations Plan

    • Define Roles and Responsibilities

    • Notification Procedures

    • Evacuation Lockdown and Shelter‐In‐Place Policies and Procedures

    • Plans for Diverse Needs of Children and Staff

    • Necessary Equipment and Supplies

    • Common Vocabulary

    • Emergency Drills

    Call us at (212) 808-4153, or write us to tell what you think or how we can be of more assistance and remember, always dial 911 first in an emergency!







  • Integrated Security Services


  • About Alan Schissel










  • Cool Justice Editor’s Note: By way of disclosure, Cool Justice is an occasional denizen of Integrated’s Hartford office and once in a while even does a little work …

  • more COOL JUSTICE

  • Hartford PI Stars in Network Real-Life Manhunt Show

  •           Post Shuwit Shuwit Nyampah - Hahaha~        
    bila tengok gambar ni, terus rasa "pandai aku jaga... mengembang dengan helokkk"
    hahahahahaha


    10 tahun dah.. 
    banyak sangat ups and downs yang kitorang dah lalui
    dari zaman freehair pakai cap, sampai la *ehem*ayu*ehem* macam ni.. hahaahaha


    teringat lagi, nak mengorat ambik nombor phone depan depan takut
    ye lah, wanie jenis ignorance sikit - not too friendly dengan orang tak kenal
    pergi kelas, balik kelas ... petang nye atau malam pegi gym training Taekwondo
    weekend? 
    membuta je ... takpun jejalan pegi Times Square / Jusco / Midvalley sesorang
    last-last?
    buat-buat pinjam buku Java Programming
    sebab dapat tau yang semua buku-buku wanie, ada nombor phone (time tu buku mahal, takde nak download-download) so kalau wanie misplaced buku tu, hopefully ada orang call lah.. hahaha


    awal-awal dulu, SMS "Hi" je... 
    nak ngorat tapi tak reti
    lama-lama, sebab se"utara" , jadi rapat - kalau nak balik kampung, naik bas sekali 
    ada chemistry sebab sama-sama agak skema
    port dating dulu-dulu haruzzzlahh Lowyat kan
    paham-paham je lah interest sama.. 
    further study pun sesama lagi, course sama
    cuma result dia lah lagi excellent 
    walaupun dalam kelas, keja membuta.. notes pun ambik kat kita yang macam nak putus jari mencatat itu ini


    tak sangka
    2 bulan lagi bakal disatukan jadi husband and wife
    dalam masa bertunang ni
    dua-dua cuba lebih memahami dan lebih mengenali 
    Alhamdulillah... 
    takde dugaan yang berat berat
    cuma masing-masing terlampau sibuk dengan kerja, sampai rasa kena abandon 
    tapi cepat-cepat kami "fix" balik loophole tu


    dalam hubungan perlu ada
    give and take
    trust
    understanding
    loyal
    jealousy
    loving
    caring
    be yourself

    know-how-to-annoy-your-partner
    contohnya 
    nyanyi kuat-kuat dalam keta walaupun suara kelautt
    kutuk-kutuk each other
    contohnya
    gumuknyeee... but i still love u! 
    haaagitteww..
    - padahal, kita pun dah start mengembang dengan marvelous ni -


    harapannya
    #kejannah uolzzz..
    hahaha~


    - wanie
    - 09:58 | 1/22/2017 -
    - Hewlett-Packard -

    p/s : ye, kena keja weekend. sebab takde user ni yang boleh blogging!

              ILIQUIDEZ E IMPUESTOS: Ineficiencias del sistema tributario.        
    Yo pesco y el estado pesca lo que pesco...
    El sistema tributario justo es aquel que no existe. En justicia todo derecho tiene su causa en términos antropológicos o económicos. Ahora bien, si no hay una causa para una determinada erogación, por más que sea "legal", estamos ante una injusticia y un enriquecimiento sin causa. Ahora bien, dirán los constitucionalistas -que creen que un texto es vinculante porque sí- que es que es nuestra "contribución al bien común". La verdad eso no son más que teorías que producen unos sofistas burócratas para permanecer en sus deliciosos tronos de poder. ¿Acaso usted firmó la constitución? ¿Por qué tiene que pagar por proyectos de los políticos que muchas veces son ineficientes de los cuales no está de acuerdo con muchos?

    Por ejemplo, a muchas personas que estamos en desacuerdo con el Asesinato de Niños por nacer, nos obligan a financiar ese crimen por una decisión de 5 magistrados. ¿Por qué en aras del supuesto bien común tendría yo que seguir como un esclavo aquellos lineamientos? ¿Por qué tenemos que permitir que el dinero que nosotros ganamos se utilice para financiar el crimen de unas pocas multinacionales perversas? 

    Ya decía Lysander Spooner:
    "Todos los grandes gobiernos de la tierra - los que hoy existen como los que han ido desapareciendo - han tenido el mismo carácter. No pasan de simples bandas de ladrones que se han asociado con el fin de despojar, conquistar y someter a sus semejantes." (Tomado de SPOONER, Lysander. “El derecho natural: la ciencia de la justicia” En Wikisource tomado dehttp://es.wikisource.org/wiki/El_derecho_natural:_la_ciencia_de_la_justicia 08/10/2009 02:39 p.m. Capítulo III. El derecho natural contra la legislación. Segunda parte del Capítulo.)
    Y es que el fenómeno es bastante cierto y se observa por ejemplo en los denominados "combos" de Medellín que muchos quieren incluir en la "institucionalidad". Estos combos son bandas asociadas de delincuentes que dominan unas zonas limitadas por "fronteras invisibles", tienen allí el monopolio de las armas, cobran "vacuna" que no es más que una suma mensual a cambio de "protección". Inclusive se ha llegado a afirmar que los combos suelen tener mejor logística que la Policía Metropolitana. Nadie negaría que los "combos" son bandas delincuenciales, pero quiero que alguien me diga cuál es la diferencia de estos con el estado. A mi modo de ver la diferencia radica en el cómo, los combos son auténticos, el estado mentiroso. Además, los combos no requieren gigantescas justificaciones ideológicas para legitimar su acción, hacen lo que hacen y listo. Son delincuentes y lo saben, en cambio, muchas de las personas que trabajan en el estado ni si quiera se han dado cuenta para quién trabajan...

    LAS INEFICIENCIAS TRIBUTARIAS.
    Uno de los tantos "tributos" sin sentido.
    Norte de Santander cobra a todos las personas
    que salen del aeropuerto Camilo Daza de Cúcuta,
    esta estampilla. ¿Por qué? ¡Pura recocha!
    Contrario a los combos dueños de fronteras invisibles, restringiendo la entrada a dichas zonas, el estado se ha devanado el cerebro en generar justificaciones absurdas a su accionar y frente a los impuestos siempre está el trasfondo de la eficiencia. ¿Cómo recaudar más (para nada) sin desincentivar el trabajo de sus víctimas? El trasfondo de incentivar cierta actividad económica o cierta acción conveniente al estado provoca una serie de disposiciones tributarias. Conclusión un complejo enmarañado de disposiciones que generan una serie de costos operativos adicionales para la gestión empresarial.

    Ese enmarañado sistema genera que en Colombia haya un exceso de tributación. Tanto como los griegos que le tenían altar al "dios desconocido" en Colombia puede llegar un momento en que nos toque pagar al "impuesto desconocido". A grandes rasgos los principales impuestos en Colombia son:

    • Impuesto sobre la renta y complementarios.
    • Impuesto sobre el valor agregado (IVA).
    • Gravámen a los movimientos financieros (4 X 1000)
    • Impuesto de Industria y Comercio y Avisos y Tableros (Municipal).
    Estos impuestos, en apariencia simples, plantean una serie de complicaciones operativas a las empresas que hacen prácticamente que tenga una o dos personas de tiempo completo como mínimo resolviendo el problema de los impuestos. Es tal que muchos de los enredos provienen de presumir la mala fe del "contribuyente".

    SE PRESUME LA MALA FE DEL CONTRIBUYENTE.
    La verdad creo que este es un principio acertado de la tributación, ¡NADIE QUIERE PAGAR IMPUESTOS! No creo que haya alguien que pague la declaración bimestral del IVA o el impuesto de renta con una satisfacción y una sonrisa "Hoy contribuí al bien común" y pensando "Un compromiso tan lindo que no puedo evadir". Bueno quizás Ned Flanders en un capítulo de los Simpson, capítulo donde se hace una crítica anarquista y capitalista bastante positiva... y donde obviamente se ve que los impuestos son un dolor de cabeza...Aquí pueden verlo http://www.seriescoco.com/capitulo/los-simpsons/capitulo-20/40521

    El caso es que esa presunción de mala fe del contribuyente genera un enmarañado inteligentísimo que el estado llamó "retención en la fuente". La retención en la fuente aplica para todos los impuestos (excepto para el 4 X 1000 dado que éste ya es de por sí una retención del banco al dueño de la cuenta). Pero no se dio cuenta el inteligentísimo legislador que estaba confiándole el aumento de las contribuciones a la misma serie de personas de las que desconfiaba. Linda solución crear penalizar la "omisión del agente retenedor":

    ARTICULO 402. OMISION DEL AGENTE RETENEDOR O RECAUDADOR. <Ver Notas del Editor> <Penas aumentadas por el artículo 14 de la Ley 890 de 2004, a partir del 1o. de enero de 2005. El texto con las penas aumentadas es el siguiente:>

     El agente retenedor o autorretenedor que no consigne las sumas retenidas o autorretenidas por concepto de retención en la fuente dentro de los dos (2) meses siguientes a la fecha fijada por el Gobierno Nacional para la presentación y pago de la respectiva declaración de retención en la fuente o quien encargado de recaudar tasas o contribuciones públicas no las consigne dentro del término legal, incurrirá en prisión de cuarenta y ocho (48) a ciento ocho (108) meses y multa equivalente al doble de lo no consignado sin que supere el equivalente a 1.020.000 UVT.

    En la misma sanción incurrirá el responsable del impuesto sobre las ventas que, teniendo la obligación legal de hacerlo, no consigne las sumas recaudadas por dicho concepto, dentro de los dos (2) meses siguientes a la fecha fijada por el Gobierno Nacional para la presentación y pago de la respectiva declaración del impuesto sobre las ventas.

    Tratándose de sociedades u otras entidades, quedan sometidas a esas mismas sanciones las personas naturales encargadas en cada entidad del cumplimiento de dichas obligaciones.

    Ante esa circunstancia cualquiera que inicie una nueva persona jurídica o quiera "cumplir alegremente con los aportes a la nómina de los congresistas" queda mágicamente obligado a retener y de no retener el estado  te cobrará con la cárcel.

    ¿NO MÁS REMEDIO QUE HACER BILLETES?
    El artículo de la omisión del agente retenedor nos hace preguntarnos ¿bueno y cuándo sería la fecha en la que se generaría este delito? Pues la respuesta mágica es ¿desde cuándo tengo que hacer la retención o cobrar el IVA? Pero ¿cuándo es eso? Resulta que tenemos que acudir a la teoría de la "causación". ¿En qué consiste eso de la causación? El momento en el cuál surge un derecho. La teoría de la causación no está mal, pero que se genere un derecho a mi favor o una obligación en mi contra no implica... BILLETES EN EL BOLSILLO. ¿Y cuándo se causa una retención o un IVA? Esto es lo más interesante del asunto...

    Si uno mira el artículo 437 del Estatuto Tributario la regla general consiste en que el Impuesto Sobre las Ventas se causa en cualquiera de los dos primeros casos:

    • Pago
    • Al momento de la facturación o abono en cuenta (causación).
    Si la facturación se da primero, en el caso del impuesto sobre las ventas, ya la empresa que cobra el IVA tendrá una deuda en dinero que tendrá que pagar en la declaración siguiente, así el deudor se demore en pagar la factura. 

    Lo mismo sucede en el caso de la retención en la fuente, la regla general es la misma, se retiene o al momento del pago o al de la causación (abono en cuenta). Para eso puede observarse el artículo 392 del Estatuto Tributario que consagra exactamente la misma idea de la causación. Adicionalmente, esto ha sido reiterado en conceptos de la DIAN ¿cuándo se ocasiona la retención?: 

    "Momento de causación de la retención en la fuente Tal como lo establecen las disposiciones del Estatuto Tributario y lo ha precisado la doctrina de la DIAN (Conceptos No 008054 y No 095988 de 1998, entre otros), la retención en la fuente a título del impuesto sobre la renta debe efectuarse, por regla general, en el momento del pago o abono en cuenta, lo que ocurra primero. Se entiende por "pago" la extinción total o parcial de una obligación mediante la prestación de lo que se debe y por "abono en cuenta" el reconocimiento contable de una obligación independientemente de su cancelación o pago." (Concepto 003580. 12 de Enero de 2006. DIAN. En http://actualicese.com/normatividad/2006/Conceptos/Enero/003580-06.htm Consulta 17/4/2012)

    Esto se puede resaltar en cualquier portal de información contable:
    "La contabilidad en Colombia, según el decreto 2649, opera bajo el sistema de causación, lo que significa que los hechos se deben reconocer al momento de surgir la obligación o el derecho, aunque no se haya hecho o recibido el pago." (Gerencie.com. Retención en la fuente en operaciones de la misma fecha con un mismo proveedor. En http://www.gerencie.com/retencion-en-la-fuente-en-operaciones-de-la-misma-fecha-con-un-mismo-proveedor.html Publicado el 20/12/2010. Consultado 17/05/2012)
    Es decir, así uno no haya recibido el dinero o no tenga con qué pagar, mágicamente su cuenta tiene que tener billetes a la hora de las declaraciones de retención y de IVA. En términos de derechos y obligaciones, quizás esa teoría de la "causación" esté bien, pero es demasiado teórica a la hora de afrontar la realidad.

    Causar una obligación a su favor no implica tener esa obligación en efectivo. De hecho, tenerla causada significa precisamente que no se ha utilizado un bien líquido llamado dinero que la cancele. El poder liberatorio del dinero implica eso, la capacidad de cancelar las obligaciones causadas.

    Pero ¿cómo si no se ha cancelado la obligación mágicamente el contribuyente va a tener dinero para pagar la declaración? Esta tesis de la causación desconoce la realidad de los negocios en Colombia, donde la puntualidad en el cobro es rápida (o sea se factura rápido) pero el pago es lento. Así las instituciones tienen el reto de enfrentar una "cartera" morosa de obligaciones "causadas" que generan IVA. Sin embargo, mientras el deudor se demora en cumplir, no puede quien cobra el IVA sustraerse de su obligación de pagar con dinero que no ha entrado en su flujo de caja. 

    UN CASO TÉTRICO
    La omisión del agente retenedor se ocasiona dos meses después de causada la obligación. Imaginemos en el normal tráfico jurídico un IVA causado en Abril, cuya declaración ha de pagarse los primeros días de mayo y el deudor se ha demorado en pagar (porque a su vez a él le han incumplido), ya si la mora llega a los primeros días de Julio y el Agente recaudador del IVA no ha podido pagar ya ha cometido omisión del agente retenedor. Para ir a la cárcel se requiere que concurran otros dos factores aparte de describir la conducta en el artículo, "antijuridicidad" y "culpabilidad", la defensa es amplia... empezando por la ridiculez de la irrealidad del legislador, pero en todo caso las vueltas, las llamadas de la DIAN, entre otras dudo que sean agradables. Y casos así conozco bastante cercanos...

    DAR DEL AGUA QUE NO TENGO.
    Para que se comprenda el tema del "flujo de caja", podemos comparar el dinero con el agua que fluye. Si yo le digo a otro "lléneme este balde" y el otro va a buscar el agua, no puede un ladrón pedirme el agua que no tengo simplemente porque "ya se causó la obligación de traer agua". ¿De dónde va a sacar el agua? ¿De la humedad relativa del ambiente? ¿Escupiendo? ¿Robando? El dinero, como cualquier bien, está sometido a una serie de reglas y como tal su movimiento depende de la sencilla realidad de recibirlo.

    Es claro que en materia dineraria se puede acudir a la figura del crédito y al contrato de factoring que sirve para resolver esos casos "tétricos". Pero acudir al crédito implica una pérdida, sacar del dinero que no tengo, pagar luego intereses por una obligación sin sentido o que implicaba "causación".

    EL EXTREMO DEL ABSURDO, EL PRINCIPAL ASESINO DEL FLUJO.
    El leviatánUna de las retenciones más ridículas es la que se conoce como el IVA teórico, o mal llamado "rete-iva", el término correcto es la asunción del IVA en el régimen simplificado. Resulta que en el IVA hay dos clases de regímenes, el régimen común y el denominado régimen simplificado. Sin embargo, el régimen simplificado debería llamarse más bien "régimen complicado" y es que es bastante complicado. Los agentes del régimen simplificado no tienen que pagar el IVA, pero eso no implica que el estado no desee recibir algo de aquella operación. 

    Resulta que por arte de magia un genial legislador (que si trabajara para otro sector tendría la denominación de estafador) se le ocurrió que los responsables del régimen común paguen el IVA que no recaudan los del régimen simplificado. Es así como el artículo 437- 1 del Estatuto Tributario en su numeral 4 manda a que los contribuyentes hagan magia y de la buena reteniendo el IVA en operaciones con régimen simplificado. Pero no es que se lo descuenten a la persona perteneciente al régimen simplificado: ¡HA DE PAGARLO ÍNTEGRO! 

    Y ha de seguir la misma teoría de la causación. Aunque si bien es cierto, este es descontable de la declaración del IVA (vaya enredo) tiene que pagarlo cada que haga un contrato con el régimen simplificado y supere los topes legales. Es decir, si soy del régimen común y causo una deuda con una persona del régimen simplificado, así no haya recibido el flujo con el que le pagaré, no solamente debo retener del flujo de caja que no tengo, sino sacar dinero adicional a lo que me están cobrando. 

    Aunque la situación final del "contribuyente" quede en cero, es preferible no pagar nada y luego no recibir nada a cambio que pagar lo que no tengo para luego descontarlo. Además, se paga cada mes la declaración de retenciones, pero el IVA es cada dos meses luego el estado tendrá esos recursos un mes ¿me pagará intereses por ello? ¡NO! Pero en cambio al "contribuyente" sí le tocará pagar por el precio de contar con dinero antes: ¡Valor anticipado! ¿No es evidente quién se enriquece a costa de quién?

    CONCLUSIÓN.
    Sin perjuicio que lo mejor es que no existieran impuestos pues no tienen causa, las complicaciones del mismo aumentan tanto los costos de transacción empresarial que hacen más ineficiente la actividad económica como consecuencia de ello. Una de las cosas más ineficientes es la forma en la que afectan el flujo de caja empresarial en especial en lo que se refiere al IVA y a la retención en la fuente. El dinero, como el agua o el aire, fluye de una forma natural de acuerdo al tráfico de los negocios humanos. Estas formas tributarias lo que hacen es desconocer la forma como circula el dinero en la sociedad para aumentar su calidad tributaria, generando un aumento innecesario en los costos de generación de flujo de caja en las empresas.

    No me gusta la palabra conclusión pero sino la sociedad no entiende. Lo que quisiera es seguir criticando el sistema tributario a ver si algún día desaparece. Más aún esto lo que debería es oxigenar de alguna manera el debate de la reforma tributaria que propone el gobierno de "Prosperidad democrática". Un mínimo sería que desaparecieran todas esas ideas absurdas de retención en la fuente que cargan al "contribuyente" con obligaciones ridículas por las que no recibe nada a cambio.







              Â¿QUÉ PASA SI HACEMOS BILLETES?        
    En el artículo  Â¿LA POBREZA PROVIENE DE LA FALTA DE DINERO? sembramos la inquietud de cómo el dinero no implica pobreza ni riqueza sino su medida. Sin embargo, explicamos qué pasa si hacemos billetes. El niño propuso como solución hacer billetes y... Keynes le hizo caso. Quizás me digan que degrado a Keynes considerándolo que promovía la misma solución del niño, la verdad es que no, promovía el control de la "oferta monetaria" para influir en la "demanda agregada"... no promovía hacer billetes, promovía un sinónimo. 

    Pero ¿cuáles son las consecuencias de hacer billetes? Prendamos la maquinita y experimentemos. Las consecuencias anticipo son dos, la primera se llama inflación, la segunda se llama hurto mediante la mutación de la moneda.

    INFLACIÓN
    La inflación es la pérdida del poder adquisitivo del dinero por el aumento de los precios. Es que el valor del dinero también está sometido a las reglas de exceso y la escasez, escaso vale más por lo que los precios bajan, si vale menos por tanto los precios suben. Ya esto lo había descubierto Domingo de Soto como nos lo cita José Alpiniano García en su tesis doctoral:

    "La falta de dinero en un lugar determinado hace que el precio de los demás bienes descienda, y la abundancia de dinero hace que el precio suba. Cuanto menor es la cantidad de dinero en un sitio, más aumenta su valor y, por tanto, ‘caeteris paribus’, con la misma cantidad de dinero se pueden comprar más cosas”.  (DE SOTO, 1968, pág. 543).
    Es que como decíamos en Â¿POR QUÉ SURGE EL DINERO? el dinero vale en la medida en que  puede cambiarse por otra cosa, además que la compra es el fin de la venta como veíamos en Domingo de Soto citado por García Muñoz. El ejemplo de una persona en una isla con un millón de dólares desierta que no puede cambiar por nada muestran como ese dinero no vale nada. ¿Un millón de dólares no valen nada? Sí, en una isla desierta sin poderlos cambiar por nada. 

    Eso pasa si hacemos billetes. La cantidad de bienes producidos será exactamente la misma, pero con más billetes éstas valdrán mucho más. Es sencillo, si tenemos 100 unidades de productos por 100 unidades monetarias, esos 100 productos pueden cambiarse por las 100 unidades monetarias. Pero si por esa misma cantidad de unidades tenemos 200 unidades monetarias, todas esas 100 unidades valdrán el doble. 

    EL ROBO CAMUFLADO.
    Una de las formas que utilizan los estados para reducir sus déficit fiscales de todas las absurdas promesas que hacen los políticos, es prendiendo la maquinita. Es en últimas si no hay plata ¡hagamos billetes! Aparte que esa situación aumenta el precio que tienen que pagar las personas por las cosas, genera que el porcentaje de poder adquisitivo que tienen los particulares sobre los bienes se reduzca y el de los estados:

    Si hay 100 unidades de cambio por 100 bienes y servicio y el estado produce 60 para "aumentar la demanda agregada" ahora por cada unidad de bienes ya no habrá 1 unidad de cambio, sino que se requerirá 1,6 unidades de cambio para adquirir un bien. Pero que implica eso, que si las unidades de cambio pertenecían al 100% antes de la emisión de dinero, ahora tenemos que el estado será dueño del 37,5% de las unidades de cambio y los particulares del 62,5%. Lo que palabras más palabras menos significa un robo muy sofisticado...: la mutación de la moneda. (TORO RESTREPO, 2010)

    Sin embargo, una mejor explicación al respecto puede encontrarse en (GARCÍA-MUÑOZ, 2001, pág. 151 a 155). Además, las denuncias sobre estos temas ya se hicieron por los escolásticos españoles, en especial Juan de Mariana en su libro sobre la mutación de la moneda que he buscado pero no lo encuentro. En todo caso sí encuentro la descripción del libro en uno de los artículos del excelente Instituto español que lleva su nombre. Este libro: 



    "comienza en sus dos primeros capítulos explicando con firmeza que “el Rey no es dueño de los bienes particulares de sus vasallos”, por lo que, lógicamente, conforme a derecho y justicia, debe “tomar el beneplácito del pueblo para imponer en el reino nuevos tributos y pechos”. En seguida derivará su argumento hacia lo que constituyó el objetivo de ese librito: criticar la alteración monetaria que practicaba el gobierno de Felipe III por ser causa directa de subida de los precios; juzgando inmediatamente (con enorme perspicacia) que tal inflación era injusta por ser un impuesto oculto, no votado en las Cortes." (GÓMEZ RIVILLAS, 2010)
    ¿Por qué es robar? Es simple, si una persona me quita mi dinero me está quitando mi poder adquisitivo, pero pueden quitarme mi poder adquisitivo dejándome mi dinero. En últimas no se roba dinero, porque como hemos visto el dinero vale es en su capacidad de cambio por otra cosa, por eso se hurta poder adquisitivo. En el ejemplo citado vemos cómo el estado, mediante la impresión de moneda, redujo el poder adquisitivo de las personas en un 62.5%, si una persona se los hubiera quitado habría generado el mismo perjuicio y el mismo enriquecimiento injusto.


    LA FORMA QUE UTILIZAN LOS PARTICULARES PARA "HACER BILLETES".
    Sin perjuicio de la falsificación de la moneda, que también es un hurto similar a producir más dinero, los particulares también tienen sus formas de hacer dinero. Obviamente no somos el Banco de la República o Banco Central para hacer billetes, algo que sería tentador, pero sí tenemos el acceso al crédito que no podemos pagar. El crédito no es malo en sí mismo, muy por el contrario es una forma de garantizar la liquidez de las empresas, pero el crédito de consumo (que no genera riqueza) puede utilizarse como una forma de autoengañarse gastándose los recursos que no se tienen.

    A mi modo de ver, un crédito válido y viable es aquel que puede garantizarse con otra cosa que es el objeto del crédito. Es decir, un crédito debe garantizarse o apalancarse con aquello objeto del crédito. De esa forma, mediante el apalancamiento el balance permanece intacto pero se aumenta la liquidez, a futuro generará pérdida si no se paga, pero si se paga puede ser una forma de mejorar el balance. Pero cuando se accede a un crédito de consumo el balance no queda igual, sino que, como se trata de bienes de consumo, el balance queda en negativos. 

    En Colombia el crédito de consumo es mayor inclusive que el de vehículos (que es una forma de crédito de consumo), vivienda o educación. Al respecto veamos lo que dicen los expertos de Investigaciones Económicas de Bancolombia en uno de sus editoriales:


    La cartera del sector financiero llegó a 177 billones de pesos en junio de 2011, habiendo crecido 11.5% frente a diciembre de 2010. En ese mismo periodo la cartera de consumo creció 14.7% y alcanzó los 52.2 billones de pesos, un 29.5% de la cartera total (un año atrás representaba el 28.7%). En todo 2010 el monto de deuda en consumo aumentó 6.4 billones, y en los primeros seis meses de 2011 aumentó en 6.7 billones de pesos. Los datos mencionados contrastan con el hecho de que la cartera de vivienda a junio de 2011 creció 11% desde diciembre de 2010, con lo que representa el 11.3%de la cartera total (similar a los últimos tres años), y el monto de deuda en vivienda aumentó 2 billones de pesos en el primer semestre del presente año. 
    Existen varias alertas por el endeudamiento de los hogares. Una de ellas hace mención a cuánto más pueden endeudarse los colombianos sin comprometer su capacidad de pago.  (BANCOLOMBIA INVESTIGACIONES ECONÓMICAS, 2011) 
    ¿Hasta cuándo podremos endeudarnos? El crédito de consumo implica, en muchos casos, hacer lo mismo que hace el estado utilizar un dinero que no representa, ni representará riqueza. De esa manera, la herida en el patrimonio de las personas y de la economía en general genera una inflación. No se trata de unos recursos que adquirí con el sudor ni podré adquirir con todo el sudor a futuro. En otras palabras el mal uso del crédito de consumo me desincentiva de producir y trabajar, que es lo que verdaderamente genera riqueza. De esa forma se disminuye el valor del dinero porque no requiere bienes, servicios o trabajo para producirse. 

    Si somos realistas la cartera de consumo de 52.2 billones de pesos es un indicador que mide los recursos que no tenemos pero que tarde que temprano tendremos que generar. Eso sin contar con los intereses que generan y van a generar. Se preguntan ¿qué genera el ciclo económico y las crisis? ¡Demandar más de lo que podemos dar a cambio por ello!

    INCONCLUYENDO.
    La confusión que la riqueza proviene del dinero nos genera tanto el robo estatal como el deseo desenfrenado de consumir más de lo que podemos ofrecer. El dinero no es la felicidad, la compra hecha dice una frase, pero tampoco será felicidad si ese dinero no lo hemos conseguido a cambio de algo, a futuro será infelicidad. La falsedad de la idea de que el dinero es la riqueza radica en la confusión -originada en Adam Smith- que considera que el origen de los intercambios proviene de la demanda y no de la oferta (GARCÍA MUÑOZ, Derecho y Economía según Tomás de Aquino, Tesis Doctoral, 2011, pág. 34). Y es que, claramente, el dinero está del lado de la demanda, no de la oferta. ¿Será entonces que tenemos que mirar la oferta? ¿Será que es en la oferta donde podremos conocer la naturaleza del dinero? ¿Será que la riqueza proviene de la oferta?

    OTROS ARTÍCULOS

    OTROS ARTÍCULOS

    BIBLIOGRAFÍA


    DE SOTO, D. (1968). De Iustitia et iure (Vol. III). Madrid: Instituto de Estudios Políticos.

    GARCÍA MUÑOZ, J. A. (2011). Derecho y Economía según Tomás de Aquino, Tesis Doctoral. Pamplona, España: Universidad de Navarra. Facultad de Filosofía .

    GARCÍA-MUÑOZ, J. A. (2001). Derecho Económico de los Contratos. Bogotá: Ediciones Librería del Profesional.

    GÓMEZ RIVILLAS, L. (28 de Mayo de 2010). MARIANA Y LOS IMPUESTOS. Recuperado el 28 de Enero de 2012, de INSTITUTO JUAN DE MARIANA: http://www.juandemariana.org/comentario/4625/mariana/impuestos/

    Niño Tarazona, D. I. (11 de Noviembre de 2011). BANCOLOMBIA INVESTIGACIONES ECONÓMICAS. EDITORIAL SEMANAL: EL GASTO Y EL ENDEUDAMIENTO EN LOS HOGARES COLOMBIANOS . Colombia: Investigaciones Económicas Bancolombia.

    TORO RESTREPO, D. (29 de Marzo de 2010). EL MITO DE LA SOBREPOBLACIÓN Y LAS VERDADERAS CAUSAS DE LA POBREZA. Recuperado el 28 de Enero de 2012, de EL ALISPRUZ: http://elalispruz.blogspot.com/2010/03/el-mito-de-la-sobrepoblacion-y-las.html



    PUBLICIDAD EXTERNA



              Â¿LA POBREZA PROVIENE DE LA FALTA DE DINERO?        
    Para un niño es es fácil de creer que la pobreza proviene de la falta de dinero. Si a uno le dicen, "los ricos tienen mucha plata, los pobres poca plata" pues la inferencia lógica sería "pues la pobreza proviene de la falta de dinero". Adicionalmente si uno medio piensa el asunto, podría fácilmente concluir, que el problema se resolvería haciendo billetes para los pobres. Podríamos citar el intento de chiste "había una persona tan pobre, tan pobre que solo tenía plata" para explicar la falsedad de esta situación. Eso sin perjuicio que si el estado produce dinero, prende la maquinita de billetes, lo que está haciendo es una forma muy sutil de robo, como ya lo denunciaba Juan de Mariana en su libro sobre la mutación de la moneda. Una persona con dinero en una isla desierta cabría en el ejemplo del intento de chiste. Efectivamente ¿de qué me sirve tener un millón de dólares si no lo puedo cambiar por comida, bebida, refugio?

    Es así como para responder a la pregunta, la respuesta tajante es NO. La pobreza es la insatisfacción de ciertas necesidades, diferentes para cada persona, en cada situación, contexto. El dinero, en un contexto social, puede cambiarse por cosas que satisfagan necesidades pero no puede hacer que se produzcan esas cosas. Ni la expansión de la oferta monetaria, ni los créditos bancarios, ni nada puede hacerse si nadie produce. Muy por el contrario, si se descubre una forma de vivir -y las personas la acogen- que facilite el intercambio sin dinero y producen mucho, no necesitarán dinero para satisfacer sus necesidades. El dinero es un excelente invento para agilizar los intercambios, pero bien pueden existir otros medios para agilizarlo. Sin embargo, las tesis económicas actuales que se centran en un monetarismo y la centralización de la producción de dinero en los estados convierten al dinero en fin y no en medio. Efectivamente mi querido Keynes, haciendo billetes no vas a calmar el hambre de los pobres, pero sí la perversa avaricia de los gobernantes. 

    ¿ESCLAVOS DEL DINERO?
    La economía actual pretende someter y alienar mediante un exagerado culto al dinero. Es que la ciencia económica actual produce la alienación de la persona humana (Véase GARCÍA MUÑOZ, 2011). La visión económica actual parte de la idea que el ser humano es netamente un número que consumo y que la producción está fatalmente determinada (Véase GARCÍA MUÑOZ, 2011). Adicionalmente, al ser el dinero el medio por el cual se mueve el mercado, pues controlar el dinero en el mercado es una alternativa para que ese personaje adicto al consumo (la persona en su reducida visión) no dañe a los otros consumidores... más bien no deslegitime el poder del estado. Es así como la tesis de derecho y economía del santo de hoy 28 de Enero del profesor José Alpiniano nos centra en un punto esencial: "Esta visión aliena la personalidad humana en tanto que somete al hombre al imperio fatal de algo creado por él mismo: el mercado." (GARCÍA MUÑOZ, Derecho y Economía según Tomás de Aquino, Tesis Doctoral, 2011, pág. 131). Y si el mercado surge de intercambios con dinero, en la actualidad nuestra personalidad humana se encuentra alienada al dinero. 

    Así ve la economía actual
    al ser humano.

    Mediante la oferta dineraria, la producción de billetes, intervenciones macroeconómicas en las tasas de interés, control del aumento de los salarios, el incentivo o desincentivo de créditos para consumo, etc., no vamos a lograr satisfacer nuestras necesidades. De hecho, yo he vivenciado eso en términos prácticos. Una situación económica compleja no se resuelve por más sumas, restas, multiplicaciones o divisiones que se realicen con el dinero que se tiene. Es volver al problema que hablábamos en SOBRE EL DINERO un millón de dólares en una isla desierta no sirven para nada.

    La alienación económica, es decir, la confusión del dinero con la riqueza, se refleja también en el management o administración. Que el dinero al ser medio de cambio de todas las mercancías mida la riqueza no significa que sea la riqueza en sí. Es como decir que un edificio de 30 metros son 30 metros, no es un edificio. Sería como decir que el avalúo de ese edificio, sea ese edificio. Veamos cómo se ve esta problemática en el management.

     De acuerdo con Hamel y Prahalad (Prahalad QEPD es, entre otras, el creador de la idea "mercadeo en la base de la pirámide" que es aplicada, entre otros, por el profesor César Betancourt de la Universidad de la Sabana en el área de mercadeo) el rendimiento de una inversión se explica de la siguiente manera: "Ahora bien, el rendimiento de la inversión (o rendimiento de los activos netos, o rendimiento del capital empleado) tiene dos componentes: un numerador, que es la renta neta, y un denominador, que es la inversión, los activos netos o el capital empleado." (HAMEL & PRAHALAD, 1999, pág. 44). La estrategia común en la mayoría de los directivos es la reestructuración empresarial, ¿en qué consiste? En disminuir el nivel de gastos, costos y generalmente, la primera idea que se le viene a la cabeza a cualquiera -por más socialista que hubiese sido en su juventud- son los recortes de personal. ¿Por qué esta estrategia? Precisamente por un auto-engaño matemático, si recorto lo que pago en salarios podré, en mi división, ver cómo aumentan los rendimientos y en últimas auto-engañarme creyendo que por esto soy más rico. 

    ¿Esclavos de la economía?
    Pero ¿Qué consideran los autores Hamel y Prahalad frente a esa táctica de mejorar los rendimientos? Frente a esto plantean los citados autores lo siguiente: "A pesar de que quizás ha sido inevitable y en muchos casos loable, la reestructuración ha destruido vidas, hogares y comunidades en nombre de la eficacia y de la productividad" (HAMEL & PRAHALAD, 1999, pág. 44). Si una reestructuración pretende mostrar un número que dice que el rendimiento aumenta, pero destruye familias, hogares, etc., ¿no es eso muestra de la tesis central de Alpiniano sobre cómo la economía nos aliena? ¿Aumento de acciones a costa de destruir vidas? No es que la reestructuración sea mala en sí, sino que en muchos casos no es justa. Por ejemplo, cuando se despiden a tres empleados que trabajan intensamente y se deja a un cuarto con ese trabajo por el mismo salario ¿podemos decir que se aumentó la productividad? Dicen Hamel y Prahalad "la gestión del denominador [o sea reestructuración y recorte de personal] es un atajo contable para aumentar la productividad de los activos" (HAMEL & PRAHALAD, 1999, pág. 45). 


    A pesar de que en apariencia los rendimientos aumentan, simplemente por un "atajo matemático", esto no es necesariamente un bien para la empresa: "la reestructuración raramente da como resultado una mejora fundamental de la empresa. En el mejor de los casos sirve para ganar tiempo." (HAMEL & PRAHALAD, 1999, pág. 47). Es así como ese autoengaño bien podía producir efectos al corto plazo, pero no a mediano o a largo plazo en la valoración de las acciones:

    "Un estudio realizado entre dieciséis grandes empresas estadounidenses que llevaban, como mínimo, tres años en reestructuración, reveló que, aunque la reconversión normalmente mejoraba el precio de las acciones de la empresa, dicha mejora casi siempre tenía carácter temporal. Tres años después de iniciar la reestructuración, el precio de las acciones de las empresas encuestadas era, en promedio, incluso inferior a la tasa de crecimiento anterior al inicio del procedimiento de reestructuración."  (HAMEL & PRAHALAD, 1999, pág. 47)

    Sin embargo, no se trata de condenar a la reestructuración, que es una alternativa necesaria cuando en la empresa se forman estructuras injustas que limitan su eficiencia. Por ejemplo, que en una empresa de familia el hijo gerente gana lo mismo que su hermano que realiza una gestión operativa es un claro ejemplo de estructura injusta. En ese caso hay un desorden que no da al aporte del trabajo de cada uno su justa retribución. Además, debe ser posible reestructurar esa estructura injusta. A veces, como en el caso de las fusiones empresariales es necesario tolerar -por un tiempo- esa estructura injusta porque de lo contrario se quebraría y sería más injusto aún con todos. 

    CONCLUSIÓN INCONCLUSA.
    Tanto desde tesis doctorales como del management encontramos que se suele alienar al ser humano a costa de los números de la medida. Confundimos la riqueza con una forma de medirla y por eso, manipulamos su medida en aras de ver mejores resultados. La riqueza no es su medida. ¿Qué es entonces la riqueza? ¿Qué es entonces la pobreza? Para ello escribiremos dos cortos escritos uno sobre cómo el exceso de dinero se utiliza como robo y no genera riqueza y dos sobre lo que es la riqueza.

    OTROS ARTÍCULOS
    1. EL ALISPRUZ : ¿POR QUÉ SURGE EL DINERO?
    2. EL ALISPRUZ : SOBRE EL DINERO
    3. EL ALISPRUZ : ¿QUÉ PASA SI HACEMOS BILLETES?

    BIBLIOGRAFÍA


    GARCÍA MUÑOZ, J. A. (2011). Derecho y Economía según Tomás de Aquino, Tesis Doctoral. Pamplona, España: Universidad de Navarra. Facultad de Filosofía .

    HAMEL, G., & PRAHALAD, C. K. (1999). Compitiendo por el Futuro. En H. B. Press, La gestión en la incertidumbre (R. Aparicio Aldazabal, Trad., págs. 37-56). Bilbao, España: Ediciones Deusto S.A.

    PUBLICIDAD EXTERNA



              Â¿POR QUÉ SURGE EL DINERO?        

    ¿Por qué surge el dinero? ¿Para qué sirve? ¿Cuál es entonces su verdadera naturaleza? En  SOBRE EL DINERO iniciamos una serie de inquietudes acerca de la naturaleza del dinero. El dinero es algo bueno, muy bueno porque puede cambiarse por cualquier cosa útil, sin embargo, en la actualidad, desconocer su naturaleza genera muchos problemas, en especial la crisis económica que se cierne como una sombra sobre el mundo.

    EL ORIGEN DEL MERCADO Y EL INTERCAMBIO

    Es complicado cambiar hamburguesas por casas
    o cosas que
     no le interesen a esta mujer.
    El ser humano primero era nómada y hacía de todo menos vivir bueno. Cada persona, o cada familia más bien, debía protegerse, buscar alimento, refugio, sanarse, pasar la enfermedad, entre otras, solo. Esa situación en términos biológicos era una desventaja notoria. Una desventaja que impedía la supervivencia. ¿Entonces Rousseau se equivoca en lo del buen salvaje? ¡Efectivamente! El buen salvaje solo es incapaz de satisfacer por sí mismo todas sus necesidades lo que reduce notablemente su vida.

    Un día, unas personas inteligentes, se dieron cuenta. Él es bueno para cazar, yo para arar la tierra (bueno realmente no existía el arado), aquel para hacer protectores para el frío. De esa manera si uno hacía una cosa más veloz que otro, y el otro a su vez más veloz que aquel, pues, en vez de que cada uno intente hacer todas sus labores al tiempo ¿no es mejor que el que las hace más rápido lo haga por mí y yo haga por él lo que él no es capaz de hacer más rápido que yo? Así si uno recogía 10 frutas por día y hacía 2 empaques para conservarla al día y el otro producía 10 empaques para conservar el alimento y recogía 2 frutas. ¿Por qué no se dedica uno a hacer empaques para conservación y el otro a recoger frutas? ¡Eso fue lo que hicieron! Ese fue el origen de la economía y de la ciudad y ya lo comprendía Sócrates desde tiempos inmemoriales:

    SÓCRATES: Pues bien la ciudad nace, en mi opinión, por darse la circunstancia de que ninguno de nosotros se basta a sí mismo, sino que necesita de muchas cosas. ¿O crees otra la razón por la cual se fundan las ciudades?

    ADIMANTO: Ninguna otra

    SÓCRATES: Así, pues, cada uno va tomando consigo a tal hombre para satisfacer esta necesidad y a tal otro para aquella; de este modo, al necesitar todos de muchas cosas, vamos reuniendo en una sola vivienda a multitud de personas en calidad de asociados y auxiliares y a esta cohabitación le damos el nombre de ciudad. ¿No es así? (Platón, pág. 55: 369 B).
    Sin embargo, surge un problema. Tenemos en la comunidad una persona que hace chorizos y otra que construye casas. Si el que hace chorizos ofrece un chorizo por la casa, quizás el constructor le conteste "para construir una casa necesito más alimento que un simple chorizo", entonces el que hace chorizos le contestará "me importa un chorizo...", bueno, no le contestará eso. El que hace chorizos seguramente le contestaría que podría darle 100, 1000, los que sean, pero mientras tanto el que construye requerirá comida (además de chorizo), vestidos para protegerse del frío, etc., y con chorizos no podrá intercambiar todas sus necesidades. De la misma manera si recibiera muchos chorizos, es probable que el zapatero sea vegetariano que su medio de pago sean casas o chorizos le importe "un chorizo".

    De esa manera, la ciudad, comunidad, foro, plaza, constituye, de forma "consuetudinaria" un medio de cambio. Es así como originarse de una práctica consuetudinaria y ser medio de cambio son las dos características referentes al dinero.

    CARACTERÍSTICAS DEL DINERO
    ¿Qué implica que sea medio de cambio? Esto quiere decir que es el estándar o lo que mide un determinado intercambio. Es decir, el dinero es algo que puede cambiarse por todas las cosas, por todos los bienes o servicios. Es así como uno vende, pero para tener la libertad de intercambiar lo que quiera, no se vende por dinero porque nos pasaría lo de la isla desierta: ¡no serviría para nada! Con acierto sostuvo Domingo de Soto que se vende para recibir dinero y comprar de lo que falta sin compromiso de tener que recibir del comprador aquello que no necesite: “vendido lo que le sobra de una cosa, compra lo que de otra le falta (…) la compra es el fin de la venta”  (DE SOTO, 1968, pág. 593). El profesor José Alpiniano García Muñoz, en una tesis doctoral recientemente defendida en la Universidad de Navarra, nos aclara esta frase en relación al tema del valor del dinero "En consecuencia, quien vende no tiene como fin el dinero, sino la compra o adquisición de otra cosa que le falta." (GARCÍA MUÑOZ, 2011, pág. 28). La razón de ser del dinero no es otra pues que facilitar los intercambios de cosas realmente necesarias para cada persona. En otro libro del mismo autor se explica con más claridad este punto: "Como se dijo antes, el papel moneda sólo tiene razón de ser en la medida en que, por decirlo gráficamente, represente una cantidad o servicios, esto es, su razón de ser es su valor de cambio objetivo; el dinero vale toda la cantidad de bienes o servicios que puede obtenerse a cambio de él." (GARCÍA-MUÑOZ, 2001, pág. 148).

    Bolívar. Moneda Venezolana.
    El gobierno ha intentado avaluarla mediante sellos,
    pero es la mejor muestra que el valor del dinero
    nace de la costumbre.
    Adicionalmente el dinero se caracteriza por ser consuetudinario ¿Por qué consuetudinario? Porque es una costumbre, las personas se acostumbran a que esa cosa sea la medida que utilizan para intercambiar las cosas. Sin embargo, no faltan en la vida ciertos personajes que se dan el lujo de hacer dinero. Antes el oro y la plata eran los medios de cambio, en la actualidad, los estados se inventan el cuento que el dinero vale porque es hecho por ellos. Es así como surge el cuento del curso forzoso. Es así como si uno se encuentra del lado Colombiano de la frontera con Venezuela entre Villa del Rosario (Norte de Santander) y San Antonio del Táchira  y va a comprarle a un Venezolano tendría que hacerlo en pesos. Sin embargo, es precisamente en zona de frontera donde se observa lo ridícula que es su existencia. El Venezolano podría recibirle en pesos si quisiera, o únicamente recibirle en el tan "revaluado" Bolívar (moneda de Venezuela). Es que Chávez tiene el poder de producir un Bolívar "fuerte". En San Antonio del Táchira es usual que se reciban pesos como intercambio y en Cúcuta que se reciba el tan "revaluado" Bolívar. Adicionalmente, nada obstaría para que recibieran pesos, dólares, dólares canadienses, euros, yens, o tres vacas, un kilo de oro o una libra de sal. En todo caso, se acostumbra a recibir en una moneda determinada, en un "país" (en su sentido geográfico) determinado.

    Un ejemplo de que el dinero se utiliza de forma consuetudinaria es el uso del dólar estadounidense en Ecuador. ¿Por qué si es un billete que únicamente tiene cambio  curso forzoso en los EEUU? Pues porque es una costumbre. Citado por el profesor José Alpiniano, Domingo de Soto, hace ya varios siglos nos decía:  “aunque la moneda no estuviera sellada, tendría el mismo valor en el precio de las cosas”. (DE SOTO, 1968, pág. 585). Es así que si un día en Colombia o en el mundo decidiéramos cambiar nuestro "medio de cambio" por cualquier otro medio de referencia, nadie podría impedirlo...

    Es imposible en Colombia que nos inventemos un medio de cambio diferente al peso, dada nuestra mentalidad legalista y con nuestro arraigado culto al estado. Como diría Fernando González estamos sometidos al "espíritu" de Santander que consideraba que la ley era la causa de la libertad. Sin embargo, en la edad media, al resurgir del comercio, el medio de cambio era bastante escaso y el tránsito inseguro por lo que acudieron a diversas vías como el renacimiento del crédito o el contrato de cambio trayecticio (GARCÍA MUÑOZ, TÍTULOS-VALORES. RÉGIMEN GLOBAL, 2008, pág. 23 y siguientes).

    CONCLUSIONES
    El dinero -o medio de cambio- nace como una necesidad para facilitar los intercambios estandarizando los precios de las cosas. No proviene del estado su valor o legitimidad, sino que proviene de los individuos que utilizan cierta cosa o documento para hacer sus intercambios. Eso se denota incluso cómo los individuos en momentos de escasez de un determinado medio de cambio inventan o crean figuras para facilitar el intercambio a pesar de ello.

    OTROS ARTÍCULOS


    1. EL ALISPRUZ : SOBRE EL DINERO
    2. EL ALISPRUZ : ¿LA POBREZA PROVIENE DE LA FALTA DE DINERO?



    BIBLIOGRAFÍA

    DE SOTO, D. (1968). De Iustitia et iure (Vol. III). Madrid: Instituto de Estudios Políticos.

    GARCÍA MUÑOZ, J. A. (2011). Derecho y Economía según Tomás de Aquino, Tesis Doctoral. Pamplona, España: Universidad de Navarra. Facultad de Filosofía .

    GARCÍA MUÑOZ, J. A. (2008). TÍTULOS-VALORES. RÉGIMEN GLOBAL. Bogotá D.C, Colombia: Temis S.A.

    GARCÍA-MUÑOZ, J. A. (2001). Derecho Económico de los Contratos.Bogotá: Ediciones Librería del Profesional.

    Platón. La República (Versión en PDF ed.). www.planetalibro.com.ar.





              SOBRE EL DINERO        
    Uno de los problemas tanto de la avaricia como del derroche en el que caemos algunas veces es desconocer lo que es realmente el dinero. ¿Qué es el dinero? En primer lugar el dinero es un BIEN. El dinero no es algo malo como muchos creen, el dinero es necesario. Pensar que el dinero es algo malo es un error rotundo en la naturaleza misma del dinero.

    Si el dinero no es malo ¿por qué es mala la avaricia?  He allí el punto, el dinero no hace malo al hombre, lo que pervierte al hombre es desconocer su naturaleza. Digo esto porque en las ocasiones en las que he desconocido la naturaleza del dinero he caído en una tremenda infelicidad, como cuando uno se equivoca. Sí he sido avaro y también derrochador. No en exceso, pero sí por desconocer lo que es el dinero.

    Y ¿cuál es la naturaleza del dinero? El dinero es una cosa inútil. Usted puede comerse un billete y ¿es alimento?  Todos sabemos desde niños que es mejor lavarse las manos después de tomar billetes o monedas. El dinero en sí mismo no sirve para nada. En una selva o en una isla desierta y sin gente, si uno está muriéndose de hambre, de nada servirá tener una maleta con un millón de dólares, bueno quizás para hacer una fogata y dudo del potencial de un billete para encender fuego. Para eso es buena la metáfora del rey Midas que todo lo que toca se convierte en oro, ¡qué hambre! Porque el oro no alimenta.

    Si el dinero es inútil, ¿por qué la gente trabaja por dinero? ¿Cambia una cosa por dinero? ¿lo primero que busca un atracador es dinero? ¿Por qué un banco paga dinero por recibir dinero en depósito y cobra dinero por dar dinero en préstamo?  Â¿Por qué lo que se produce se cuenta en dinero? Pues trabajan, cambian, atracan, especulan y producen cosas ¡inútiles! No, eso no es cierto, el dinero es inútil pero puede cambiarse ¡por cualquier cosa útil!

    Es así como iniciaremos con este una serie de cortas notas para explicar lo que es el dinero y cómo las crisis actuales no se resuelven simplemente porque parten de un desconocimiento de la naturaleza misma del dinero.

    Artículos relacionados

    1. EL ALISPRUZ : ¿POR QUÉ SURGE EL DINERO?
    2. EL ALISPRUZ : ¿LA POBREZA PROVIENE DE LA FALTA DE DINERO?










              CARA MUDAH MEMASANG WIDGET FLAG COUNTER PADA BLOG        

    CARA MUDAH MEMASANG WIDGET FLAG COUNTER PADA BLOG

    Contoh tampilan Widget Flag Counter pada Blog

    KENAPA FLAG COUNTER  PERLU DIPASANG ?


    Flag Counter adalah sebuah program komputer yang menggunakan algoritme untuk menghitung jumlah pengunjung pada suatu web atau blog, yang mendeteksi asal negara pengunjung bog dan menampilkannya secara online berdasarkan IP Address.

    Memasang Widget Flag Counter Di Blog dapat membantu kita untuk mengetahui berapa banyak jumlah pengunjung blog kita serta asal negaranya .  Jumlah kunjungan dan jumlah negara pengunjung dapat kita jadikan parameter perkembangan blog kita.

    CARA MEMASANG FLAG COUNTER PADA BLOG


    Berikut ini Cara Mudah Memasang Widget Flag Counter pada Blog

    Langkah pertama, Klik alamat Situs Flag Counter ini : http://flagcounter.com 

    Setelah diklik, akan tampilform isian seperti ini :


     Form Isian untuk mengatur tampilan Flag Counter pada blog

    Langkah kedua, Mengisi form untuk mengatur tampilan flag counter agar sesuai dengan yang diinginkan dan sesuai dengan format blog.

    Penjelasannya sebagai berikut :

    • Maximum flag to show : jumlah bendara maksimal yang akan ditampilkan (bisa diisi 10 negara atau lebih, sesuai selera)
    • Columns of flag : jumlah kolom (bisa di isi 2, 3, dan seterusnya, tergantung lebar widget yang mau ditampilkan)
    • Label on top of counter : nama dari Flag Counter
    • Background color : warna latar dari Flag Counter
    • Text color : warna tulisan
    • Border color : warna garis tepi dari Flag Counter
    • Show country flag : untuk menampilkan kode negara (jika dicentang icon benera negara pengunjung akan tampil)
    • Show pageview : untuk menampilkan jumlah halaman yang dikunjungi (jika dicentang, jumlah halaman blog kita yang dikunjungi akan tampil)
    • Show Visitor : Menampilkan Visitor (bisa ditampilkan dalam bentuk angka atau persentase)
    • Flag Size : Ukuran Widget Flag Counter pada blog (small, medium, atau large)

    Setelah form tampilan Flag Counter selesai kita isi, akan terlihat preview pada example flag counter with your choices, setelah tampilan sesuai dengan keinginan,
    Klik  >> GET YOUR FLAG COUNTER.

    Kemudian akan muncul form seperti ini :

     Form register Fleg Counter Blog

    Form di atas bisa diisi dengan alamat email kita, atau bisa juga di skip.  Jika kita mengisikan email, data yang sudah terekam di blog kita akan disimpan oleh Flag Counter,  sehingga tidak hilang jika suatu saat misalnya widget kita terhapus tak sengaja karena kita mengganti template blog kita.

    Citra Property Land memilih opsi Skip.

    Selanjutnya akan muncul dua (2) kode HTML,

    Kode yang atas adalah Code for websites (HTML), sedangkan di bawahnya adalah Kode untuk Forum.  Pilih kode yang di atas atau kode for websita (HTML), yang kurang lebih (tergantung isian form) seperti ini :

    ---------------------------------------------------------------------------------------------------------------
      
    <a href="http://s05.flagcounter.com/more/l2P"><img src="http://s05.flagcounter.com/count2/l2P/bg_FFFFFF/txt_000000/border_CCCCCC/columns_2/maxflags_10/viewers_0/labels_1/pageviews_1/flags_0/percent_0/" alt="Flag Counter" border="0"></a>

     ---------------------------------------------------------------------------------------------------------------
    Langkah ketiga atau terakhir adalah Memasang Flag Counter pada Blog.  Memasang Flag Counter copy codenya lalu paste ke widget blog kita.

    Caranya kita masuk ke Dasboard Blog, dan pilih layout atau tata letak.

    Klik Tambahkan Gadget
    Klik Opsi HTML/JAVA SCRIPT
    Paste kan kode HTML Flag Counter yang telah dicopy tadi  pada form nya, kemudian save atau simpan perubahan.


    Selesai.


    Demikian artikel Citra Property Land tentang CARA MUDAH MEMASANG WIDGET FLAG COUNTER PADA BLOG.  

    Semoga bermanfaat






              PAID CCCAM FULL HD         
    Premium CCcam

    PAID CCCAM FULL HD 

    TO RENEW YOUR EXISTING ACCOUNT OR BUY  NEW ONE JUST CONTACT US, USE THE FORM BELOW.
    WE WILL GET BACK TO YOU AS SOON AS POSSIBLE
    We are ready to offer you one of the best server you have ever tried. A lot of packages with a lot of local cards low ecm time. One of the most stable server ever with the best support. You will be convinced for that after testing your server..

    a) 3 Days (test) ==> 1$
    b) 1 Month ==> 5$
    c) 2 Month ==> 9.5$
    $d) 3 Month == > 14 

    For Test 1 $ For 3 days or free download from our Site 

    packages available on the server
     
    BIS TV (13E/5W/19E/12W)

    CanalSat France (19E)

    ORF

    Sky Italia (13E) not available at the moment will update when available

    TNT Sat (19E)

    HD+ (19E)

    ART
    viasat

    Canal+ Nederland (19E/23E)

    MBC HD

    Kabel Kiosk/DigitAlb

    TV Cabo,zon

    Digital+ (19E)(30W/19E),

    SKY Germany/SKY Germany Extra (19E)

    SKY UK (28E)

    TivuSat (13E)

    POLSAT HD Mediaset Premium (13E/5W), Polsat HD, Polsat HD

    DigiTV

    Cyfra+ VOD, Cyfra+ (13E)

    yes (4W)

    Mediaset Premium

    Bulsatcom/39E)

    RTL/UPC Direct (13E/19E/1W), RTL (13E), UPC Direct (1W/19E)

    Polaris (39E)[Deltacom]

    MEO PT DHT (30W)
    pink tv

    SRG Swiss (1

    new one just contact us



    foxyform



              Kendo Grid MVC beforeEdit        

    Hello,

    The only way we can access the beforeEdit Event on a kendo grid is with javascript. shouldnt this be accessible through the Kendo.Mvc.UI.Fluent.GridEventBuilder? attached are just images showing that it errors and that we are using Kendo version 2017.2.621.340 as our dll.

     

    the way we did get it to work is by binding it via javascript with this code (for anyone that wants to know how to get this event to work)

        $(document).ready(function () {
            var grid = $("#BrandsGrid").data("kendoGrid");
          
            grid.bind("beforeEdit", function (e) {
                alert("Before Edit");
            });

        })

    but its weird to have 2 of your events using the grid builder and then 1 of your events bound through javascript makes it easy for a developer to miss that the event exists which can lead to them not fully understanding what is happening upon editing the grid.

     

    Thanks,

    Thomas


              Pass additional parameters to Read ajax datasource method - MVC        

    Hi, 

    is there a way to bind this additional data function

    .Read(read => read.Action("Products_Read""Grid").Data("additionalInfo"))

     

    via javascript?

    So far I have tried it like this:

    headerSchnellsuche.bind("data", function () {
     console.log("Set data");
    });

     

    but without success


              C#/.NET Little Wonders Anthology        

    Originally posted on: http://geekswithblogs.net/BlackRabbitCoder/archive/2016/04/19/c.net-little-wonders-anthology.aspx

    The following is the complete anthology of Little Wonders, Pitfalls, and Presentations.  

    Enjoy!  A new little puzzler will be coming out this week.

    The C# 6 Little Wonders

    The Original C#/.NET Little Wonders Trilogy

    The C#/.NET Little Wonder Sequels

    The Visual Studio Little Wonders

    The C#/.NET Concurrent Little Wonders

    The C#/.NET Little Pitfalls

    The C#/.NET Little Wonders and Little Pitfalls Presentations

    C#/.NET Little Wonders from BlackRabbitCoder

    More Little Wonders of C#/.NET from BlackRabbitCoder

    C#/.NET Little Pitfalls from BlackRabbitCoder

    The C#/.NET Fundaments: Of Lambdas and LINQ Presentation

    Of Lambdas and LINQ from BlackRabbitCoder

     

    Technorati Tags: , , , ,

              Amazon.com Recruiting Event Coming to St. Louis in April        

    Originally posted on: http://geekswithblogs.net/BlackRabbitCoder/archive/2016/03/23/amazon.com-recruiting-event-coming-to-st.-louis-in-april.aspx

    Hey all my friends and readers in the St. Louis area, my team from Amazon is heading to St. Louis to do an in-person hiring event in April!

    Have you always wanted to work in a place that hires and develops the best?  That lets builders be builders?  That has excellent benefits and salary/bonuses?  That has a clear technical path all the way from entry-level developer to architect and beyond?

    If you're a developer who loves to solve problems and learn new skills, and be in an environment that encourages you to learn and grow, this is a great opportunity.

    We will be there in the last week of April (I'll send more information when I know more).  Let me know if you are interested in an interview while we are there and I'll get you in contact with recruiting.

    -Jim


              The Gamma — Visualizing Olympic Medalists        

    Olympic Games are perfect opportunity to do a fun data visualization project - just like New Year, you can easily predict when they will happen and you can get something interesting ready in advance. I used this year's Games in Rio as a motivation to resume working on The Gamma project. If you did not read my previous article, the idea is to build tooling for open, reproducible and interactive data-driven storytelling. When you see a visualization, not only you should be able to see how it has been created (what data it uses & how), but you should also be able to modify it, without much programming experience, and look at other interesting aspects of the data.

    The first version of The Gamma project tries to do some of this, using historical and current data on Olympic medals as a sample dataset. You can play with the project at The Gamma web site:

    Without further ado, here are the most important links if you want to explore how it all works on your own. However, continue reading and I'll describe the most important parts!

    The project is still in early stages and the code needs more documentation (and ReadMe files, I know!) However, if you would be interested in using it for something or you have some interesting data to visualize, do not hesitate to ping me at @tomaspetricek. Also, thanks to the DNI Innovation Fund for funding the project and to the Alan Turing Institute for providing a place to work on this over the coming months!


              Upcoming F# events - learn Suave, FsLab & more!        

    Some people in the F# community have reputation for traveling too much. I do not know how that is possible, but as it happens, I will be visiting a couple of places in June and doing a number of talks, workshops and courses. So, if you are thinking about getting into F#, web development with F# using the amazing Suave library, playing with the new trendy F# to JavaScript compiler called Fable, or learning about the recent features in FsLab and Ionide, then continue reading!

    The map includes all my travels, but not all of the pins are for F# events. I'm visiting Prague just to see my family (even though there is a new awesome F# meetup there) and my stop in Paris is attending Symposium for the History and Philosophy of Programming (although we might still do something with the local F# group too).


              In the age of the web: Typed functional-first programming revisited        

    Most programming languages were designed before the age of web. This matters because the web changes many assumptions that typed functional language designers tak for granted. For example, programs do not run in a closed world, but must instead interact with (changing and likely unreliable) services and data sources, communication is often asynchronous or event-driven, and programs need to interoperate with untyped environments like JavaScript libraries.

    How can statically-typed programming languages adapt to the modern world? In this article, I look at one possible answer that is inspired by the F# language and various F# libraries. In F#, we use type providers for integration with external information sources and for integration with untyped programming environments. We use lightweight meta-programming for targeting JavaScript and computation expressions for writing asynchronous code.

    This blog post is a shorter version of a ML workshop paper that I co-authored earlier this year and you should see this more as a position statement. I'm not sure if F# and the solutions shown here are the best ones, but I think they highlight very important questions in programming language design that I very much see as unsolved.

    The article has two sections. First, I'll go through a simple case study showing how F# can be used to build a client-side web widget. Then, I'll discuss some of the implications for programming language design based on the example.


              Photos Published in Northern Wilds Magazine        

    I had the honor of having some of my photos included in the April 2016 publication of Northern Wilds. the photos are of my visit to the Duluth Junk Hunt's fall 2015 show.



    You can view the full issue here...



    Keep in mind that the spring show is just around the corner...

    JH May 2016, Ad - jpeg
    More info at http://duluthjunkhunt.com...

                      



    Vipassana Meditation

    Vipassana Meditation As Taught By S। N। Goenka in the tradition of Sayagyi U Ba Khin.
    This is the motivated page created for those who wish to learn and practice Vipassana Meditation as taught by S.N. Goenka and his assistant teachers in the tradition of Sayagyi U Ba Khin

    Vipassana, which means to see things as they really are, is one of India's most ancient techniques of meditation. It was taught in India more than 2500 years ago as a universal remedy for universal ills, i.e., an Art of Living. For those who are not familiar with Vipassana Meditation, an Introduction to Vipassana by Mr. Goenka and Questions & Answers about Vipassana are available.

    The technique of Vipassana Meditation is taught at ten-day residential courses during which participants learn the basics of the method, and practice sufficiently to experience its beneficial results।

    There are no charges for the courses - not even to cover the cost of food and accommodation. All expenses are met by donations from people who, having completed a course and experienced the benefits of Vipassana, wish to give others the opportunity to also benefit.
    Courses are given in numerous Meditation Centers and at non-center course locations at rented sites. Each location has its own schedule of courses. In most cases, an application for admission to each of these courses can be made by clicking on a selected one of the listed course dates that appear in the schedule. There are numerous Centers in India and elsewhere in Asia; ten Centers in North America; three Centers in Latin America; seven Centers in Europe; seven Centers in Australia/New Zealand; one Center in the Middle East and one Center in Africa. Non-center courses frequently hold ten courses at many locations outside of Centers as they are arranged by local students of Vipassana in those areas. An alphabetical list of worldwide course locations is available as well as a graphical interface of course locations worldwide and in India and Nepal.
    Vipassana Meditation courses are also being taught in prisons.
    A special 10-day Vipassana course especially for business executives and goverment officials is being held periodically at several centers around the world

    For additional information visit the Website :http://www.dhamma.org/


              Kommentar zu Docs & Demo von Tesla        
    Thank you so much! It works perfect now. I have also removed the "sensors=false" part as suggested by Google's warning: Google Maps API warning: SensorNotRequired: https://developers.google.com/maps/documentation/javascript/error-messages Thank you again! Nice work :)
              Kommentar zu Docs & Demo von b.a.        
    GPX has no style mechanism but you may edit the JavaScript Code to set a default color.
              Kommentar zu Docs & Demo von b.a.        
    Google decided to get an api key for every G-map after june 2016. See announcement: <a href="http://googlegeodevelopers.blogspot.com.au/2016/06/building-for-scale-updates-to-google.html" target="_blank" rel="nofollow">http://googlegeodevelopers.blogspot.com.au/2016/06/building-for-scale-updates-to-google.html</a> To fix this: 1) Create an API key as per instructions here: <a href="https://developers.google.com/maps/documentation/javascript/get-api-key" target="_blank" rel="nofollow">https://developers.google.com/maps/documentation/javascript/get-api-key</a> 2) Edit line 14 in the plugin file wp-content\plugins\google-maps-gpx-viewer\php\load_jsapi.php and append the key parameters "&key=YOUR_API_KEY" as shown here: $params = "sensor=false&libraries=places,panoramio,drawing&key=YOUR_API_KEY" thats it.
              Kommentar zu Docs & Demo von Tesla        
    I was using your excellent plugin but now, since few days ago, it is showing the following error: “Google Maps API error: MissingKeyMapError https://developers.google.com /maps/documentation/javascript/error-messages#missing-key-map-error“js:34:391 Any advice on how to solve it? Thanks and congratulations for the good job!
              Kommentar zu Docs & Demo von b.a.        
    So, request a free API key from <a href="https://developers.google.com/maps/documentation/javascript/get-api-key?utm_source=geoblog&utm_medium=social&utm_campaign=2016-geo-na-website-gmedia-blogs-us-blogPost&utm_content=TBC#api-schlsseltypen" rel="nofollow">google, </a> edit the file "google-maps-gpx-viewer/php/load_jsapi.php" on line 14 you'll find this: $params = "sensor=false&libraries=places,panoramio,drawing" change it to $params = "sensor=false&libraries=places,panoramio,drawing&key=insert-your-google-api-key-here" thats it!
              Kommentar zu Docs & Demo von Digby Maass        
    The maps have stopped working! I've posted on the WP support page: Suddenly the map containers are either blank or show the map but when enlarged the small map goes up to the corner, the rest of the screen fills with a blank, and it is unresponsive. The same on site as on a localhost installation. Error console shows a whole lot of Google js errors: TypeError: 'undefined' is not an object (evaluating '_.Zc.prototype.Db=_.ni(1,_.l("O"))') - common.js:216 js:38TypeError: 'undefined' is not a function (evaluating 'a.set("length",a.j.length)') stats.js:9TypeError: 'undefined' is not a function (evaluating '_.x(l3,_.J)') util.js:30 SensorNotRequired, SensorNotRequired: https://developers.google.com/maps/documentation/javascript/error-messages util.js:30 Google Maps API warning: SensorNotRequired: https://developers.google.com/maps/documentation/javascript/error-messages 22common.js:9TypeError: 'undefined' is not a function (evaluating 'b.getSouthWest()')
              Kommentar zu Docs & Demo von b.a.        
    MS nutzt leider nicht das Standard WMS-Protokoll, sondern ein Proprietäres aber OSM ähnliches. Mit ein wenig Javascript sollte das zu lösen sein.
              Quase uma neném, tesão de ninfeta        

    Trabalhando em uma produtora de vídeo, gravando uma campanha política, sempre é necessário passar por situações inusitadas, por exemplo, cobrir um café da manhã com pastores evangélicos, em que o candidato majoritário recebe a benção(?) dos pastores presentes.
    Em um desses cafés da manhã eu vi ajudando nos preparos das mesas uma bela ninfetinha, uma das bundas mais perfeitas que já vi na minha vida, redondinha, sob uma calça colada, tinha peitinhos pequenos, mas era muito linda. Moreninha, por volta de 1,60m, 44kl aproximadamente, um tesãozinho mesmo.
    Após a gravação, ela veio conversar comigo, disse que ninguém gostava dela, que se achava feia e coisas do tipo, tive que dizer que ela é linda, que os garotos não gostavam dela por serem idiotas.
    Neste mesmo dia, seria complicado qualquer tipo de aproximação maior, portanto, trocamos telefone e no dia seguinte, que estaria de folga liguei e marcamos de sair. Na verdade não era bem sair, e sim, aproveitar que o pai dela trabalharia o dia todo para podermos ficar juntos e “nos conhecermos melhor”.
    Menina novinha, 16 aninhos, tem que ter muita calma para não assustar, então nesse dia e em mais três semanas ficamos apenas em beijos e abraços, e sempre muito bom, aquele beijo macio que só as virgens tem, que inclusive já relatei nos contos anteriores.
    Eis que em mais um dia de folga eu disse que daríamos uma volta, já tinha preparado as coisas em casa, sabia que não haveria ninguém, portanto ela poderia gemer muito, trouxe-a para cá, sempre com muita calma, fomos nos beijando, e depois do quarto beijo comecei a tirar as peças de sua roupa, isso muito lentamente, cada beijo era uma peça, ela fazia o mesmo, tirando minha roupa aos poucos.
    Quando percebemos estávamos os dois completamente nus, deitados de lado, um de frente para o outro, eu bolinando-a e ela sem muita experiência acariciando minha pica, que em poucos minutos estaria completamente enterrado dentro daquela chaninha linda e cheirosa.
    Ficamos assim por cerca de dez minutos, quando eu a deitei com a barriga para cima e lentamente fui descendo, beijando sua orelha, beijando e lambendo seu pescoço, descendo mais um pouco e sugando seus pequenos seios com muito carinho, beijava primeiro um enquanto apalpava e apertava o outro, em seguida trocando, chupando o outro e apertando o primeiro, e continuei descendo, precisa sentir o sabor daquele suquinho maravilhoso e doce que tinha naquela rachinha, e foi o que fiz lambia muito aquela chaninha fechadinha, com poucos pelos, lambia e brincava com seu clitóris, ela só me pedia que não parasse, que estava muito bom.
    Quando percebi que já estava bem preparada fui subindo carinhosamente beijando-a cada milímetro daquele corpinho perfeito, dei-lhe um beijo na boca e pedi que ficasse apenas me beijando, que ela iria adorar aquilo que estava para acontecer. Ela me pediu apenas que fosse com cuidado pois nunca tinha feito, coisa que eu já sabia no primeiro dia que havíamos nos beijado, prometi que tomaria cuidado, e assim o fiz.
    Apontei meus 17,5cm na entradinha da sua chaninha e fiquei brincando com ela, sem enfiar ele todo, apenas com a cabecinha dentro, para deixá-la com mais vontade, não agüentando mais ela disse “para com isso, coloca tudo, por favor” e foi o que fiz, lentamente fui colocando quando eu senti seu hímem dei uma pequena pausa, comecei a beijá-la e forcei a entrada com força mas ao mesmo tempo de forma muito carinhosa.
    Mesmo com todo o carinho que fazíamos ela urrou de dor, gritou muito, pedindo para que eu parasse, eu buscava acalmá-la com beijinhos e aos poucos ela foi sentindo mais confiança e voltei a colocar de forma bem lenta, para poder sentir perfeitamente cada milímetro daquela até então grutinha inexplorada, bombava lentamente, dando de vez em quando uma bombada mais rápida, sempre ao mesmo tempo que a beijava e enfiava minha rola na sua chaninha eu apertava aquela bundinha deliciosa.
    Cada enfiada que eu dava era um beijo gostoso que ela me dava, ela pedia que fizesse sempre gostoso daquele jeito que ela seria minha para sempre. Eu respondia que seriamos um do outro eternamente e que ela teria sempre prazer enquanto me desse prazer. Ficamos nisso por uns 10 minutos, quando eu percebi que estava prestes a gosar, pedi que ficasse de quatro, ensinei a ela como fazer, vendo aquela bundinha linda toda a minha disposição, dei uma mordida bem gostosa em cada uma de suas nádegas, me levantei um pouco e enfiei meu pau todo na sua rachinha maravilhosa.
    Algumas poucas bombadas e eu tirei de sua chaninha e coloquei a cabeça do meu pau na entrada do seu cuzinho, ela assustou, porque suas amigas sempre diziam que doía mais, eu a acalmei dizendo que não iria colocar tudo, e não coloquei mesmo, empurrei a cabeça para dentro do seu cuzinho, dei uma brincadinha tirando e colocando e gosei, gosei muito no cuzinho dela, sentindo minha porra inundando seu anus ela deitou me puxou para sue lado e disse “eu te amo, obrigado por me dar a tarde mais perfeita de minha vida” descansamos alguns minutos e comecei tudo de novo. Gosei 4 vezes praticamente seguidas nesse dia, mas com receio de engravidar uma menina tão nova não gosei nenhuma vez na bucetinha dela. Ficamos juntos por quatro meses e meio, comigo ela aprendeu a chupar, e como chupava gostoso, deu seu cuzinho para mim várias vezes. Era muito bom quando eu ia para casa dela e na frente de sua casa nos trepávamos no carro, ela fazia tudo que eu queria, por isso, mesmo não estando juntos mais, nos amamos, e sempre que é possível marcamos de sair para podermos matar a saudade.
    B – Itaguaí - RJ
              O sitio que Meu Marido Comprou        


    Meu marido comprou um sitio em Boa Esperança, era na ocasião uma aquisição oportuna, sou professora e tinha pedido uma licença médica e estava tratando de colocar o sitio em ordem, meu marido vem no sábado e traz as duas crianças e uma moça que cuida delas para mim trabalhando de babá. Meu marido contratou um moço para caseiro que cuida dos animais e da horta, morando na edícula, casa principal, muito prestativo, jovem e bastante sorridente, me auxiliando nas tarefas rotineiras do jardim e mesmo de casa. Devo esclarecer que sou de família tradicional e casei virgem, meu marido foi meu primeiro homem e nunca pensei em trai-lo, numa quinta feira fui para o sitio sem avisar o caseiro, lá chegando a noite, encontrei o caseiro totalmente nu e bastante bêbado dormindo na varanda da casa. Embora assustada com a cena, devia tira-lo dali, lógo não conseguindo movê-lo e nem acordá-lo, tratei de arrastá-lo para dentro de casa e deita-lo num tapete felpudo da sala, mas ao tentar coloca-lo no sofá escorreguei e caí de cara no seu instrumento, ao encostar no membro quente semi duro me excitei sentido a minha face do rosto queimar, nunca tivera a vista uma péça igual aquela, senti no meio do meu peito uma dor de desejo e me senti molhada, o membro cresceu em minha mão e engrossou ficando duríssimo, caí de boca abocanhando o membro esfomeada até que gozou na minha boquinha e enguli toda a porra, ele então me puxou para cima dele e zonzo começou a beijar e chupar meu pescoço e a no movimento minha fina blusa se abriu e ele tratou de chupar meus peitos que estavam sem sutiã pelo calor.e eu delirei e me ajustei ao seu corpo levantando a minha saia e colocando minha calcinha muito gozada em contato com aquele membro super dotado enquanto o beijava sentido os vapores do vinho engerido, beijava desesperadamente,chupando minha língua de forma a sentir seu pau crescer de encontro com minhas coxas e a buceta na calcinha. Ele sozinho não conseguia nada e tratei de tirar a calcinha e montar naquele membro delicioso que era muito maior que o de meu marido e tratei de monta-lo como uma cavaleira que só de entrar todo, meu deu um gozo inesperado, eu gemia e o sentia forçando minhas entranhas ,até o útero, quando ele agarrando minha bunda com as suas mãos fez Introduzir seu dedo indicador no meu cúzinho e tive mais um orgasmo no contato com aquele dedo grosso e áspero! Fiquei assim cavalgando e gozando até o momento em que senti seu membro aumentar e descarregar em jatos sucessivos na minha bucetinha. Tratei de suga-lo até ficar o mais duro possível e esfreguei meu cúzinho naquela pica maravilhosa mas não consegui enfia-lo pois dobrava ,tratei de coloca-lo todo na menina novamente e tornei cavalgar seu membro sem esquecer de colocar seu dedo grande e grosso no meu rabo enquanto eu aproveitava o movimento sugando meus seios e mexendo no meu grelinho até explodir num orgasmo que me fez gritar de prazer e o moço gozou bem fraquinho como tivesse voltado a dormir. Tomei um banho quente lavando todas as minhas culpas pela traição e me purgando do prazer que escorria com a mangueirinha que mostrava como a minha xota tinha ficado dolorida, aproveitando para lavar minha cabeça e minha calcinha que ficou pendurada no registro do chuveiro. Agora eu tinha consciência de que não seria a última vez que faria aquilo com o caseiro e nem haveria de me preocupar com sua inocência, mas para o meu marido seria segredo absoluto nada acontecera. Jade, a princesa.
              Sexo no Trabalho        

    O que vou contar pra vocês é verdadeiro e não faz muito tempo ocorreu há dois anos. Vou tentar resumir para não ficar tão cansativo espero que gostem e gozem rsrsr. Na época eu Trabalha-va em um local praticamente sozinho e quando menos espera-va, entra pela porta da frente nada mais e nada menos que a minha gostosa amiga . Não era a primeira vez que ela me visitava naquele local, portanto, ela sabia muito bem o que a esperava. Por estar um dia muito frio e chuvoso, ela usava naquele momento um casaco (sobretudo) preto cujo comprimento chegava até ao meio de suas canelas, que já¡ encontravam-se cobertas pelo cano longo de suas botas. Levantei-me o mais depressa possível e fui ao seu encontro onde nos beijamos avidamente. Convidei-a para que se sentasse, no qual ela prontamente aceitou e foi tirando o seu casaco para coloca-lo no encosto da cadeira. Encontrava-se por baixo do casaco em um deslumbre total: A blusa de cor branca, quase que transparente, mostrava os seus volumosos seios por inteiro, pois estavam sem o soutien. Não permanecemos por muito tempo ali sentados, pois, apenas com um olhar, levantamos-nos e fomos direto para os fundos, onde tenho um pequeno deposito de mercadorias. A sala e este deposito são separados por um biombo, o qual, deixa condições de ver se entra alguém pela frente. Em tão, nos abraçamos e nos beijamos loucamente, com as nossas mãos percorrendo todo o nosso corpo. Uma das minhas mãos passeava por baixo da saia, pela sua bundinha e pela bucetinha e a outra pelos seus peitos, enquanto que, ela alisava o meu cacete por cima da calça. . Abaixei a minha calça e a minha cueca até os joelhos, deixando o meu cacete para que ela de cócoras o abocanhasse e fizesse uma gostosa chupeta. Após se deliciar com ele todo em sua boca e sentir que estava em ponto de bala, levantou-se e veio me beijar novamente. Apenas levantei aquela saia e abaixei a sua calcinha o suficiente para que o meu cacete se encaixasse entre o vão de suas pernas. Com a cabeça passeando pela portinha da buceta e massa-geando o seu grilinho, sentia o quanto aquela bucetinha estava ficando encharcada. O meu cacete deslizava naquele li quido viscoso e quente, pressionado pelo elástico da calcinha e pelos grandes lábios, e eu apenas não deixava que ele a penetrasse, enquanto que, tanto eu como ela tínhamos as nossas respirações ofegantes e continuada-mente gemi amos nos ouvidos um do outro. Senti que ela estava gozando pois, deu um longo suspiro e contraiu seu corpo todo. Não resistindo daquele orgasmo que dela desprendia, também não conseguia me segurar mais. Enchi a portinha da sua bucetinha e os fundos da sua calcinha de porra. Foi uma verdadeira gozada nas coxas srsr, que por algumas vezes vale muito e pena mais gostoso do que uma foda mal dada. Fomos ao banheiro, providenciamos uma rápida limpeza e retornamos a sala novamente. Sentei na minha mesa e ela sentou-se do outro lado, defronte a mim. Ficamos conversando sobre varios assuntos por um bom tempo, até que de repente, por debaixo da mesa, sinto o bico de sua bota percorrer pela minha perna, subindo e descendo. Olhei para dentro de seus olhos e ela simplesmente disse-me : sabe o que eu vim fazer aqui? Vim aqui com o propósito de dar o meu cuzinho para você. A ultima vez que eu dei ele, foi para você mesmo naquele Motel. O meu marido não gosta e diz que o cú não foi feito para isso rsrsr, portanto, como eu estava morrendo de saudades de senti-lo novamente dentro de mim e com muita tesão, a não ser que você não queira, não saio daqui sem que você me coma o cuzinho e goze dentro dele.” – Que susto.!!!. Na cara e na lata.!!! Levantei-me imediatamente da cadeira já com cacete duro pela situação criada, peguei-a pelas suas mãos e retornamos ao deposito dos fundos, espalhei umas duas caixas de mercadorias que davam a altura suficiente para encaixar o meu cacete em seu buraquinho, e para mais uma surpresa, ela dirigiu-se a mim com um tubo de KY em suas mãos. Disse-me que já havia planejado tudo antes de sair de casa e assim poderia sentir ele deslizando até o fundo sem sentir dores. Abracei-a e beijei aqueles lábios que ferviam de tesão. Foi logo abaixando e tirando o meu cacete para fazer outra gostosa chupeta. Apóss chupar com vontade, levantou-se e foi virando de costas, encostando aquela deliciosa bundinha no meu cacete. Levantei um pouquinho a sua saia e coloquei-o entre as suas nádegas. Continuei abrasando-a por detrás, mordiscando a sua nuca, até que implorou-me para colocar no seu cuzinho. Pedi que ficasse de joelhos sobre as caixas, levantei o resto de sua saia e fiquei com aquela deslumbrante bundinha toda a minha disposição. Abaixei-me e fui beijando as suas nádegas até encontrar o reguinho que me levaria ao local da loucura. Procurava deixar a li ngua bem em riste e com a sua pontinha, penetrava-a levando-a ao delirio total. Com as pontas dos dedos, massa-geava o seu grelinho durinho de tesão, até que novamente pediu-me para fode-la. Coloquei um pouco do gel em sua entradinha e com o dedo empurrei todo o KY para dentro daquele buraquinho, que piscava sem parar. Aproveitei também para lubrificar a cabeçe do meu cacete que encontrava-se em ponto de estourar. Logo que sentiu a pontinha do cacete encostando na sua entrada, forsou de uma vez e gemeu alto quando a cabeça passou pelo seu anelzinho. Com tudo lubrificado, não houve resistência para que sentisse as bolas do meu saco bater em sua bucetinha. Estava todinho enterrado naquele guloso cuzinho. Ela por si só começou a fazer o vai e vem e pedia freneticamente que a fodesse com toda força que eu tinha. Cheguei a em me preocupar com alguém que pudesse chegar a qualquer momento no local e ouvir todo o escândalo que ela fazia. Imagine se alguém entra e me pega com o cacete todo enterrado em seu cúzão gostosoº. Iri a ficar numa situação difi cil. Mas continuemos com a minha gostosa e inesqueci vel foda. Parecia que o seu anelzinho estava pegando fogo de tão quente e gostoso. Fazendo uma siririca com um dedo e outro enterrado dentro da sua bucetinha, ela anunciou que vinha vindo o seu gozo. Sentia o seu corpo estremecer todo enquanto o seu cuzinho latejava, piscarva gozava de tesão , meu pinho (18cm)estava todo enterrado na quele RABO delcioso,. num movimento mais lento e cadenciado após ter gozado, pediu-me que enchesse o seu cú de porra, porque ela iria guardar dentro dele e só iria desfazer dela quando estivesse já em sua casa. não aguentei mais e gozei como se estivesse gozando pela primeira vez, devido a quantidade de porra que despejava naquele delicioso frasquinho. Tirei o cacete bem devagar e ela rapidamente colocou a sua calcinha ainda com a porra toda dentro do seu cú, despediu-se com um beijo e foi embora. Mais tarde me ligou dizendo que guardou toda a minha porra ao chegar em casa, para que ela ficasse impregnada na sua calcinha e como já havia tomado seu banho, agora descansava deitada no sofá da sala cheirando a sua calcinha e sentindo o cheiro de porra de alguém que sabia fazer ela chegar as nuvens. Depois dessa, faz um bom tempo que estamos sem nos encontrar, por isso, ainda sinto saudades daquelas visitas. Quero conhecer uma mulher de preferencia casada, safadinha somente para bons momentos ,( Tenho o desejo de desflorar um cuzinho virgem claro feminino) sou de SP Capital . algomaissp@yahoo.com.br
              MINHA PRIMA ME INICIOU NO BI        

    Tenho apenas vinte anos de idade, mas sou o tipo de garota bem safadinha. Adoro transar, seja com homens, mulheres, casais ou em grupo.O que importa para mim que sou do tipo completinha, é eu gozar muito e fazer o mesmo com o meu parceiro ou parceira. Perdi a minha virgindade quando eu tinha dezesseis anos,foi com um namorado cinco anos mais velho que eu, mas que soube conduzir toda relação com muita cautela e fez-me mulher de uma forma que jamais esqueci, já que foi uma experiência bastante satisfatória e muito prazerosa. Daí pra frente, transávamos quase todos os dias e eu cada vez queria mais e mais, até que passei a pular a cerca e transar com outros homens também, pois minha xana e meu cuzinho, assim como a minha boca, almejava cada vez mais por uma rola grande e grossa preenchendo os espaços. Em suma, tornei-me uma viciada em sexo, mas até então somente com homens. Portanto no dia que eu estava completando dezenove anos, minha prima que já tinha vinte, conversávamos no meu quarto abertamente sobre namorados, transas, etc, foi quando ela perguntou-me se eu já havia transado com mulher. Disse-lhe que não e não sei se gostaria, pois eu adorava sentir um tarugo bem grande me invadindo as entranhas. Ela insistiu no assunto e perguntou-me se eu nem curiosidade sentia pra saber como era. Disse-lhe que curiosidade eu tinha sim, já que amigas minhas do colégio experimentaram e algumas gostaram e confidencie-lhe que um dia quase aconteceu com uma amiga de sala. Minha prima então perguntou, se de repente pintasse uma chance se eu toparia, respondi que talvez, dependendo com quem fosse e antes que eu pudesse falar mais alguma coisa, ela segurou minha cabeça e lascou um beijo em minha boca. A principio fiquei estática, e como não reagir, ela empurrou meu corpo na cama e veio por cima, beijando-me sem parar e acariciando minha nuca. Percebendo que eu ficara meio ofegante, ela começou a apalpar meus seios e bunda e não levou muito tempo para alcançar minha calcinha, que já estava toda molhadinha, tamanho a satisfação que eu sentia. Percebendo meu estado, ela sugeriu que tirássemos nossas roupas, então foi até a porta do meu quarto, trancou-a e deixou cair o vestidinho que usava, ficando só de calcinha. Eu não reagia, mas instintivamente, retirei minha blusa e saia e também fiquei só de calcinha. Ela então se aproximou, segurou minha mão e fez-me acariciá-la, ao mesmo tempo que me acariciava também. Minutos depois estávamos aos beijos novamente e nos tocando mutuamente já totalmente despidas. Deitamos na cama e começamos a roçar nossas xotas, a dela bem peludinha, ao contrário da minha que tinha poucos cabelos. Ficamos ali deitadas nos roçando por um tempo até que ela desceu sua boca, até chegar na minha xotinha que estava completamente melada e começou a me chupar, como poucos homens fizeram. Um tremor tomou conta do meu corpo e entre gemidos e pedidos para que não parasse, gozei fartamente na boca dela. Foi um prazer e tanto e a primeira vez que gozei com alguém me chupando. Vendo a minha satisfação, ela deitou-se e pediu para que eu a chupasse também. Embora fosse minha primeira vez com uma mulher, não hesitei e cai de boca naquela xota peludinha, chupando-a e introduzindo minha língua, até fazê-la gozar na minha boca também. Daí nos abraços e ficamos nos beijando e nos acariciando até que meu telefone tocou e eu levantei para atender. Quando terminei de falar com a amiga que me dava os parabéns, minha prima chamou-me e perguntou o que eu achei do que acabara de acontecer entre nós, eu nada falei, apenas olhei-a nos olhos, aproximei meus lábios dos dela e dei-lhe um beijo apaixonado de língua, que chegou arrepiá-la. Quando parei, ela apenas falou: que bom que gostou e saiba que sempre que quiser é só me chamar. Disse-lhe que iria querer repetir mais vezes sim, e assim continuamos a fazer até os dias de hoje, sendo que além dela, tenho outras amigas que eu iniciei e que já tinham sido iniciadas por outras. Hoje me relaciono bastante com casais, pois adoro sentir uma vara me rasgando o cu enquanto chupo uma buceta. Mas de todas as mulheres que me relaciono ou me relacionei, nenhuma se iguala a minha prima, que a cada relação nossa e linguada dela na minha xana, me faz sentir nas nuvens.
    M.F - Itaguaí - RJ
              Entreguei-me ao meu primeiro amor        

    A história que vou relatar aqui é verídica. Há seis anos atrás eu morava no sitio com meus pais e estudava numa escola rural. Ao terminar o ensino médio fui para uma cidade vizinha, morar com uma tia, onde além de estudar ajudava-a nos afazeres de casa. Meu primeiro beijo aconteceu quando eu tinha dezesseis anos, com meu amigo de escola chamado Fernando (nome fictício), que sempre foi apaixonado por mim, mas que eu sempre ignorei por ser três anos mais velho que eu. Hoje estou com dezessete anos e mesmo morando na cidade grande, com novas amizades, continuo virgem. Certa noite quando cheguei em casa após o colégio, tinha uma carta das minhas amigas que deixei lá no interior, convidando-me para a festa de formatura delas e dizendo-me o Fernando continua apaixonado por mim, pois nunca deixa de querer saber notícias minhas. No dia seguinte escrevi para elas confirmando minha presença e no dia marcado lá estava eu de volta na minha cidadezinha. Minhas amigas estranharam um pouco o meu novo visual e a forma que eu me vestia, muito mais sexy e provocante. Meus pais então nem queiram saber o que eles falaram ao me ver. Passei a tarde com minhas amigas no galpão onde rolaria a festa, ajudando-as na decoração. Lá pudemos conversar sobre tudo, mas o Fernando era o tema principal, pois nos meses que eu fiquei fora, elas contaram-me que ele não namorara ninguém a sério, pois só ficava, certamente para se satisfazer e sempre dissera a elas que continuava me amando. Ouvindo tudo aquilo, não podia deixar de admitir que eu também tinha uma quedinha por ele e talvez fosse até apaixonada, mas nunca admitira, portanto sem falar nada a ninguém, eu também nunca o esquecera e sempre tinhas sonhos e pensamentos eróticos com ele, imaginando-o ser o meu primeiro homem, aquele que iria tirar o meu cabaço e me ensinar as maravilhas do sexo. Já a noite no galpão, a festa tava bombando e eu andava de um lado para o outro procurando pelo Fernando, que ainda não encontrei desde que voltei. As horas iam passando e nada. Fiquei numa aflição, prometendo mil coisas caso ele aparecesse, como já era bem tarde ele num aparecia eu fui dançar e curtir um pouco a festa, e ele nada. Quando foi bem mais tarde, e eu já sem esperanças vi ele chegando, tava ainda mais lindo do que quando o vi na última vez. Nossa, minha buça molhou na hora, minha vontade era de voar em cima dele, mas me contive, e assim a festa ia rolando, e ele nada de me procurar, talvez ressentido ainda pela forma que fui embora sem sequer despedir-me dele. Eu fiquei com o coração na mão e minutos depois decidi ir embora muito triste pois ele ainda não tinha me procurado. Despedir-me das minhas amigas e quando sai da festa ele estava do lado de fora do portão me esperando, e veio em minha direção falando: “preciso conversar com você, pode me ouvir?”, Disse-lhe que sim, mas antes queria um abraço bem forte dele, o que ele não pensou duas vezes em me dar. Disse que estava um pouco cansada, mas que poderíamos ir conversando enquanto caminhávamos. Ele então me acompanhava dizendo: “Porque você fez isso comigo? Você não percebeu e percebi que sou louco por você?, por favor diga-me alguma coisa?” Eu continuava andando sem nada falar, apenas ouvindo-o e quando chegamos na praça, ele se pos na minha frente, me parou, ergueu meu rosto e viu que eu estava chorando, então me abraçou falando: “porque você complica as coisas, eu amo você e sei que no fundo você também me ama. Te desejo desde aquela vez que ficamos juntos, mesmo que por alguns instantes e trocamos nosso primeiro beijo, o qual eu nunca esqueci” então aproximou seus lábios dos meus e me beijou, eu então baixei a guarda, abracei-o e correspondi com muita excitação. Ele disse que não via a hora de sentir meus lábios novamente e eu disse-lhe que eu também nunca esquecera aquele beijo. Continuamos a nos beijar e nas poucas palavras que trocávamos, ele disse saber que eu ainda era virgem e que nunca havia beijado outros rapazes, pois minhas amigas havia lhe dito sobre os meus medos e raiva que eu tinha de homem, devido meus traumas de infância, em seguida fomos para a praça onde não tinha ninguém, nos sentamos em um banco daquele e começamos a nos beijar, ele sabia como me deixar louca, eu não conseguia me soltar, mas ele com sua paciência aos poucos foi me relaxando, para que se eu quisesse me entregar a ele sem receio, ele mordiscava minha orelha, chupava, ia descendo pelo meu pescoço me deixando muito excitada. Resolvi me entregar de corpo e alma a ele, pois sempre sonhara com aquele momento, então comecei a soltar gemidos baixinhos, com vergonha dele perceber como eu estava cedendo aos seus encantos, eu respirava fundo e gemia, ele lentamente desceu sua mão em meus seios, eu delirei quando ele toucou eles pela primeira vez. Ele desceu sua mão até minhas pernas por entre as coxas e foi passando me fazendo gozar pela primeira vez naquela noite, sem ao menos ter me penetrado. Ele percebeu que me fez gozar e continuou a me tocar, em seguida ele devagar passou sua mão em minha xaninha por cima da calcinha, e viu como eu estava super molhadinha, e disse ao meu ouvido: “agora estou domando a minha menina” , então disse a ele: “quero ser sua, me doma” ele respondeu “já esta domada”, e ele me beijou na boca e desceu sua mão até minha xaninha e ficou alisando-a, depois tirou minha calcinha e colocou em seu bolso da calça e me pediu pra abrir minhas pernas, o que eu obedeci sem reclamar, pois eu queria muito que ele me penetrasse, mas não foi isso que ele fez, ele abaixou as alças de meu vestido e levou sua língua lambendo meus seios e depois chupando-os, eu gemia muito, não conseguia me controlar, minha xana estava muito molhada, ele passou sua mão nela enquanto sugava meus seios intumescidos, e eu urrava de desejo, estava como uma mulher vulgar em sua mão, ele voltou a me beijar na boca, com aquele beijo macio e molhado. Então ele abriu o zíper da calça e tirou aquele mastro pra fora e me pediu que eu olhasse para aquilo que seria todinho meu, eu olhei meio tímida e ele levou seu pau até minha boca e disse: “chupa meu pau minha menina, ele é todinho seu, hoje quero ter você por inteira e sem pressa, agora coloca sua boca nele e suga como se tivesse mamando” eu fiz o que ele pediu e meti minha boca naquele cacete enorme, chupei com muita vontade, como se fosse uma puta bem experiente, mas na verdade era a primeira vez que me via com um cacete na boca. Depois disso ele me pegou pelas mãos e disse: - Vamos para a minha casa, lá eu te farei mulher, a minha mulher e se quiser você será minha para sempre. Seguimos para a casa dele. Já na casa dele, fomos direto para o quarto dele, onde logo que entramos ele me virou de costas, beijou meu pescoço, foi tirando todo o meu vestido e continuou me lambendo e beijando nas costas. Então me deitou de bruços na cama e retirou meu vestido deixando-me nuazinha. Em seguida percorreu sua língua em minhas costas até chegar em meu rego e no meu cuzinho, deixando-me enlouquecida. Ele então começou a se despir e já livre das roupas, com aquele cacete duro feito pedra na minha frente, fez-me segurar e colocar na boca, chupando-o novamente. Vez ou outra ele parecia querer me furar a garganta, pois empurrava aquela vara até minha goela, fazendo-me ânsia de vômito. Depois de um tempo,veio por cima de mim, abriu minhas pernas e encostou seu mastro em minha xaninha, me levando a loucura, e ali ficou roçando e me beijando, eu comecei a chorar de prazer e respirar ofegante como se tivesse faltando algo me mim, e ele dizia: “chora minha menina, que agora você vai ser minha pra sempre” e de repente ele forçou a entrada de seu pênis em minha xana enfiando apenas a cabecinha, depois eu comecei a rebolar em seu pau para que o resto entrasse, mas ele retirou seu pau, e eu comecei a gemer alto e entre gemidos eu dizia: vai, por favor, me faz tua mulher, eu quero ser sua e nunca mais vou ti ignorar, não me deixe assim” ele ouvindo o que disse retornou seu pau em minha xana e forçou sua entrada, aquilo queimava minhas entranhas, ele tentou me penetrar mas não entrava, afinal eu ainda era cabaço e eu comecei a chorar de dor e prazer e ele me beijava e voltava e a me penetrar, e não conseguia e eu comecei a falar: “pode meter tudo em mim de uma vez que eu agüento, mas não me deixe sem sentir você, preencha esse vazio que esta entre minhas pernas” ele obedeceu enfiou novamente forçando a entrada, as lagrimas escorriam de meu olhos, mas aquela dor e prazer que eu senti foi enorme, me senti sair do meu corpo, como se fosse desmaiar, ele me beijava, e eu sentia cada centímetro de seu pau rasgando a minha xana, ele enfiou tudo e esperou um pouco para que eu pudesse relaxar e começou num movimento de vai e vem bem devagar, e ao mesmo tempo ele me beijava e segurava meus cabelos fortemente, aquilo pra mim era um sonho. Eu gozei múltiplas vezes insanamente, naquele pau gostoso e ele vendo aquilo todo melado tirou seu pau pra fora e se pos a chupar e lamber minha xoxota, eu me contorcia de prazer até que gozei em sua boca, depois ele meteu seu pau em mim novamente e bombou bem rápido dizendo: “vou gozar minha menina ahhhhhhhhh, você agora é minha mulher, eu ti fiz minha mulher ahhhahhaahhh” e começou a gozar dentro da minha buceta e também sobre ela. Sentindo aquele leitinho quentinho no meu interior e sobre meu corpo, comecei a gemer feito uma alucinada e mais uma vez gozei gostoso. Depois de tudo terminado ficamos coladinho um ao outro com ele fazendo carinho. A sua porra escorria entre minhas pernas, eu passei a mão em minha xana e pude notar que tinha um pouco de sangue pelo meio, ele notou que eu vi e começou e me explicar que aquele sangramento era normal, afinal eu acabara de ser deflorada. Depois de uma meia hora nos limpamos e nos vestimos e ele levou-me até minha casa. No dia seguinte acordei feliz da vida e quando pensei em ligar para ele, o meu telefone tocou e era ele, perguntando-me se estava tudo bem e convidando-me para almoçarmos juntos na pensão de um amigo nosso num bairro vizinho. Disse-lhe que sim. Mas tarde nos encontramos, almoçamos e depois fomos para um hotel onde mais uma vez entreguei-me a ele e desta vez além de minha bucetinha recém desvirginada, ele colocou-me de quatro na beirada da cama e arregaçou o meu cuzinho, tirando-me todas as pregas e depois fazendo-me chupar e engolir toda a porra dele na hora de gozar, o que fiz sem nojo e sem receio, afinal eu sempre o amei e não queria perdê-lo. Daí pra frente assumimos nosso relacionamento e depois de quatro meses de namoro, resolvemos morar juntos numa casinha modesta, mas nossa, que construímos num terreno que ele tinha. Hoje somos felizes e realizados sexualmente, pois sabemos como nos completar.
    Luana – Rio Claro - RJ
              TIRANDO O CABAÇO DA MINHA CUNHADA        

    Voltando das férias onde tirei o cabacinho da minha cunhada a vida voltou a rotina do começo de ano, mas nunca mais foi a mesma. Uma semana depois da volta da praia tive a oportunidade de ficar a sós com minha cunhada. Minha noiva voltou ao serviço e teve que viajar para São Paulo e ficar uma semana fazendo treinamento, foi quando minha cunhada teve que ir refazer matricula da faculdade e fui levá-la. Nayara estudava em uma cidade vizinha e quando pegamos estrada ela já veio me deixando louco. Disse que ficou uma semana na praia, perdeu a virgindade comigo e que estava louca pra transar novamente, pois seu namorado não havia feito nada em Camburiu. Assim que passamos pelo pedágio ela começou a passar a mão no meu pau e disse que queria fazer uma loucura e perguntou se eu permitia. Lógico que já sabendo das pretensões dela concordei e ela abriu o zíper da minha calça e desabotoou o botão. Começou a chupar meu pau como se tivesse chupando um sorvete. Aquela língua e o olhar pra cima de provocação me desconcentravam. Não agüentei e parei o carro. Na estrada mesmo ela continuou a chupar meu pau com mais intensidade foi logo que gozei na sua boca. Dessa vez nem precisei pedir e Nayara engoliu toda minha porra quente. Ela me deixava louco. Nos recompomos e seguimos viagem até a faculdade. Lá ela entrou para fazer rematricula e logo percebi de longe que ela falava algo com a colega e apontava para meu lado. Ela estava de calça jeans bem justa e uma blusinha preta bem decotada de alça e sua amiga de mini saia jeans e blusinha branca. As duas eram lindas, mas fiquei de longe só espiando. Assim q ela terminou veio em minha direção acompanhada da amiga Juliana que fiquei sabendo o nome depois. Nos apresentou e disse que eu era o professor de matemática mais bonito da cidade. A amiga bem safada disse que era um pecado ter um cunhado assim. Dei risada e chamei a cunhada para voltarmos. Minha intenção era voltar o mais rápido para pegar uma rodovia onde tinha um motel e minha cunhada sabia disso e se despediu da colega, mas não chegamos nem sair da faculdade. Ela estava terrível aquele dia, disse que ia me apresentar a faculdade e levou para o segundo andar onde ficava sua sala. Sabia que ela estava aprontando foi quando antes de chegar na sua sala ela me arrastou para o banheiro da faculdade. Sabia que seria ali que íamos transar e fomos logo nos fechando em um Box. Ela estava totalmente alucinada e foi tirando minha roupa. Sem camiseta e com as calças abaixadas sentei no vaso e foi ai que ela começou a tirar sua blusinha como se tivesse fazendo um strip e dançando. Meu pau já estava totalmente duro a ponte de explodir e ela se virou e foi tirando a calça com a bundinha virada pra mim. Ela sabia provocar como ninguém. De calcinha sentou no meu colo e disse: Faz essa sua cunhadinha putinha gozar como da outra vez professor bem dotado e me beijou. Aquilo me arrepiava e não sentia nem medo de transar ali. Tirei o sutiã e comecei a chupar seus seios ela começou a gemer feito uma cadelinha. Pegou meu pau e começou a bater uma punheta e sem tirar a calcinha e sim puxar para o lado encaixou meu pau na sua bucetinha. E começou a rebolar. Aos poucos o pau foi entrando e dessa vez parecia que estava mais apertadinha a bucetinha dela. Após entrar quase tudo levantei e encostei ela na parede e comecei a bombar. Ela gemia muito e não conseguia se controlar. Suas pernas já estavam cruzadas na minha cintura e meu pau totalmente penetrado nela. enfiei tudo dessa vez. Ela estava super molhada e facilitava a penetração. Estávamos completamente excitados como nunca nenhuma mulher tinha me deixado antes. Estávamos pela primeira vez a ponto de gozarmos juntos e isso não demorou a acontecer. Novamente gozei dentro daquela bucetinha linda. Os dois totalmente suados sem fôlego. Lembrando do motel na praia quis logo pegar ela de quatro ali mesmo e comer seu cuzinho. Dessa vez ela não falou nada. Virou tentou ficar de quatro mas o espaço era muito pequeno. Mandei encostar-se à parede e tentei enfiar no seu cuzinho. Ela começou a gritar de dor e a cabeça do pau nem tinha entrado. Escutamos alguns passos no corredor e ficamos em silencio quando resolvemos sair de lá e terminar isso no motel. Saindo da faculdade entramos no carro e perguntei onde era a farmácia mais próxima pra comprar algum lubrificante. Pegamos a estrada e em menos de 15 minutos estávamos no motel. Entramos, era um quarto bem simples e sem hidro dessa vez. Deitamos na cama e começamos a despir. Ela continuava cheirosa mesmo com todo o suor do banheiro da faculdade. Totalmente pelado peguei o lubrificante se já fui colocando ela de 4 na cama. Ela olhou pra mim e pediu pra enfiar com carinho. Não via a hora de comer aquele cuzinho apertadinho. Meu pau latejava de tesão. Lubrifiquei bem o meu pau e quando estava passando no cuzinho dela aproveitei e enfiei o dedo indicador. Ela virou e olhou pra trás. Sabia que era só o começo. Comecei a enfiar a cabeça do meu pau. Como foi difícil. Não entrava de jeito nenhum...Muito grande e grosso. Depois de uns 5 minutos de batalha e dor consegui enfiar a cabeça Ela gritava de dor e prazer ao mesmo tempo. Comecei bem devagar a bombar o pau naquele cuzinho. No que tirava e colocava já via sangue no pau. Ela estava sendo totalmente arrombada aos poucos. Comecei a forçar e consegui enfiar uns 15 cm e ela começou a pedir para parar. Apenas parei de bombar e deixei o pênis penetrado. Após passar os gritos comecei novamente mexer devagar e com a mão direita comecei a bater uma siririca para ela. Ela estava totalmente lambuzada. Ela começou a gemer com a siririca e até esqueceu da dor do cuzinho. Comecei a aproveitar da situação e fui intensificando as socadas de pau no cuzinho dela. Estava tão intenso que por pouco não consegui enfiar tudo naquela bundinha empinada. Depois de uns 20 minutos não agüentei segurar mais e comecei a gozar dentro dela. Ela sentiu aquilo quente por dentro e começou a gemer mais ainda dizendo que queria gozar novamente também. A virei e deitei-a rapidamente na cama e enfiei meu cacete, lambuzando-a com minha porra que ainda escorria sem parar. Meu pau estava totalmente roxo e doendo muito, mas mesmo assim comecei a comer a bucetinha dela. Levantei a pernas dela e deixei na posição de frango assado e enfiei todo o pau. Penetrou completamente. Ela gritava de tesão até que em pouco tempo gozou. Tomamos um banho e voltamos para nossa cidade e planejando quando seria a próxima loucura. Passou uma semana ela terminou com o namorado e me deixou numa fria. Mas isso vocês irão ler no próximo conto.
    M.C – Rio de Janeiro - RJ
              DE PAI PRA FILHO II        

    Feito histórico: o agora ex-jogador Rivaldo atuando ao lado de seu filho Rivaldo Júnior




    Mais um craque anunciou sua despedida dos gramados. Neste sábado o agora ex-meia Rivaldo anunciou sua aposentadoria aos 41 anos de idade e daqui por diante seguirá com sua carreira de cartola dirigindo o Mogi-Mirim, clube que o revelou para o Brasil e no qual também fez sua última partida.

    Rivaldo Vítor Borba Ferreira, nascido em Paulista/PE em 19 de abril de 1972 ganhou o mundo da bola nos anos 90 e começo dos 2000. Começou sua carreira no Santa Cruz de Pernambuco, mas seu nome veio aparecer de verdade no Mogi Mirim, time que ficou famoso como o "Carrossel Caipira" em 1992 juntamente com os meias Leto e Válber. 

    Passou com brilho por Corinthians, Palmeiras, Deportivo La Coruña, Barcelona e seleção brasileira. Neste período faturou uma Copa do Mundo e o título de melhor jogador do planeta em 1999. Outras passagens foram mais discretas como no Milan e no Olympiakos da Grécia, apesar de também ser ídolo por lá. Já o final de carreira foi um tanto melancólico com atuações por times obscuros ou de menor expressão (à exceção do São Paulo, obviamente) como Bunyodkor do Uzbequistão, Kabuscorp de Angola e São Caetano.

    Mas Rivaldo não colecionou apenas jogadas geniais, brilho, belos gols e troféus. Justamente em sua última partida conseguiu um feito histórico e que muitos atletas sonham com ele: o de atuar com seu filho em uma partida. Aconteceu justamente na última de sua carreira de 22 anos dentro dos gramados contra o São Bernardo pelo Campeonato Paulista deste ano em 18 de fevereiro no empate por 1 a 1. O pai chegou a dar um passe para o filho Rivaldo Júnior, atacante de 18 anos, mas que não resultou em nada.

    Confira abaixo o momento em que o fato histórico ocorreu.


    mattn/memoはGoで書かれていて、800行程度なのですぐに読めますし、気になる挙動があったらしゅっと直せます(自分も細かいPull Requestをいくつか送ってマージしてもらった)。特に以下の点が気にいっています。

    • Goで書かれていて、高速に立ち上がる
    • 簡単にgrepしたり(memo g)、pecoでファイル選択(memo e)ができる
    • httpサーバーが立ち上がって(memo s)、markdownがいい感じに見れる
      • テンプレートファイルをいじると自分の好きなようにできる(後述)

    半年ほど使って、メモも大分書いたので、より使い勝手を増すために自分がやっている設定を書いてみようと思います(ディフォルトの設定で使っていても十分使いやすいとは思います)。

    Emacsからさっと開く

    memo nから新しいテキストファイルを作れますが、同じ日付けの事柄は1つのテキストファイルに日報として書いています。なので、その日の日報ファイルが3秒で開けることが大事です。EmacsからM-x memoですぐに開けるようにしておきます。

    (defun memo ()
      (interactive)
      (find-file
       (concat "~/Dropbox/_posts/" (format-time-string "%Y-%m-%d") "-日報.md")))
    

    vimの人も似たようなことやってそう。

    数式の見栄えやコードのシンタックスハイライト

    論文を読んだときのちょっとした数式のメモや、スニペット的にメモにコードを貼っておくということは結構あると思います。その数式が綺麗に描画されたり、スニペットがシンタックスハイライトされていると、大したことないものでもテンションが上がってきます(大事!)。mattn/memoではテンプレートファイルを自分で自由に書けるので、私は数式描画にはKaTeXを、シンタックスハイライトにはhighlight.jsを使っています。cdnから読み込んでもいいですが、ダウンロードしてローカルに置いておくと、ネットに繋らない環境でも全く問題なく使えるので、そちらがよいでしょう。特にKaTeXは描画も相当早いし、aligned環境も使えてなんだこりゃ…という感じでした。

    f:id:syou6162:20170520174939p:plain

    そんなに凝ってないLaTeXだったら、ほぼ変えずにいい感じにmarkdownで書ける。markdownで雑に書いておいて、LaTeXに持っていくこともできそう。

    f:id:syou6162:20170520174703p:plain

    tableの見た目などを整えるためにlessが書きたかったので、less.jsも使っています。

    テンプレートファイルの内容

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>{{.Name}}</title>
    
        <link rel="stylesheet/less" type="text/css" href="/assets/style.less">
        <script src="/assets/less.js" type="text/javascript"></script>
    
        <link rel="stylesheet" type="text/css" href="/assets/atelier-dune-light.min.css">
        <script src="/assets/highlight.min.js" type="text/javascript"></script>
    
        <link rel="stylesheet" type="text/css" href="/assets/katex.min.css">
        <script src="/assets/katex.min.js" type="text/javascript"></script>
    
        <script src="/assets/auto-render.min.js"  type="text/javascript"></script>
    
        <script>
         document.addEventListener("DOMContentLoaded", () => {
           var katex_opts = {
             displayMode: true
           };
    
           Array.from(document.querySelectorAll("div"), elem => {
             if (elem.className === "highlight highlight-math") {
               var e = elem.querySelector("pre");
               katex.render(e.textContent, e, katex_opts);
             } else {
               hljs.highlightBlock(elem.querySelector("pre"));
             }
           });
    
           renderMathInElement(document.body, {
             delimiters: [
               {left: "$", right: "$", display: false},
             ]
           });
         });
        </script>
      </head>
      <body>{{.Body}}</body>
    </html>
    

    空のテキストファイルを削除するサブコマンド

    mattn/memoではサブコマンドを簡単に実装することができます。私の場合、日報ファイルを開いたもののその日は力尽きて空ファイルができて放置されてしまっていたので、それらを掃除するサブコマンドを実装しました。Goの練習にちょうどいい感じで簡単に書ける。

    サブコマンドのコード

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "os"
        "path/filepath"
        "regexp"
        "sort"
        "strings"
    
        "github.com/fatih/color"
        tty "github.com/mattn/go-tty"
    )
    
    const (
        memoDir            = "/Users/yasuhisa/Dropbox/_posts"
        emptyContentRegexp = `(?s)^# 日報[\n\s]*$`
    )
    
    type File struct {
        Path    string
        Content string
    }
    
    func filterMarkdown(files []string) []string {
        var newfiles []string
        for _, file := range files {
            if strings.HasSuffix(file, ".md") {
                newfiles = append(newfiles, file)
            }
        }
        sort.Sort(sort.Reverse(sort.StringSlice(newfiles)))
        return newfiles
    }
    
    func isEmptyContent(content string) bool {
        return regexp.MustCompile(emptyContentRegexp).MatchString(content)
    }
    
    func ask(prompt string) (bool, error) {
        fmt.Print(prompt + ": ")
        t, err := tty.Open()
        if err != nil {
            return false, err
        }
        defer t.Close()
        var r rune
        for r == 0 {
            r, err = t.ReadRune()
            if err != nil {
                return false, err
            }
        }
        fmt.Println()
        return r == 'y' || r == 'Y', nil
    }
    
    func deleteFile(f File) error {
        color.Red("%s", "Will delete the following entry. Are you sure?")
        fmt.Println("File: " + f.Path)
        fmt.Println(f.Content)
        answer, err := ask("Are you sure? (y/N)")
        if answer == false || err != nil {
            return err
        }
        answer, err = ask("Really? (y/N)")
        if answer == false || err != nil {
            return err
        }
        err = os.Remove(f.Path)
        if err != nil {
            return err
        }
        color.Yellow("Deleted: %v", f.Path)
        return nil
    }
    
    func main() {
        f, _ := os.Open(memoDir)
        defer f.Close()
        files, _ := f.Readdirnames(-1)
        files = filterMarkdown(files)
        for _, file := range files {
            path := filepath.Join(memoDir, file)
            b, _ := ioutil.ReadFile(path)
            content := string(b)
            if isEmptyContent(content) {
                deleteFile(File{path, content})
            }
        }
    }

    簡易markdown previewerとしてmemoを使う

    ~/.config/memo/config.tomlの設定項目の中のmemodirでmarkdownを置いているディレクトリを指定できます。しかし、たまにそのディレクトリ以外のREADME.mdなどのプレビューを見たいときがあります。そういうときはシンボリックリンクを貼ってごまかしながら使っています。

    % ln -s ${PWD}/README.md ~/Dropbox/_posts/2017-05-20-hoge.md

    これで、http://localhost:3456/の一覧にファイル(2017-05-20-hoge.md)が出てくるようになるので、html描画後の様子を見ながら編集します。いい感じに編集が終わったらunlinkで掃除。

    % unlink ~/Dropbox/_posts/2017-05-20-hoge.md

    supervisorでmemoをサーバーとして起動時に立ち上げる

    memo s --addr :3456でhttpサーバーがさっと立ち上がるのですが、ずっと使っていると立ち上げるのすら面倒で、PC起動したら立ち上がっていてくれという気持ちになりました。そこで、supervisorでmemoをサーバーとして起動時に立ち上げるようにしました。/usr/local/share/supervisor/conf.d/memo.confにこんな感じに書いておく。

    設定ファイルの内容

    [program:memo]
    command=zsh -c 'direnv exec . memo s --addr :3456'
    directory=%(ENV_HOME)s
    user=yasuhisa
    numprocs=1
    stdout_logfile=/tmp/memo_out.log
    stdout_logfile_maxbytes=10MB
    stdout_logfile_backups=3
    stderr_logfile=/tmp/memo_err.log
    stderr_logfile_maxbytes=10MB
    stderr_logfile_backups=3
    autostart=true
    autorestart=true
    

    ~/.config/memo/config.toml等を編集した場合、再起動しないと反映されないと思うので、適当にkillします。supervisorでautorestartがかかるので、ちょっと待っていると設定が反映されます。


              AWS Lambdaに入門する        

    Amazon Elasticsearch Serviceに引き続き、AWS Lambdaに入門しました。Lambdaを使って、Amazon Elasticsearch Serviceで特定の単語を検索をさせてslackに書き込んでくれるbot君を練習台でやってみました。

    やりたいこと

    AWS強化月間(?)ということでAmazon Elasticsearch Serviceに入門していました。

    twitterやslackのデータ置き場は無事に自宅のmac miniからAmazon Elasticsearch Serviceに移行できました。しかし、肝心のクローラーは相変わらず自宅のmac miniのjenkinsが頑張っているので、それをAWS Lambdaで代わりにやってもらおうというのがやりたいことです。一気にやるのはしんどいので、今回は以下のことをやってみます。

    • CloudWatch Eventsで定期的にlambdaを起動
    • Amazon Elasticsearch Serviceに貯蓄されているtwitterのデータから特定の単語を含むものを検索
      • goを使って書いていますが、AWSの認証をどうやるか
    • 検索にヒットした発言をslackに投稿
      • lambdaから簡単に外に出られるのか

    簡単なことしかやっていないですが、まぁ手始めということで。

    準備: 適切なポリシーを設定する

    後で説明しますが、apexからあれこれできるようにする必要があるので、IAMのポリシーを設定します。

    IAMのポリシー

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "iam:Create*",
                    "iam:Attach*",
                    "lambda:*"
                ],
                "Resource": "*"
            }
        ]
    }
    

    Goで書いたプログラムをapexを使いAWS Lambdaに転送

    AWS Lambdaでサポートされている言語はNode.js、Java、C#、Pythonのみですが、最近練習しているGoで書きたかったので方法を探りました。

    ちょっと脇道にそれますが、最近オフィスでNetatmoを使ってco2濃度をはかって、閾値を越えたら強制的に窓を開ける活動が流行っています。東京はGoogle App Scriptでやっています。

    京都では同様のことをlambdaでやっている同僚がいて、聞いてみるとapexを使っているようでした。なるほど、これを使うとGoで書いてlambdaで動かせるようです。

    Goでビルドしたバイナリをlambdaに送り、それを実行しているようで、外部のライブラリに依存していても割と安心なのはいいですね。サーバー上でライブラリをインストールする手間が省けます。AWSのコンソール画面をほぼ開くことなく、apex deployでlambdaにコードがdeployされていき、apex invoke hello --logsとやるとlambdaのプロセスを叩けました。1時間もかからずお手軽。

    Lambda上からAmazon Elasticsearch Serviceで検索

    GoからElasticsearchを叩けるようにするライブラリを作っている人はすでにいらっしゃいました。

    これを使うとやりたいことができそうですが、AWSの認証を突破しないといけません。私の場合、IPでの接続制限ではなくロールでの制限をやっているので、その情報を上述のclientに渡す必要があります。AWSがgo用のsdkを用意してくれていて、それを利用した認証情報をclientに食わせると、Amazon Elasticsearch Serviceで検索できるようになりました。

    あとはこれをlambda上で動かせるようにすれば完成です。githubに上げました。

    ACCESS_KEYやtokenも環境変数としてlambdaに登録していく必要がありますが、以下のようにするとそこまで面倒を見てくれます。

    % apex deploy --set AWS_ES_ENDPOINT=https://search-XXX.ap-northeast-1.es.amazonaws.com --set AWS_ES_ACCESS_KEY_ID=XXX --set AWS_ES_SECRET_ACCESS_KEY=YYY --set SLACK_TOKEN=xoxp-XXX --set SLACK_CHANNEL_NAME=mackerel_search
    % apex invoke hello --logs < event.json

    毎回invokeしたくないので、AWSのコンソール画面からトリガー(CloudWatch イベント - スケジュール: cron)を設定しました。これで数分に一回、lambda側で勝手に起動してくれます。

    MackerelのAWS連携でLambdaを監視

    お決まり感がありますが、Mackerelで監視させます。MackerelのAWS連携はLambdaに先日対応したので、agentを入れることなくlambdaをMackerelにホストとして登録することができます。

    read_onlyなロールを作ったらすぐ連携できます、便利。

    f:id:syou6162:20170331091611p:plain

    まとめ

    AWS lambda上でGoを使って割と自由にコードを実行することができました。今回はElasticsearchの検索しかやっていませんが、元々はクローラーを作ってElasticsearchに結果を格納していきたかったのでした。しかし、ひとまず準備は整ったかなと思います。AWSのサービスも2つ触ったことになるし、段々雰囲気が分かってきたので勉強も進みつつあると思いたいです。勉強だけだと辛いので、自分で楽しめるやつをやっていこうとは思います。

    Amazon Web Services実践入門 (WEB+DB PRESS plus)

    Amazon Web Services実践入門 (WEB+DB PRESS plus)


              Javaの例外をScalaで扱う        

    タイトルのことを調べようとしていて、三ヶ月に同じことを調べていたのでブログにメモしておきます…。主に↓に書いてある内容以上のことはありません。前より早く理解できたり、理解が深まったりしたので、進捗していると思いたい。

    Scalaの場合

    Scalaの関数の場合、以下のケースが多いと思います。

    • 値が存在しない場合もあるときはOption[A]を返す
      • 例: DBから値を引いてきたけど、存在しないときはNoneを返す
    • 失敗するかもしれない処理で、失敗した場合は理由も返して欲しいときはEither[A, B]を返す
      • 例: 外部との通信で破壊的な処理が失敗するかもしれないので、Left("Could not delete user")を返す
      • TryでSuccessかFailureというパターンもできる

    SomeやRightになっているもの同士の演算は取り出してくるんで…と手で丁寧にやっていると疲れるし読むのも大変です。mapやflatMap、forを組み合わせると書くのも楽になるし、読むのも楽になります。Haskellの本で勉強した。

    すごいHaskellたのしく学ぼう!

    すごいHaskellたのしく学ぼう!

    どれを使うにしてもパターンマッチでかちっとできるのは書いてても読んでても安心できますね(特にsealed traitなどを使っている場合)。

    Javaの場合

    ScalaのプロジェクトでもJavaのライブラリを使うことはよくよくあると思いますが、Javaの場合は失敗するかもしれない処理でもOptionやEitherを返さず例外を吐くことが多いです。以下のように、一旦OptionやEitherでくるむとScalaの場合と同じように扱うことができてよさそうですね。

    • allCatch opt => 例外吐いたときはNoneにして、成功した場合はSomeでくるんで返してくれる
    • allCatch either => 例外を吐いたときはLeftにして、成功した場合はRightでくるんで返してくれる

    参考


              Angular2に入門している話        

    機械学習のエントリばかりポストしていますが、現在の本職はWebエンジニアのid:syou6162です。

    フロントエンドの勉強がひたすら足りていないけど、きっかけがないと色々やり出さない性格なので、勉強会ドリブンでAngularの勉強を少しづつ進めています。先週末にちょうどAngularを作っているGoogleの中の人が大阪にいらっしゃるということで行ってきました。ぐぐりづらいことを直接聞けたので、大阪まで行ったかいがありました。

    基本的には下のハンズオンをひたすら写経するという感じ。資料はjsじゃなくてtypescriptで構成されているので、エディタで型の情報を見ながら勉強できて初心者に優しかった。

    DOM直接触ったり、JQueryとXPathでちょこちょこやったことがあるくらいだったので、双方向バインディングの考え方が新鮮でした。htmlの構造とかは一旦置いといて、オブジェクトの状態に応じてdomの中身やスタイルを変えることができるので、フロントエンドをやっているけどサーバーサイドっぽい思考でコードが書けるので助かる、という感想でした。

    困ったところ

    やっていて困ったこととしてはAngular2を自分のプロジェクトで動かしたいときに、最小限の設定はどれなんだ???というのが分からず困りました。gulpとかgruntとかあれこれあり、「えっ、小さいプロジェクトならpackage.jsonに直接書いていいの?」という感じで開発環境を整えるところが一番鬼門だったように思います。

    JavaScriptプログラマのための 実践的TypeScript入門 (アスキー書籍)

    JavaScriptプログラマのための 実践的TypeScript入門 (アスキー書籍)

    速習ECMAScript6: 次世代の標準JavaScriptを今すぐマスター!

    速習ECMAScript6: 次世代の標準JavaScriptを今すぐマスター!


              nasneの残量やGoogle Analyticsの情報をMackerelに監視させよう        

    Mackerelアドベントカレンダー6日目です。昨日はid:buty4649さんによるmackerelメタデータでパッケージ一覧を管理するCLIツールを作ったでした。

    こんにちは、株式会社はてなでアプリケーションエンジニアをやっているid:syou6162です。10月にMackerelチームにjoinしました。今回は生活に関するあれこれをMackerelに監視させると便利!という軽い話を紹介します。

    nasneの残量やjenkinsのjobの成功/失敗数をカスタムメトリックとして投稿/監視

    私はライフログを集めるのが好きで、twitterの発言、歩いた歩数、預金残高などなど取れそうな情報をひたすら自宅のElasticSearchに保存しています。そのデータをkibanaで可視化したり検索すると、月や年単位での振り返りが簡単にできます。

    ElasticSearchはこのように可視化や検索は得意なのですが、一点問題があって、数値がある閾値を越えたときの通知ができないという問題がありました。自分に関する多様なデータを貯め込んでいると通知して欲しくなる状況は結構あり、例えば「nasneの残量が減って、録画できなくない状況になる前に通知して欲しい」などの状況があります。最初はslackへの通知を自分で書いていたのですが、真面目に書くと割と面倒になってきたので(例えば60分おきの通知の再送など)、通知部分をmackerelに任せることにしました。

    方法は色々ありますが、今回はホストのカスタムメトリックとして投稿するやり方でやってみます。

    mackerel.io

    agentの設定ファイルに指定されたフォーマットを吐くようなコマンド(スクリプト)を用意するだけなので簡単ですね。nasneの容量の場合、スクリプトを用意するまでもなく、こんな感じでワンライナーで投稿することができます。

    [plugin.metrics.nasne]
    command = "echo \"nasne.volumes.freeVolumeSizeRatio\t$(curl -s 'http://10.X.X.X:64210/status/HDDInfoGet?id=0' | /usr/local/bin/jq -r '.HDD | .freeVolumeSize / .totalVolumeSize')\t`date -u +%s`\""
    

    これで1分置きにnasneの残り容量が分かり、監視設定をすれば容量が足りなくて「逃げるは恥だが役に立つ」が予約できなかった、という事態を防ぐことができます。slackへの通知も簡単にできるので、家庭内のslackに通知すればITにそれほど詳しくない妻も簡単に状況が分かります。実際の我が家のnasne残量の推移はこんな感じになっています(2-3日に1回は通知がくるような残量を推移しています...)。

    f:id:syou6162:20161129195440p:plain

    ライフログの取得にはjenkinsを活用しているのですが、ジョブの数が50個を越えてきたため、個別に通知されると見るのも大変です。そこで、成功/失敗の数もmackerelのカスタムメトリックで監視させています。nasneのときと同様にagentの設定ファイルに簡単なワンライナーを書けばOKです。

    [plugin.metrics.jenkins_jobs_red]
    command = "echo \"jenkins.jobs.red\t`curl -s http://localhost:3000/api/json | /usr/local/bin/jq -r '.jobs[] | .color' | grep -c red`\t`date -u +%s`\""
    
    [plugin.metrics.jenkins_jobs_blue]
    command = "echo \"jenkins.jobs.blue\t`curl -s http://localhost:3000/api/json | /usr/local/bin/jq -r '.jobs[] | .color' | grep -c blue`\t`date -u +%s`\""
    

    成功/失敗の数のグラフは下の図で、安定していますが、瞬間停電でjenkinsを走らせている自宅macが落ちてしまったときにすぐ気づくことができ、長期間ライフログの失敗に取得していた、という事態を防ぐことができました(connectivityの通知でも気づくことができます)。

    f:id:syou6162:20161129200442p:plain

    Google Analyticsのユーザー数をサービスメトリックとして投稿/監視

    Google Analyticsはリアルタイムに現在の訪問ユーザー数を知ることができるので見ているだけでも楽しいですが、「頻繁に見ていては仕事にならん、炎上しそうになってる(?)とき教えてくれ!」というのができると楽しそうと思ってやってみました(完全にネタです)。Google Analyticsから情報を取得するのは面倒そうですが、Google SpreadsheetのアドオンにGoogle Analyticsの情報を取得するものがあったのでそれを使います。

    Google SpreadsheetにはGoogle App Script(javascriptと似たようなもの)を定期的に動かすことができる機能があるので、それを使って最近の訪問者数をmackerelに投稿させましょう。スクリプトはこんな感じです(ネタなので、かなり適当に書いています...)。

    function postMackerelServiceMetric(apiKey, serviceName, payload) {
      return UrlFetchApp.fetch(
        "https://mackerel.io/api/v0/services/" + serviceName + "/tsdb",
        {
        "contentType" : "application/json",
        "method" : "post",
        "headers" : {
          "X-Api-Key" : apiKey
        },
        "payload" : JSON.stringify(payload),
        "muteHttpExceptions" : true
        }
      );
    }
    
    var epoch = Date.now() / 1000;
    var mackerelApiKey = "YOUR_MACKEREL_API_KEY";
    var serviceName = "Analytics";
    
    function run(term, sheetName) {
      var ss =SpreadsheetApp.getActiveSpreadsheet()
      var mySheet = ss.getSheetByName(sheetName)
      SpreadsheetApp.setActiveSheet(mySheet);
      
      var row = mySheet.getLastRow();
      var users = mySheet.getRange(row, 2).getValue();
      var sessions = mySheet.getRange(row, 3).getValue();
      var pageviews = mySheet.getRange(row, 4).getValue();
    
      var payload = [
        {"name" : "analytics." + term + ".users", "time" : epoch, "value" : users},
        {"name" : "analytics." + term + ".sessions", "time" : epoch, "value" : sessions},
        {"name" : "analytics." + term + ".pageviews", "time" : epoch, "value" : pageviews}
      ];
      var mackerelPostRes = postMackerelServiceMetric(mackerelApiKey, serviceName, payload);
      Logger.log(mackerelPostRes)
    }
    
    function main_day() {
      run("day", "Google Analytics(Day)")
    }
    
    function main_hour() {
      run("hour", "Google Analytics(Hour)")
    }
    

    Google Spreadsheetで15分に一度くらい実行させておけばまぁよいでしょう。こんな感じで、炎上してそうかどうかも簡単に通知させることができます(実際はRTされてバズったとかですが)。

    f:id:syou6162:20161129202636p:plain

    機械学習の分類器の性能をサービスメトリックとして投稿/監視

    ネタ要素を書いたので、最後は真面目なネタを書きます。最近は機械学習をサービスに導入する企業も大分増えてきたので、この分類器の性能はいい/悪いといった情報がどんどん流れてきます。Webサイトの訪問者数の増加によってサーバーのCPU率が上がっていないかどうかを(mackerelで!)監視したいのと同様に、機械学習の分類器(回帰も)の性能も刻々と追加/修正される教師データやチューニングの状況によって変化するため、これもmackerelで監視できるとうれしいでしょう。早速、サービスメトリックに投稿するようにしましょう。PerlやRuby、Goなど様々な言語からサービスメトリックの情報を簡単に取得/追加/更新/削除することができます。

    例えばPerlで機械学習の分類器のF値などを投稿するスクリプトはこんな雰囲気です。簡単ですね。

    use JSON::Types;
    use WebService::Mackerel;
    
    my $mackerel = WebService::Mackerel->new(
        api_key => $ENV{ML_STUDY_MACKEREL_API_KEY},
        service_name => 'ML-Study',
    );
    
    my $res = $mackerel->post_service_metrics(
        [
            {
                "name"  => "evaluation.precision",
                "time"  => time,
                "value" => JSON::Types::number $metrics->{precision},
            },
            {
                "name"  => "evaluation.recall",
                "time"  => time,
                "value" => JSON::Types::number $metrics->{recall},
            },
            {
                "name"  => "evaluation.f_value",
                "time"  => time,
                "value" => JSON::Types::number $metrics->{f_value},
            },
        ]
    );
    

    社内ではまだ導入していませんが、勉強会で雑談するときのエントリを推薦するbotを作ったので、この精度を投稿させています。こんな様子です。

    f:id:syou6162:20161129204759p:plain

    アノテーションの基準を特に決めていなかったために、教師データを増やしていっても精度がかえって落ちていっているという悲しい状況をmackerelは教えてくれます。

    まとめ

    今回は大まかに3つほどmackerelに様々なメトリックを投稿/監視させる方法を書きました。10行程度の簡単なスクリプト(あるいはワンライナー)、サーバーがなくてもGoogle Spreadsheetからメトリック投稿ができる、ということが分かっていただけたかと思います。このようにお手軽なところからmackerelを使っていただき、mackerelの本業であるサーバーの状態監視も体験してもらえるとうれしいです。

    明日はhtnosmさんです。

    参考情報

    blog.sushi.money blog.a-know.me astj.hatenablog.com


              Fabulous technology for your.....mirrors!        
    I'm sitting at the mechanic's shop, getting the oil changed and tires rotated.  Loving their Wifi.  I think I hear Kelly Ripa on the waiting room TV.  What's her show called now that Regis has retired?  She's got such a friendly, happy voice.

    The article below is by Mike Elgan, and was sent to me from Houzz.com (you know I love that site).  Read it at your leisure and take the time to watch the various videos when you can.  You won't regret it.  Very exciting advances in mirrors that will be used in amazing ways around the house.  Some of it I don't want (no emails on the bathroom mirror, thank you), but others I can't wait for!

    Let's see if I can successfully embed the article.  Every day, a new skill...


    Houzz- Kitchen Remodel, Bathroom Remodel and More Â»

    I think I did it!  And the day is just beginning.   What will I tackle next?

    Ciao,
    Anne
    Browse Furniture on Houzz- For Example:

              Global Alumni Panel        

    A panel of former international and U.S. UNI students will describe how their experiences living, studying and working in a different culture,
    other than their own, have helped them to gain advantage in their post-college professional and personal lives.

    Conferences, Workshops, & Camps
    Location: 
    Room 301, Rod Library
    Tuesday, November 15, 2016 - 12:00 pm
    Enter Your Email: 
    Name: 
    Kristi Marchesani
    Share/Save
              Stadium WE9 - Turf HD UCL 12/13 Collections        









    STADIUM WE9 UCL 12/13 COLLECTIONS

     Screen Shoot



     Download Link

    Show


    NOTE : If you find any problems for use of this stadium, please leave a comment


    Credit In File


    Regards
              Materi Sejarah sm.1 SMA XII IPS        

    KEADAAN EKONOMI-KEUANGAN PADA AWAL KEMERDEKAAN


    A.   FAKTOR-FAKTOR PENYEBAB MEMBURUKNYA KEADAAN EKONOMI DAN KEUANGAN DI INDONESIA PADA AWAL KEMERDEKAAN
    Pada akhir pendudukan Jepang dan pada awal berdirinya Republik Indonesia keadaan ekonomi Indonesia sangat kacau. Hal ini disebabkan oleh hal-hal sebagai berikut :
    1.    Inflasi yang sangat tinggi (Hiper-Inflasi).
    Penyebab terjadinya inflasi ini adalah beredarnya mata uang pendudukan Jepang secara tak terkendali. Pada saat itu diperkirakan mata uang Jepang yang beredar di masyarakat sebesar 4 milyar. Dari jumlah tersebut, yang beredar di Jawa saja, diperkirakan sebesar 1,6 milyar. Jumlah itu kemudian bertambah ketika pasukan Sekutu berhasil menduduki beberapa kota besar di Indonesia dan meguasai bank-bank. Dari bank-bank itu Sekutu mengedarkan uang cadangan sebesar 2,3 milyar untuk keperluan operasi mereka. Kelompok masyarakat yang paling menderita akibat inflasi ini adalah petani. Hal itu disebabkan pada zaman pendudukan Jepang petani adalah produsen yang paling banyak menyimpan mata-uang Jepang.
    Pemerintah Republik Indonesia yang baru berdiri, tidak dapat menghentikan peredaran mata uang Jepang tersebut, sebab negara RI belum memiliki mata-uang baru  sebagai penggantinya. Maka dari itu, untuk sementara waktu pemerintah RI menyatakan tiga mata uang yang berlaku di wilayah RI, yaitu :
    a.    mata-uang De Javasche Bank;
    b.    mata-uang pemerintah Hindia Belanda;
    c.    mata-uang pendudukan Jepang.
    Pada saat kesulitan ekonomi menghimpit bangsa Indonesia, tanggal 6 Maret 1946, Panglima AFNEI yang baru, Letnan Jenderal Sir Montagu Stopford mengumumkan berlakunya uang NICA di daerah-daerah yang diduduki Sekutu. Uang NICA ini dimaksudkan sebagai pengganti uang Jepang yang nilainya sudah sangat turun. Pemerintah melalui Perdana Menteri Syahrir memproses tindakan tersebut. Karena hal itu berarti pihak Sekutu telah melanggar persetujuan yang telah disepakati, yakni selama belum ada penyelesaian politik mengenai status Indonesia, tidak akan ada mata uang baru.
    Oleh karena itulah pada bulan Oktober 1946 Pemerintah RI, juga melakukan hal yang sama yaitu mengeluarkan uang kertas baru yaitu Oeang Republik Indonesia (ORI) sebagai pengganti uang Jepang. Untuk melaksanakan koordinasi dalam pengurusan bidang ekonomi dan keuangan, pemerintah membentuk Bank Negara Indonesia pada tanggal 1 November 1946. Bank Negara ini semula adalah Yayasan Pusat Bank yang didirikan pada bulan Juli 1946 dan dipimpin oleh Margono Djojohadikusumo. Bank negara ini bertugas mengatur nilai tukar ORI dengan valuta asing.
    2.    Adanya blokade ekonomi, oleh Belanda (NICA). Blokade laut ini dimulai pada bulan November 1945 ini, menutup pintu keluar-masuk perdagangan RI. Adapun alasan pemerintah Belanda melakukan blokade ini adalah :
    a.    Untuk mencegah dimasukkannya senjata dan peralatan militer ke Indonesia;
    b.    Mencegah dikeluarkannya hasil-hasil perkebunan milik Belanda dan milik asing lainnya;
    c.    Melindungi bangsa Indonesia dari tindakan-tindakan yang dilakukan oleh orang bukan Indonesia.
    Akibat dari blokade ini barang-barang dagangan milik pemerintah RI tidak dapat diekspor, sehingga banyak barang-barang ekspor yang dibumihanguskan. Selain itu Indonesia menjadi kekurangan barang-barang impor yang sangat dibutuhkan.
    3. Kas negara kosong, pajak dan bea masuk sangat berkurang, sehingga pendapatan pemeritah semakin tidak sebanding dengan pengeluarannya. Penghasilan pemerintah hanya bergantung kepada produksi pertanian. Karena dukungan petani inilah pemerintah RI masih bertahan, sekali pun keadaan ekonomi sangat buruk.

    B.   USAHA MENEMBUS BLOKADE EKONOMI
    Usaha-usaha untuk menembus blokade ekonomi yang dilakukan oleh pihak Belanda dilaksanakan oleh pemerintah dengan berbagai cara, diantaranya sebagai berikut :
    1.    Diplomasi Beras ke India
    Usaha ini lebih bersifat politis daripada ekonomis. Ketika terdengar berita bahwa rakyat India sedang ditimpa bahaya kelaparan, pemerintah RI segera menyatakan kesediaannya untuk membantu pemerintah India dengan mengirimkan 500.000 ton beras, dengan harga sangat rendah. Pemerintah bersedia melakukan hal ini karena diperkirakan pada musim panen tahun 1946 akan diperoleh surplus sebesar 200.000 sampai 400.000 ton.
    Sebagai imbalannya pemerintah India menjanjikan akan mengirimkan bahan pakaian yang sangat dibutuhkan oleh rakyat Indonesia. Keuntungan politik yang diperoleh oleh pemerintah RI adalah dalam forum internasional India adalah negara Asia yang paling aktif membantu perjuangan kemerdekaan RI.
    2.    Mengadakan Hubungan Dagang Langsung ke Luar Negeri
    Usaha untuk membuka hubungan langsung ke luar negeri, dilakukan oleh pihak pemerintah maupun pihak swasta. Diantara usaha-usaha tersebut adalah sebagai berikut :
    a.    Mengadakan kontak hubungan dengan perusahaan swasta Amerika (Isbrantsen Inc.). Usaha ini dirintis oleh BTC (Banking and Trading Corporation), suatu badan perdagangan semi-pemerintah yang dipimpin oleh Dr. Sumitro Djojohadikusumo dan Dr. Ong Eng Die. Dalam transaksi pertama pihak Amerika Serikat bersedia membeli barang-barang ekspor dari Indonesia seperti gula, karet, teh, dan sebagainya. Kapal Isbrantsen Inc. yang masuk ke pelabuhan Cirebon adalah kapal Martin Behrmann yang mengangkut barang-barang pesanan RI dan akan memuat barang-barang ekspor dari RI. Akan tetapi kapal itu dicegat oleh kapal Angkatan Laut Belanda dan diseret ke pelabuhan Tanjung Priuk dan seluruh muatannya disita.
    b.    Menembus blokade ekonomi Belanda di Sumatera dengan tujuan Singapura dan Malaysia. Oleh karena jarak perairan yang relatif dekat, maka usaha ini dilakukan dengan perahu layar dan kapal motor cepat. Usaha ini secara sistimatis dilakukan sejak tahun 1946 sampai dengan akhir masa Perang Kemerdekaan. Pelaksanaan penembusan blokade ini dilakukan oleh Angkatan Laut RI dengan dibantu oleh pemerintah daerah penghasil barang-barang ekspor.
    Sejak awal tahun 1947 pemerintah RI membentuk perwakilan resmi di Singapura yang diberi nama Indonesia Office (Indoff). Secara resmi Indoff ini merupakan badan yang memperjuangkan kepentingan politik di luar negeri, namun secara rahasia juga berusaha menembus blokade dan usaha perdagangan barter.
    Kementerian Pertahanan juga membentuk perwakilannya di luar negeri yang disebut Kementerian Pertahanan Usaha Luar Negeri (KPLULN) yang dipimpin oleh Ali Jayengprawiro. Tugas pokok badan ini adalah membeli senjata dan perlengkapan Angkatan Perang. Sebagai pelaksana upaya menembus blokade ini yang terkenal adalah John Lie, O.P. Koesno, Ibrahim Saleh dan Chris Tampenawas. Selama tahun 1946 pelabuhan di Sumatera hanya Belawan yang berhasil diduduki Belanda. Karena perairan di Sumatera sangatlah luas, maka pihak Belanda tidak mampu melakukan pengawasan secara ketat. Hasil-hasil dari Sumatera terutama karet yang berhasil diselundupkan ke luar negeri, utamanya ke Singapura, mencapai jumlah puluhan ribu ton. Selama tahun 1946 saja barang-barang yang diterima oleh Singapura dari Sumatera seharga Straits $ 20.000.000,-. Sedangkan yang berasal dari Jawa hanya Straits $ 1.000.000,-. Sebaliknya barang-barang yang dikirim ke Sumatera dari Singapura seharga Straits $ 3.000.000,- dan dari Singapura ke Jawa seharga Straits $ 2.000.000,-.
    C.   USAHA-USAHA MENGATASI KESULITAN EKONOMI
    Pada awal kemerdekaan masih belum sempat melakukan perbaikan ekonomi secara baik. Baru mulai Pebruari 1946, pemerintah mulai memprakarsai usaha untuk memecahkan masalah-masalah ekonomi yang mendesak. Upaya-upaya itu diantaranya sebagai berikut :
    1. Pinjaman Nasional
    Program Pinjaman Nasional ini dilaksanakan oleh Menteri Keuangan. lr. Surachman dengan persetujuan BP-KNIP. Pinjaman Nasional akan dibayar kembali selama jangka waktu 40 tahun. Besar pinjaman yang dilakukan pada bulan Juli 1946 sebesar Rp. 1.000.000.000,00. Pada tahun pertama berhasil dikumpulkan uang sejumlah Rp. 500.000.000,00. Sukses yang dicapai ini menunjukkan besarnya dukungan dan kepercayaan rakyat kepada Pemerintah RI.
    2. Konferensi Ekonomi, Februari 1946
    Konferensi ini dihadiri oleh para cendekiawan, para gubernur dan para pejabat lainnya yang bertanggungjawab langsung mengenai masalah ekonomi di Jawa. Konferensi ini dipimpin oleh Menteri Kemakmuran, Ir. Darmawan Mangunkusumo. Tujuan konferensi ini adalah untuk memperoleh kesepakatan yang bulat dalam menanggulangi masalah-masalah ekonomi yang mendesak, seperti :
    a.    masalah produksi dan distribusi makanan
    Dalam masalah produksi dan distribusi bahan makanan disepakati bahwa sistem autarki lokal sebagai kelanjutan dari sistem ekonomi perang Jepang, secara berangsur-angsur akan dihapuskan dan diganti dengan sistem desentralisasi.
    b.    masalah sandang
    Mengenai masalah sandang disepakati bahwa Badan Pengawasan Makanan Rakyat diganti dengan Badan Persediaan dan Pembagian Makanan (PPBM) yang dipimpin oleh dr. Sudarsono dan dibawah pengawasan Kementerian Kemakmuran. PPBM dapat dianggap sebagai awal dari terbentuknya Badan Urusan Logistik (Bulog).
    c.    status dan administrasi perkebunan-perkebunan
    Mengenai masalah penilaian kembali status dan administrasi perkebunan yang merupakan perusahaan vital bagi RI, konferensi ini menyumbangkan beberapa pokok pikiran. Pada masa Kabinet Sjahrir, persoalan status dan administrasi perkebunan ini dapat diselesaikan. Semua perkebunan dikuasai oleh negara dengan sistem sentralisasi di bawah pengawasan Kementerian Kemakmuran.
    Konferensi Ekonomi kedua diadakan di Solo pada tanggal 6 Mei 1946. Konferensi kedua ini membahas masalah perekonomian yang lebih luas, seperti program ekonomi pemerintah, masalah keuangan negara, pengendalian harga, distribusi dan alokasi tenaga manusia. Dalam konferensi ini Wakil Presiden Drs. Moh. Hatta memberikan saran-saran yang berkaitan dengan masalah rehabilitasi pabrik gula. Hal ini disebabkan gula merupakan bahan ekspor yang penting, oleh karena itu pengusahaannya harus dikuasai oleh negara. Hasil ekspor ini diharapkan dapat dibelikan atau ditukar dengan barang-barang lainnya yang dibutuhkan RI.
    Saran yang disampaikan oleh Wakil Presiden ini dapat direalisasikan pada tanggal 21 Mei 1946 dengan dibentuknya Badan Penyelenggara Perusahaan Gula Negara (BPPGN) berdasarkan Peraturan Pemerintah No. 3/1946. Peraturan tersebut disempurnakan melalui Peraturan Pemerintah No. 4 tahun 1946, tanggal 6 Juni 1946 mengenai pembentukan Perusahaan Perkebunan Negara (PPN).
    3.    Pembentukan Planning Board (Badan Perancang Ekonomi) pada tanggal 19 Januari 1947
    Pembentukan Badan ini atas inisiatif Menteri Kemakmuran, dr. A.K. Gani. Badan ini merupakan badan tetap yang bertugas membuat rencana pembangunan ekonomi untuk jangka waktu 2 sampai 3 tahun. Sesudah Badan Perancang ini bersidang, A.K. Gani mengumumkan Rencana Pembangunan Sepuluh Tahun. Untuk mendanai Rencana Pembangunan ini terbuka baik bagi pemodal dalam negeri maupun bagi pemodal asing. Untuk menampung dana pembangunan tersebut pemerintah akan membentuk Bank Pembangunan.
    Pada bulan April 1947, Badan Perancang ini diperluas menjadi Panitia Pemikir Siasat Ekonomi yang dipimpin langsung oleh Wakil Presiden Moh. Hatta, sedangkan A.K. Gani sebagai wakilnya. Panitia ini bertugas mempelajari, mengumpulkan data dan memberikan saran kepada pemerintah dalam merencanakan pembangunan ekonomi dan dalam rangka melakukan perundingan dengan pihak Belanda.
    Semua hasil pemikiran ini belum berhasil dilaksanakan dengan baik, karena situasi politik dan militer yang tidak memungkinkan. Agresi Militer Belanda mengakibatkan sebagian besar daerah RI yang memiliki potensi ekonomi baik, jatuh ke tangan Belanda. Wilayah RI tinggal beberapa keresidenan di Jawa dan Sumatera yang sebagian besar tergolong sebagai daerah minus dan berpenduduk padat. Pecahnya Pemberontakan PKI Madiun dan Agresi Militer Belanda II mengakibatkan kesulitan ekonomi semakin memuncak.

    4.    Rekonstruksi dan Rasionalisasi Angkatan Perang (RERA) pada tahun 1948.
    Program yang diprakarsai oleh Wakil Presiden Drs. Moh. Hatta ini, dimaksudkan untuk mengurangi beban negara dalam bidang ekonomi, disamping meningkatkan efesiensi. Rasionalisasi ini meliputi penyempurnaan administrasi negara, Angkatan Perang dan aparat ekonomi.  Sejumlah satuan Angkatan Perang dikurangi secara dratis. Selanjutnya tenaga-tenaga bekas Angkatan Perang ini disalurkan ke bidang-bidang produktif dan diurus oleh Kementerian Pembangunan dan Pemuda.
    5.    Rencana Kasimo (Kasimo Plan)
    Program ini disusun oleh Menteri Urusan Bahan Makanan I.J. Kasimo. Pada dasarnya program ini berupa Rencana Produksi Tiga Tahun, 1948-1950 mengenai usaha swasembada pangan dengan beberapa petunjuk pelaksanaan yang praktis. Untuk mningkatkan produksi bahan pangan dalam program ini, Kasimo menyarankan agar :
    a.    menanami tanah-tanah kosong di Sumatera timur seluas 281.277 ha.;
    b.    di Jawa dilakkan intensifikasi dengan menanam bibit unggul;
    c.    pencegahan penyembelihan hewan-hewan yang berperan penting bagi produksi pangan;
    d.    disetiap desa dibentuk kebun-kebun bibit;
    e.    tranmigrasi.
    6.    Persatuan Tenaga Ekonomi (PTE)
    Organisasi yang  dipimpin B.R. Motik ini, bertujuan untuk menggiatkan kembali partisipasi pengusaha swasta. Dengan dibentuknya PTE juga diharapkan dapat dan melenyapkan individualisasi di kalangan organisasi pedagang sehingga dapat memperkokoh ketahanan ekonomi bangsa Indonesia. Pemerintah menganjurkan agar pemerintah daerah usaha-usaha yang dilakukan oleh PTE. Akan tetapi nampaknya PTE tidak dapat berjalan dengan baik. PTE hanya mampu mendirikan Bank PTE di Yogyakarta dengan modal awal Rp. 5.000.000. Kegiatan PTE semakin mundur akibat dari Agresi Militer Belanda.
    Selain PTE perdagangan swasta lainnya yang juga membantu usaha ekonomi pemerintah adalah Banking and Trading Corporation (Perseroan Bank dan Perdagangan).
              A Rusty Venture: Writing a text adventure in Rust        

    After a couple of months of playing around with Rust, I’ve finished a project! It’s a simple text adventure game in the vein of class text adventure Zork called Adventure!. The feature set isn’t as wide as Zork; there is no combat and movement & world interaction is pretty simple. I was never really into text adventures myself, but I though that it would make an interesting & fun first project with Rust.

    Design

    I wanted to write a game containing of a few rooms, with a few things to do in each room. The feature set wouldn’t go past picking up objects, adding them to an inventory, and using inventory objects with static objects in the world. I didn’t want to involve combat on NPCs as I didn’t want to work on this project for the long-term; it’s a toy project for learning a bit about how Rust works.

    Changing Rooms

    My first design involved having Room structs that would contain a member connection: Connection. This Connection struct would itself have 4 members: north, south, east and west. The value of these members was to be an Option<Box<Room>>. The main Game object that ran the whole show would have a current_room reference that points to whatever instance of Room the user was in.

    Unfortunately, this design gave me trouble with the borrow checker. I got many cannot moved out of borrowed context errors thrown at me. At the time, I didn’t really fully understand how the borrow checker works - and honestly, I’m pretty sure I still don’t understand fully. I decided to take a simpler approach: I’d store current_room as an integer representing an index in the vector of rooms. In Rust, the index of a vector is the type usize, a pointer-sized (therefore system-dependent) unsigned int. At first, I stored current_room as an i32 but this led to lots of as usize casting all over the place. Connection objects would be Option<usize> and changing rooms would be as simple as replacing current_room with another usize value.

    The downside of this approach is having to know each Room’s index in the vector ahead of time. I kept track of the room number while designing the game ‘map’ so it wasn’t a big deal in my particular situation. I thought being able to ‘point’ to other Room directly with a reference would be simpler, but that would bring its own problems with it. For example, this would bring about circular references (eg: Room 1 is connected to Room B, but if we create Room 1 first, how do we define this relationship when creating the Room object? My solution: You wouldn’t, you’d connect the rooms afterwards).

    Flags & Actions

    My next set of problems came with dealing with state change in the game. I ended up declaring a HashMap<&'static str, bool> in a struct Flags at the top-level of the game that gets passed around to the different functions. Originally, each Room was going to have its own set of flags but I didn’t want have to reach across rooms to check the state of something - especially if an action in one room can have consequenes elsewhere.

    Dealing with the actions took the longest to figure out. I had an important questions I needed to answer at this point: How can I define each Item or Room to have different behaviour depending on the state of global flags? To solve this, I used closures. For instance, here is how an Item is defined:

    struct Item {
        name: String,
        is_grabbable: bool,
        on_grab: Box<Fn(&mut Flags)>,
        on_use: Box<Fn(&mut Flags, String, usize) -> bool>,
    }
    

    Both on_grab and on_use accept closures. Because our state is stored in a global object, each room doesn’t really need to worry about what’s going on in other rooms - they only need to know the state of the world through the Flag objects they receive. This allows me to use closures to define certain behaviour.

    I’m not exactly sure if this method is idiomatic Rust. I’ve been writing primarily JavaScript for my day job for the past few years so I’m still in that state of mind where functions are first class citizens that I should be taking advtange of. I wasn’t really sure how else to define individual behaviour for separate instances of the same type.1

    For instance, this is an example of how an Item is defined:

    Item {
        name: "shovel".to_string(),
        is_grabbable: true,
        on_grab: Box::new(|flags: &mut Flags| {
            println!("The shovel looks as if it has never been used before; the layer of dust that falls off as you pick it up shows that it has been sitting on that table for a long time. You slip the shovel in your pocket.");
            flags.update_key("pickedUpShovel", true);
        }),
        on_use: Box::new(|flags: &mut Flags, object_name: String, current_room: usize| -> bool {
            // this sucks; checking if we are in the room before perfoming action
            if current_room == 1 && object_name == "glass door" {
                if flags.get_key("smashedDoor") == Some(&false) {
                    println!("It takes a few swings before a couple of cracks appear in the glass. Wondering why such strong glass is needed for a greenhouse door, you continue to swing away until a loud crash and gust of fresh air announces the success of your swinging endeavours.");
                    flags.update_key("smashedDoor", true);
                    false
                }
                else {
                    println!("You seem to have already done a number on that poor door - maybe you should leave it alone?");
                    false
                }
            }
            else {
                println!("You aren't sure how to use the shovel with the {}", object_name);
                false
            }
        }),
    }
    

    … and that’s just one item! Imagine a whole Room, with it’s own behaviour and items! (Or see for yourself and check out the source file with the levels defined).

    Another issue is that this method leads to cases where certain objects that don’t use a specific callback have empty closures, which makes rustc complain about unused variables. This isn’t a huge deal, but it can clutter up compiler messages which is slightly annoying.

    Originally, I planned on serializing each room into data files instead of hard coding them into Rust source code. This way, anyone can write their own text adventure without knowing a line of Rust! As soon as I decided to use closures, however, that task seemed like it would be much more difficult. How do you serialize behaviour? The only method I can think of is via a scripting language, and that was way out of scope for this project.

    Other random notes

    • It would be nice if there was a way to initialize a HashMap by passing a series of key/values to its new() function or via a literal. I’m using a macro I found on StackOverflow to do the job right now but it would be neat if this was built into the standard library.

    Conclusion: I like it.

    In the process of writing this post, I’ve had to question a few of my design choices and actually learned new stuff (the idea of changing the type of current_room from i32 to usize happened due to this post)!

    The likelihood of me continuing to work on this project is low. Howevever, if I were to make an ‘Adventure! 2.0’, I’d make the following changes:

    • Spice things up with Termion. I came across this great blog post by the author of the termion crate, ticki. Maybe making some item names show up in Zelda’s “Important Noun” red, or having more of a persistant GUI on screen such as the inventory.
    • Take advantage of more core Rust/Cargo tools, like rustdoc.
    • Tests! Testing is important. I worked on this project for a few hours a week over the span of a month so it wasn’t something at the top of my mind.
    • Figure out cross-compilation so I can build executables for Windows & MacOS from my Linux desktop

    I had fun working on Adventure. If you’d like to check it out, here is the GitHub repo. I’d like to figure out cross-compilation soon to get some binaries up on on the GitHub page. My next project will involve gasp graphics! Until then…

    1. As I write this, a few ideas come to mind (although I’m not sure if they actually work). Perhaps creating a trait that all Rooms/Items implement, and write a macro that creates a new struct with said trait with the individual behaviour defined within? Just a thought. 


              A Boilerplate for WebGL Projects        
    • 2015/12/12: Added source map support

    Between Grunt, Gulp, Webpack and Broccoli, it seems like a new build tool/asset pipeline/module bundler/etc arrives in the land of JavaScript every few months. While learning WebGL, I started to look into ways to make starting a new project and development a bit easier. I’ve been using Webpack for work-related purposes over the past few months and I’ve really grown to like its easy-to-read config files, async code splitting abilities and wide plugin ecosystem. “Since it helped make my React-based development smooth as butter,” I thought to myself, “perhaps using Webpack would help to make WebGL development go just as smoothly.”

    This post follows the steps and rationale used to build a Webpack-based boilerplate for WebGL. If you just want to look at the code, you can grab the source here.

    Getting Started

    For this build system, all you need to start with is Node.js + npm. We will use Webpack as our module loader/build tool combo. Another invaluable tool in our arsenal will be Babel library for allowing use of ES6+ features. This guide assumes you have basic familiarity with JavaScript and using npm to install modules.

    We will start off by installing Webpack globally. I like doing this so I can just use webpack on the command line from anywhere:

    $ npm install -g webpack

    Webpack is a tool used to bundle files into modules. It has a vast variety of plugins created by both the Webpack team and community to allow modules to be created using both JavaScript and non-JavaScript files. You can even use it in conjunction with tools like Grunt or Gulp! We will be making use of Webpack to transpile our ES6 code to something modern browsers can read with Babel, a plugin that allow us to write our GLSL shader code like you would for a desktop application, and finally bundle all our code into a single (or multiple) JavaScript files.

    Let’s create a new directory called webgl_project:

    $ mkdir webgl_project
    $ cd webgl_project

    We will be saving a list of libraries and tools we need to package.json so let’s create one first:

    $ npm init -y

    Using the -y flag uses default values; we will edit these shortly. Personally, I’d rather edit these fields in a text editor rather than input them into a prompt.

    Next, we will install our dependencies required for development, including:

    • webpack: The webpack documentation recommends saving webpack as a local dev. dependency
    • webpack-dev-server: Used to watch files & recompile on changes, servers files
    • babel-core: Compiler used to make our ES6 code usable in modern browsers
    • babel-preset-es2015: Since version 6, Babel comes with no settings out of the box. This is a preset to compile ES6.
    • babel-loader: Webpack plugin to transpile JavaScript files before creating modules out of them
    • html-webpack-plugin: A plugin used to auto-generate a HTML file with all webpack modules included.
    • webpack-glsl-loader: Webpack plugins to load our shaders from files into strings

    Let’s install these modules all at once:

    $ npm install webpack webpack-dev-server babel-core babel-reset-es2015 babel-loader html-webpack-plugin webpack-glsl-loader --save-dev

    At this point, I usually like to open package.json and start making some edits. This is what I end up with:

    {
      "name": "webgl-webpack-boilerplate",
      "version": "1.0.0",
      "private": true,
      "description": "a boilerplate webpack project for getting started with WebGL.",
      "scripts": {},
      "author": "Dale Karp <dale@dale.io> (http://dale.io)",
      "license": "CC-BY-4.0",
      "repository": {
        "type": "git",
        "url": "https://github.com/obsoke/webgl-webpack-boilerplate"
      },
      "devDependencies": {
        "babel-core": "^6.1.19",
        "babel-loader": "^6.1.0",
        "babel-preset-es2015": "^6.1.18",
        "html-webpack-plugin": "^1.7.0",
        "webpack": "^1.12.4",
        "webpack-dev-server": "^1.12.1",
        "webpack-glsl-loader": "^1.0.1"
      }
    }

    We’ll come back to this file to add some commands to use to the scripts key. For now, let’s hop back to the terminal.

    Project Structure

    I wanted the file structure for an intial project to be simple:

    .
    ├── package.json # lists dependencies for easy re-install
    ├── src
    │   ├── index.html # html to use as template for generated output html
    │   ├── js
    │   │   └── main.js # entry point for our application
    │   └── shaders
    │       └── ... # glsl files go here
    └── node_modules/ # folder containing our dependencies

    This structure can be created with mkdir & touch commands.

    Now that we have a clear idea of what files are going to be a part of the project, let’s get a Git repository going and set up a .gitignore file:

    $ git init
    $ touch .gitignore

    Open up .gitignore up and enter the following:

    node_modules
    dist

    Since the contents of these two folders are generated, we shouldn’t commit them to version control.

    With that out the way, let us continue by setting up Webpack.

    Webpack Configuration

    Webpack can be configured a few different ways: with its own configuration files, via the command line with flags, or as a module in Gulp/Grunt. We’ll be using the config file route. Create a file in the root of your project directory called webpack.config.js. Input the following:

    var path = require('path');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    
    var ROOT_PATH = path.resolve(__dirname);
    var ENTRY_PATH = path.resolve(ROOT_PATH, 'src/js/main.js');
    var SRC_PATH = path.resolve(ROOT_PATH, 'src');
    var JS_PATH = path.resolve(ROOT_PATH, 'src/js');
    var TEMPLATE_PATH = path.resolve(ROOT_PATH, 'src/index.html');
    var SHADER_PATH = path.resolve(ROOT_PATH, 'src/shaders');
    var BUILD_PATH = path.resolve(ROOT_PATH, 'dist');
    
    var debug = process.env.NODE_ENV !== 'production';
    
    module.exports = {
        entry: ENTRY_PATH,
        plugins: [
            new HtmlWebpackPlugin({
                title: 'WebGL Project Boilerplate',
                template: TEMPLATE_PATH,
                inject: 'body'
            })
        ],
        output: {
            path: BUILD_PATH,
            filename: 'bundle.js'
        },
        resolve: {
            root: [JS_PATH, SRC_PATH]
        },
        module: {
            loaders: [
                {
                    test: /\.js$/,
                    include: JS_PATH,
                    exclude: /(node_modules|bower_components)/,
                    loader: 'babel',
                    query: {
                        cacheDirectory: true,
                        presets: ['es2015']
                    }
                },
                {
                    test: /\.glsl$/,
                    include: SHADER_PATH,
                    loader: 'webpack-glsl'
                }
            ]
        },
        debug: debug,
        devtool: debug ? 'eval-source-map' : 'source-map'
    };

    Let’s take a look at what’s going on here:

    File header

    Firstly, we import some modules such as path and our html-webpack-plugin. We also define some constants containing the absolute paths to the folders we wil keep various types of files in, along with the entry and output paths.

    We also check for the presence of the environmental variable NODE_ENV to determine whether to build production or development bundles.

    entry

    The JavaScript entry point of our application.

    plugins

    The html-webpack-plugin generates HTML files that already have appropriate script and link tags to bundled JS and CSS bundles. We’ll make use of that plugin with a few options. title is the value of the title tag. template is a path to the HTML file we want to base our index.html off of. Finally, inject allows us to control where our script tags are being created. Valid values are body and head. We will set up our HTML template after configuring Webpack.

    output

    Here we define where we want Webpack to place the modules it creates.

    resolve

    resolve’s root key lets you tell Webpack which folders to search in when importing one file into another. For example, imagine the following file structure:

    .
    ├── js
    │   ├── Component
    │   │   └── Dude.js
    │   ├── main.js
    │   └── Utility
    │       └── VectorUtils.js
    └── shaders

    The contents of js/utility/VectorUtils.js look something like this:

    export function getDotProduct(v1, v2) {
        // gets & returns dot product
    }

    Without setting the resolve.root property in our Webpack settings, the way to include VectorUtils.js in Dude.js would look something like this:

    import { getDotProduct } from '../VectorUtils.js';
    
    export default class Dude extends Person {
        // use getDotProduct somewhere in here
    }

    After setting resolve.root to include our src/js path, we can treat that as a root directory that Webpack will search through to find other modules. This lets us write import paths like this:

    import { getDotProduct } from 'Utility/VectorUtils.js';
    
    export default class Dude extends Person {
        // use getDotProduct somewhere in here
    }

    Since we’ve also added src as a root path, we’ll be able to include shaders just by writing something like this:

    import boxShader from 'Shaders/boxShader_v.glsl';

    This makes importing files easy, no matter what directory you happen to be working in.

    module

    The loader key on module tells Webpack which files to load into modules, and how to load them. We’ve defined two loaders: one for JavaScript files, and one for our GLSL shaders. test is a regular expression that will bundle the files that match it; obviously for a JavaScript loader, we want Webpack to find modules ending with .js. We don’t want Webpack to do anything with our dependencies unless we explicitly import one, so we tell Webpack to exclude them. The loader key is the name of the Webpack plugin used to process JS files. Since we want to be able to write using ES6 syntax, Babel will handle that responsibility. Because Babel 6 comes with no options out of the box, we need to tell it to use the es2015 presets package we installed earlier. Enabling directory caching will give us faster compile times so of course we enable that.

    Our last loader is for our shader files, ending with .glsl. Here, we simply tell Webpack to use the webpack-glsl loader.

    debug

    Some loaders will perform optimizations when building bundles depending on whether the debug key is set to true or false.

    devtool

    At the moment, this tells Webpack which style of source maps to use. source-map is recommended for production use only, so we’ll use eval-source-map which is faster and produces cache-able source maps.

    With that, our configuration of Webpack is complete. Not too bad, eh?

    Let’s re-open package.json and add some commands to scripts that will make interacting with webpack a bit easier:

    {
        // ...
        "scripts": {
            "build": "NODE_ENV=production webpack --progress --colors",
            "watch": "webpack --progress --colors --watch",
            "dev-server": "webpack-dev-server --progress --colors --inline --hot"
        },
        // ...
    }

    Webpack will check for webpack.config.js and use it if found. I’m using flags to show build progress and to give the output a bit more colour. Any key added to the scripts object can be used by running npm run <keyname>. This gives us three easily accessible commands:

    • NODE_ENV=production npm run build: Builds our project into /dist/. Uses a flag to tell Webpack we want loaders to build production-mode modules.
    • npm run watch: Builds our project and watches files for changes, re-builds on change.
    • npm run dev-server: Builds our project and watches files for changes, also serves files from a web server. The --inline --hot flags enable Hot Module replacement, which will update your page without any user input. You can read more about HMR in webpack-dev-server’s documentation.

    Now we have one thing left to do, and that is to create our index.html in /dist. This is what the contents look like:

    <!doctype html>
    <html lang="en">
        <head>
            <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
            <title>{%= o.htmlWebpackPlugin.options.title %}</title>
        </head>
        <body>
            <canvas id="canvas"></canvas>
        </body>
    </html>

    That weird value used in the title tag allows Webpack to change the page’s title depending on the value of the title key passed to html-webpack-plugin. As you can see, no script tags are needed - Webpack will handle that for us.

    And with that, the boilerplate is complete. “But Dale,” you exclaim, “I don’t see the point of this. You made a simple Webpack config, so what?”

    Motivations

    My main motivations behind this came from my own experiences trying to learn WebGL. I’ve noticed that many WebGL tutorials will demonstrate shader usage in WebGL in one of two ways:

    1. Write a JavaScript string containing the shader code.
    2. Have a script element of type x-ver-shader and grab the element’s content from JavaScript.

    Personally, I don’t like either of these solutions. The first one is just ugly, unreadable and difficult to maintain yet most of the WebGL resources I see introduce shaders using this method. The second is slightly better, but I prefer to keep shaders in their own files, where I can use an editor with syntax highlighting to make readability a bit easier.

    I completely understand why tutorial writers do this. WebGL is complex, and wrapping your head around everything needed to render a simple triangle in shader-based GL can be a lot to take in at once. Once you get your head around those concepts, though, then what? What’s the best way to deal with shaders moving forward as a project scales? I’m not claiming this boilerplate is anywhere close to the best, but for me it works. Hopefully it does for you too (and if it doesn’t, please open an issue/PR on the GitHub repo and let me know).

    Mini-example: Hello Triangle

    Let’s go through a short example of how one would potentially use this boilerplate to easily load GLSL shaders. Imagine we have two shaders in our src/shaders directory, called box_vert.glsl and box_frag.glsl containing our vertex and fragment shader, respectively. No need for <script> tags or multi-line strings! Just import it when you need it, where you need it.

    // import our shaders and store them variables
    import boxVertShaderSource from 'shaders/box_vert.glsl';
    import boxFragShaderSource from 'shaders/box_frag.glsl';
    
    const canvas = document.getElementById('canvas');
    const gl = canvas.getContext('experimental-webgl');
    
    // ...
    
    // time to create our shader program with a handy function!
    // it expects the gl context and strings containing shaders.
    let program = createProgramFromGLSL(gl, boxVertShaderSource, boxFragShaderSource);

    That’s all!

    I hope you found this useful in some way. If you have any suggestions on how to improve the boilerplate, please open an issue on the GitHub repo.


              dale.io v4        

    I recently decided that my personal site needed a tune up. No longer happy with the current design, I decided to throw it away completely and to start from scratch. Here are a few things I thought about during the process of re-writing the website.

    Choosing a backend

    Right off the bat, I knew that I wanted to continue using a static site generator for my homepage. Tools like WordPress and Ghost are interesting but for my use case I found both to be overkill. After taking a look at some of the most popular static site generators1 around and playing around with them, I had a better idea of the current tool landscape at the time.

    There are a bunch of static site generators these days written in a variety of languages. I took a look at a few JavaScript-based ones, such as Hexo and Metalsmith - both on opposite sides of the feature list spectrum. Metalsmith is completely barebones to the point where all functionality is added via plugins. This is a pretty neat idea but I was looking for something that was more balanced between features and do-it-yourself mentality. When I was initially researching static site generators, Metalsmith had a lot of issues with plugin version rot as well. The idea of everything being a plugin is pretty neat - as long as these individual plugins are maintained! On the other end of the feature spectrum, Hexo reminds me a lot of Jekyll but written in JavaScript and more of an emphasis on blogs. This wasn’t enough to pull me away from Jekyll, a tool I already knew.

    On the Ruby end, I took a look at Middleman and Jekyll. Middleman is a great competitor for Jekyll with some neat features. It allows for incremental building of your site, a feature that Jekyll will be lacking until its v3 release. I have not had much of an issue with build times with Jekyll but I can see how a huge site with thousands of pages would not scale well without incremental builds. Middleman also offers more in the way of a default template and such. However, in the end I stuck with Jekyll. Recent additions to Jekyll such as collections make building non-blog and hybrid websites with Jekyll much easier.

    Choosing a colour palette

    I am not a designer - I think the previous designs of my site show as much. As much as I wish I did, I just don’t have the eye for colour. Working with designers in the past always blew my mind as to how easy it came to them. I know I could take the time to learn colour theory (and perhaps I will someday) but at the time I was more focused on redesigning my site quickly, not leisurely learning something new. This made the simple task of choosing a colour palette a long and tedious process. There are a few tools available to help one come up with a colour palette, such as Paletton or Adobe Color CC, formerly Kuler. After fiddling for them for a few days on and off and having no success, I decided just to choose a colour I liked: blue. Once I had a colour chosen for the header, I was able to build the rest of the site off of that.

    While I’m pleased with how the header turned out, I still feel as if the rest of the site can possibly use a splash of colour here or there just to make things a bit more appealing. I couldn’t really see any place to fit these accent colours in a way that felt natural. This will probably be something that will to be iterated on over time.

    The Holy Grail that is Flexbox

    Flexbox is the best thing to happen to CSS. I’ll scream it from the mountain tops if needed because it’s true. As long as the only browsers your site needs to support are IE11+ or an evergreen browser, you can (mostly2) say goodbye to hacky CSS rules to position elements on a web page.

    The great thing about Flexbox is that it’s flexible (yet another surprise!) and will adjust its size across different screen sizes if the developer desires it. For example, the page header makes use of flexbox to make sure it looks great on both large and small screens. All I need to do to get my header to scale the way I wish is use the following CSS rules on the wrapper for my header block:

    .nav-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    This sets the wrapper rendering box style to flexbox and centers all the elements along both axis. When the screen width is below a certain size, we can use the following rules to change the direction of the main axis from a row to a reversed column so each header element has room to breath and appears in the proper order:

    @media screen only and (max-width: 600px) {
        .nav-wrapper {
            flex-direction: column-reverse;
            align-items: stretch;
        }
    }

    I’m using a few more rules to align individual items, but that is the basics of it. Flexbox has enabled me to re-arrange the entire site with just a few CSS rules and I think that is awesome. I’m using it for any part of my page that requires even a tiny bit of element positioning and it’s been very easy to both learn and use. Offloading a lot of the grunt work to the browser while providing a fewer set of CSS rules was definitely a smart move, and I’m excited to see what further revisions to the spec bring.

    Consistency between old and new

    In the redesign, I decided to make better use of header tags to denote subheading rather than bolded text. Unfortunately, a few of my older blog posts made liberal use of the old and bold way. I took this opportunity to flex my bash and regex muscles and see if I can come up with an elegant way to fix this in one swing.

    My first step was to construct a regular expression that would find all the old headers. The old headers took the form of bold text which, in Markdown, meant the text was surrounded by two asterisks on each end. The header would be the only string of text on the line. With this information, I came up with the following regular expression and used it to find all headers in my _posts folder:

    git grep '^\*\*.*\*\*$'

    This regular expression looks for any length of characters in between two literal asterisks that bookend the entire line. After testing that the regex worked, I used a combination of the find and sed commands to do a massive search and replace with the following command:

    find _posts -type f -exec sed -i '' 's/^\*\*\(.*\)\*\*$/\#\#\# \1/g' {} \;

    The above command looks for files in the _post directory, and for each file runs a sed command asking it to edit files in-place without a backup3. The regular expression now creates a group around the header text so we can use it in the replace with the proper symbol denoting an h3 tag: three literal pound characters. Now all blog posts with headers will conform to the new style.

    Design & organization choices

    Aside from choosing site colours, I spent the most time thinking about how I wanted to layout my website. My previous v3 design was bland and didn’t make the best use of available space. I spent a lot of time looking at other Jekyll blogs for some inspiration but I found many of them to be overly busy or overly minimalistic. I would draw layout after layout on paper until I came to the one you see now. Moving the persistent navigation block from the side to the top allows me to take advantage of all the below space: this comes in handy when scaling the site to work on multiple resolutions.

    Since the beginning of 2015, I’ve been writing reviews on the games I have finished for fun. After deciding to add these reviews to the site. As of the launch of the redesign, only one of the eight reviews I have written are published but I’ll be editing the others and getting them online shortly. Right now, they are a separate entity from the other blog posts and I’m not sure if this was the best idea. This home page is a place for me to talk about what I love doing. For the past few years, this has solely been about programming. I’d like to expand that to writing about other subjects but dividing posts up into ‘blogs’ and ‘reviews’ may limit myself in the future. I could (and probably will) just treat everything as a blog and use tags or categories to group the related info. Design choices like this are what I spent the most time on during this redesign. Implementing the ideas I come up with are no problem but deciding whether I’m making the right choice on certain decisions is an area where working on a team definitely benefits.

    There are a bunch of other small but useful additions I’ve made. If you haven’t noticed, I tend to go off on tangent mid-paragraph. Making use of footnotes allows me to do this without breaking up the flow of content, and the Kramdown markdown renderer used by Jekykll makes usage of footnotes very easy. Some posts can have a header image, such as this one. If you’re reading this on a small device, you may not see it - I’m currently thinking of a good way to display the header image without making all of the above-the-fold content on a mobile device nothing but headers. Most of the small additions are there to make writing content easier for me and for said content to display correctly, no matter the screen scale.

    In the end

    I’m pretty happy with the layout I ended up with. I find easier on the eyes than previous designs. Standing here with the project finished, I already have a list of things I’m no longer happy with and will work on for the next iteration. Personal projects like home page redesigns give me an opportunity to experiment and play but if I don’t limit myself and consider the project ‘finished’, I’ll never release it. Do you have any suggestions about the design? Love it? Hate it? Let me know in the comments!

    1. According to StaticGen which ranks generators based off of GitHub stars and forks. 

    2. While much better than the old way of doing things, Flexbox itself is not perfect. Check out Flexbugs for more info. 

    3. Not recommended. 


              Jump Around        

    A few months ago, I wrote a blog post about my experience playing around with the Phaser game engine. I ended up making a short 2D platformer game called Jump Around. I’ve uploaded the source onto GitHub for those who are interested in taking a peek. It was a great experience in which I learnt quite a bit, so without further ado…

    Initial Design & Scope

    My initial goals for the project were pretty simple:

    1. Make a short 2D platformer game.
    2. Each level would fit on the screen; no camera work needed.
    3. Don’t focus too much on making the ‘cleanest’ code possible on this project. This is more getting a feel for game development again.

    I wanted to keep things pretty simple, as this project was meant to not only evaluate Phaser for future projects but also getting my feet wet with some simple game design. It seems almost like a rite of passage nowadays for game developers to make a 2D platformer, so I decided to go for that. Jump Around is inspired by platformers such as Super Meat Boy, where the emphasis is on pixel-perfect platforming as quickly as possible. The smaller levels in Super Meat Boy that would fit within the initial camera frame were always pretty interesting to me. The small characters moving quickly around an environment in which danger is visible everywhere made for a strange mix of emotions. Upon entering a level, I’d both feel terror at the level that I was to get through, and excitement at the challenge ahead.

    I originally scoped for around 6 levels, but I cut it down to 3 as I came to a realization: good level design is hard work! Once the game mechanics were implemented, the majority of my time was spent on figuring out how to be clever with level design. This wasn’t my goal for the project so I decided to cut the level count in half so I could move on to another project sooner. Aside from that, I feel like I did a good job with my initial design and didn’t end up with much feature creep. The only feature I ended up missing was using “Jump Around” by House of Pain as the obvious background music choice. I planned on distributing the source code for this and I’m pretty sure I would not have the rights to distribute that song. This is an issue I also had to look into regarding art I used (gasp, could this be… a segue?!).

    Art is hard

    Although I have tried many times, I just can’t draw very well. This can be a problem when you are a lone programmer working on a video game. Thankfully, there are tons of free art resources online. One of these is the great website Open Game Art. I ended up purchasing a donation-ware art pack from an incredibly talented & generous artist named Kenney. I’ve seen him post on /r/gamedev before, offering free art packs under liberal license terms for people like me who aren’t so artistically inclined. While this was a decent solution to not being able to produce art myself, in retrospect I think I should have kept it simple and gone with a more abstract art style.

    As said before, I eventually wanted to release the source of Jump Around. However, I wasn’t too sure about the license to redistribute the assets. Thankfully, Kenney includes a LICENSE.TXT in his zip of art which helpfully states that the assets are released under the liberal CC0 license. As long as I attribute him, I should be okay to redistribute the art I used and modified for my purposes.

    Most of the audio I use is also from Kenney’s donation pack, but the incredibly cheezy awesome end of level noise that plays was a clip I found off of freesound.org. This is another great resource for developers just looking for simple or placeholder sounds under a variety of licenses. Thankfully, this asset is also CC0 so the game can be fully redistributed with all assets intact.

    Resolution is confusing

    Another issue I ran into was answering the question “What resolution am I targeting with this game?” I was making this game for web browsers running on a desktop. I probably should have consulted the great Valve Hardware Survey to get a sense of what kind of resolutions people were playing at. While 1920x1080 is the most popular resolution, it only had 33.48% of user share as of this blog post. In second place was 1366x768 with 26.80%. I ended up hardcoding my game’s resolution at a very strange and non-standard 1050x714. I did this because that was the size of my level in tiles (50x24 tiles, as each tile was 21x21). In retrospect, this was a dumb idea. While I haven’t exactly alienated either of the two largest resolution groups (according to Valve), it doesn’t scale up or down at all. I probably should have spent more time on making sure the scaling worked; at one point in development, I found myself even looking at options to use the fullscreen API. In the end, I decided to push that learning exercise to my next project.

    Another consideration was “Could this game work on a mobile device?” Due to the decisions I made based on the art and not bothering to scale anything, it wouldn’t be a great experience. However, mechanically, it could work. I ended up adding a toggle to cause the player to continuously jump, and I noticed the game was actually kind of fun when I left it on. It felt more like “Pogo Around” than “Jump Around” but it was still fun. I could have left that setting on for the mobile version and had the user touch either side of the screen to simulate the left/right cursor movements. Using two fingers instead of one could make the player run… or… pogo-run… rather than pogo-walk. In the future, I may revisit this project and try to add that in, but for now it was out of scope of what I wanted to accomplish.

    If you’re interested in trying this ‘pogo’ mode for yourself, just hit the F key while playing the game. It adds another layer of challenge… think of it as hard mode!

    Architecture & Tools

    At first, I wasn’t really sure how to structure this project. I’ve done game development before but never in JavaScript. I found a very useful blog post called Building your Phaser Projects with Browserify that was helpful in getting the file structure of a game in place.

    Since the majority of my game objects were simple, I was able to make to do with simple objects that didn’t follow any particular programming pattern. Some variables, such as current level and overall game time, were kept in the game object, while each state kind of dealt with it’s own area. After the assets are preloaded, the menu state is spun up and waits for user input. After that, the level state is entered. The level state checks what level it should be loading via the game object and starts to create the needed platforms and tiles.

    The levels themselves were created using the fantastic Tiled map editor. One neat feature of Tiled that I liked was creating Objects on the map that can store any properties you wish. I ended up doing this to store quite a bit of data in the level itself, such as player spawn position, level key position, and starting positions of moving platforms, as well as their speed, distance and initial direction. This allows me to use a single state for each level with little to no code change needed to properly load each level. I feel like I do cheat a bit by passing the player object through each level state to retain some data like how many times the player has died, but it seemed like the simplest solution so I went with it.

    Phaser is a pretty nice framework but I ran into some issues. Currently only a single tile layer from Tiled can be marked as a collision layer. When Phaser moved from version 1 to 2, it lost some of it’s advanced camera capabilities such as the ability to zoom; I believe the current camera can only pan by default. Neither of these are dealbreakers, but they would be nice to have features. I still think Phaser is one of the best JS engines you can use right now. It has a decent sized community and there are always people on the IRC channel willing to help (such as myself!) I’ve read that Phaser 3 may be getting a ES6 makeover which makes me very excited for the future of the engine.

    However…

    Conclusions

    I had a blast making Jump Around, and I’m glad I finished the project. I learnt quite a bit about a variety of topics. I now have a huge amount of respect for great level designers, as I spent quite a bit of time thinking of how to make each level progressively more interesting. I’m not sure if I’ve succeeded but I tried to do something new in each level. I also learnt a bit about 2D animation to animate the player, audio codecs & conversion to get the sound effects working, and some basic game design as a result of the project.

    One area that I didn’t get to focus on as much as I would have liked was the game programming itself. I think this is because I used an engine which did a lot of it for me. Because of this, my next project will most likely not use an engine at all. I don’t want to do everything myself (not yet at least) so I’ll probably use a helper library to handle things like asset loading, input reading and window creation (if targeting desktops rather than the web). I plan on reading some of the excellent Game Programming Patterns book to get a better feel on how game architecture works and how things fit together.

    So that’s Jump Around! Feel free to try the game out and check out the source if you’re interested.


              Giffy: A Postmortem        

    I’ve recently finished up a small side project that I started quite a while ago called Giffy. It wasn’t a particularly large or complex project but the motivation to continue working on it diminished shortly after starting. Now that the project is done, I wanted to write a post discussing some of the challenges I faced and thoughts I had.

    On Side Projects

    Working on a side project is a great way for any developer to learn about a new technology, further develop an existing skill or just get some creative juices flowing. However, I’ve found it much easier to start a project than to actually finish one. There can be many reasons why finishing a side project can be hard. For Giffy, those reasons were feature creep, scope and changing personal thoughts on images on the web. While side projects can be a great place to experiment, too much experimenting led to a feature list that was much too long. This can be mentally draining when done close to the beginning of a project. I wouldn’t recommend it. I’ve learned a lot about looking at a feature and breaking it down into smaller features. Working in smaller chunks makes it easier for me to focus on the current objective and to experience the thrill of seeing a feature come to life more frequently.

    What is Giffy?

    Giffy is simply an image hosting service for gifs. You can tag gifs that has been uploaded, and find similarly tagged gifs. If you don’t have any gifs to upload, you can create one in the browser using your webcam. Once you’ve created your gif, you have the option to upload it directly to Giffy.

    Some features, such as adding & deleting tags, require an account. One of the features I ended up cutting was a permissions system that would let the admin define roles and associated permitted & forbidden actions (eg: upload a gif, delete a tag). Bits and pieces of the permissions system exist in the code, but it was never finished.

    There were a bunch of social-networky features I cut from the feature list. I had to step back and remember what my goals were for this project:

    1. Learn more about Angular
    2. Learn how to upload images directly to an Amazon S3 bucket from the browser via CORS
    3. Learn how to create a gif from a webcam using WebRTC and upload that gif directly to S3

    Here on the other side of the project, I feel that I’ve completed these goals. Learning not only how to cut unnecessary fat from the feature list, but also how to divide my main tasks into smaller, more manageable sub tasks was important to keep me going towards the finish line. Focusing on the important features to cut can be hard in a project that exists solely for learning and experimenting, but for some people it may be necessary if that project is ever going to see the light of day.

    The Backend

    There is not a whole lot of magic happening on the backend. All it is really doing is serving HTTP requests and fetching data from the database. I’m using the Bookshelf ORM to handle all things database, backed by Postgres. It’s a pretty nice ORM that makes mapping models to database tables incredibly easy. While I found that it lacked some basic features such as limiting the amount of rows returned, it’s possible to use the underlying Knex.js library to perform raw SQL queries. Other libraries I use are bcrypt for password salting, shortid to generate a unique file name for gifs and Amazon’s AWS library for Node.js

    In terms of design, I make heavy use of promises instead of callbacks in my API code. Promises are very easy to use and, in my opinion, make ones code much more readable (goodbye, callback hell).

    One design choice I regret is choosing session-based authentication over token-based. The way I originally designed the application was a standalone API that would be able to handle requests by clients on any kind of device. I ended up with more of a Rails-type monolithic app so cookie-based sessions were pretty easy to implement. From my limited understanding, cookie-based authentication doesn’t work very well on mobile devices. A much simpler solution would be to include a token that identifies the user with each request. Ah well, lesson learned for my next side project!

    Angular

    It really bothers me that I need to use a plugin for a framework just to do something as simple as nested views. I feel like a framework that focuses on building single-page apps like Angular should have this built in. Perhaps I’m being nit-picky but it’s a design choice I find baffling. Also, the way Angular differentiates services, factories and providers is a little strange and seems arbitrary.

    Aside from those points, using Angular has been mostly painless and made developing the web app portion of Giffy easy. I don’t think I was pushing the limits of the framework or anything. Most of the challenges I faced came with getting sessions to work between Angular and Express, or routing static assets; nothing specific to Angular compared to other single-page app frameworks.

    In the end, I was mostly pleased with Angular, and would consider it in future projects.

    EDIT (2015-01-17): After some consideration, I’m not too sure if I would actually use Angular for another personal project. I’m not a huge fan of how Angular 2 is looking.

    Direct to S3 Upload

    One feature I really wanted in Giffy was the ability to upload a file directly to an Amazon S3 bucket directly from the browser. I wanted the API behind Giffy to solely handle requests and to fetch the appropriate data from the database. I found an article on Heroku’s dev centre on the subject, which makes use of Amazon’s AWS library for Node.js. The library is used to create the proper signature for the upload request, which contains information like where in the bucket to put the file, expected file size, and authentication to the bucket. Once the image is successfully uploaded, a call to the API is made to register the newly uploaded gif in the Giffy database.

    The Heroku article also included a link to a client-side S3 uploading script. I quickly ran into some limits with the script though, such as not getting as much metadata as I would have liked about the file with the upload completion callback, or not supporting the ability to upload a binary image blob to S3. I ended up forking the repo and made the necessary adjustments, which you can find here.

    While this solution is novel, I kind of regret designing it this way. This has to due with how I now feel about gifs in general. Gifs can cause unnecessary repaints in some browsers, which can greatly affect performance. For Giffy, where I could potentially have a page full of gifs, I was worried that performance on some older desktop and laptops or mobile devices would suffer.

    There have been some interesting ways of solving this problem. For instance, Twitter converts gifs to mp4 and shows users the video file instead. I thought this was a pretty neat solution. Not only will a mp4 file be much smaller than the average gif, but the user also gets control over the playback of the image. This is most likely the solution I would have chosen for Giffy as well. However, since Giffy uploads the image directly to S3, it wasn’t feasible for this iteration of the project. If I decide to return to the project, it would be the first thing I would change.

    Create gif from webcam

    The final feature I wanted to implement was the ability to use one’s own webcam to create a gif. When I was working as a contractor for Mozilla Webmaker last year, this was an idea the frontend team played around with for the Webmaker Profiles feature. I thought it was fun and decided to implement it into Giffy.

    My implementation is pretty simple. The creation of gifs is done by capturing frames via button click. I found a gif encoder written in JavaScript that I use to create the gifs. When one clicks the `Capture` button, the current frame displayed in the video tag is copied pixel by pixel to a canvas. The image data stored in the canvas is used by gif.js to create one frame of the gif. gif.js uses web workers to create the gif in the background, leaving the interface responsive.

    For one crazy second, I actually considered writing my own gif encoder in JavaScript. It would have been an interesting project, but way out of the scope for Giffy. Other things I would have liked to add would have been some tacky Instagramish filters and the ability to record a gif for N seconds, rather than having to add each frame manually.

    Final Thoughts

    Some other features that were cut from the list were allowing users to add gifs to a favourites list, unit tests, and allowing user comments. The ability to search by tag was another feature I cut. In retrospect, none of these features would be particularly difficult to implement at this point but you have to draw the line somewhere on some personal projects or they will never end. There are other potential projects that I am currently more interested in spending my time on.

    I learned quite a bit from working on Giffy. Aside from the numerous technical and design lessons I learned, the lessons about scope and feature creep are what really hit me: breaking big features up into smaller ones and setting attainable milestones that end with some feature that can be demonstrated in at least a small fashion. Working on Giffy one huge feature at a time made it feel like a chore, but now that it’s finally over, the satisfaction of putting the ‘Complete’ label on a project makes it all feel worth it. Kinda weird how that happens.

    Feel free to check out the source code on my GitHub repo. A demo of Giffy is also available. I’ll be writing a cron script to clean out the database & S3 bucket every few days. Please don’t abuse the demo site! Feel free to fork, open pull requests, or leave feedback!


              Playtime with Phaser        

    For the past few days, I’ve been playing around with Phaser, a game engine written in JavaScript. I decided that I’d like to experiment with game development for the next month. It has been a career path I’ve considered on and off throughout my life, but I need to put the idea to the test: do I actually want to make games, or do I just find the thought of doing it appealing? Let’s find out!

    Struggle of Inaction

    A lot of new game developers (including myself) seem to fall into a trap. Do you want to make a game, or do you want to learn how to program games through engines? My problem was that I was obsessed with the idea that I had to start out learning how it all worked from the lowest level. “If I use an engine,” I would think to myself, “and it limited my grand ambitious game, whatever would I do?!” I would then attempt to learn OpenGL, get frustrated trying to tie everything together into something that resembles a game and give up.

    The fear of using an engine without fully understanding how games work was a huge concern, although I don’t know why. I don’t understand how my car works but that doesn’t stop me from using it. I think I was partially making excuses to justify the Not Invented Here Syndrome I was experiencing. If I really want to make games, an engine is probably the best place to start. When I run into issues due to gaps in my knowledge, I’ll just fill those gaps in as I need to.

    Select your Engines

    With a renewed sense of resolve, I now had to choose a language and engine to work in. I decided that my first project would be a simple platforming-style game so heavy engines like Unreal or CryEngine seemed a bit over-the-top. Unity is another very popular engine with indie and hobbyist developers, and has the ability to export your game to a variety of platforms. In the end, I felt forced into using their GUI app to get stuff done. I’m just not a big fan of using mice!

    It had been a few years since I last looked at JavaScript game engines. Back then, audio on the web wasn’t well-supported. The Web Audio API is now here but still doesn’t have full browser support (looking at you, IE). Regardless, I feel like JavaScript speed increases, audio API improvements and the growth of the JS game development community has made this a good time to try out writing a game in JavaScript.

    There are quite a few mature JS game engines around, such as MelonJS, ImpactJS, and Phaser. I ended up choosing Phaser for a few reasons:

    1. The Website looked good (Hey, what can I say, this actually matters to me)
    2. Excellent examples site and documentation. These two were fairly important in my final decision. The examples site contains many (you guessed it) examples of different ways to implement everything from animation via spritesheets, using the camera, music and more. I’m a learn-by-example kind of person, so this was perfect for me. The documentation is pretty great, and the source code itself is well commented and easy to understand.
    3. Price & license. ImpactJS costs $99USD for a license. While you receive the source code with your download, you can’t contribute upstream from what I understand. Both MelonJS and Phaser are open source under the MIT license. I’d prefer to use an open source engine if I could, as I’d like to contribute any bug fixes I may come across with the engine itself.
    4. Built-in support for levels created with Tiled, a tile-based map editor. This wasn’t a huge deal but it is nice to have.

    Both Phaser and MelonJS seemed equally capable. I found more questions asked on StackOverflow on Phaser (287 vs MelonJS’s 47 as of this post). While questions on StackOverflow isn’t the greatest metric to judge an engine on, I just wanted to make a quick choice and this shallow justification did the job.

    Initial thoughts & issues

    Now that I had my engine chosen, it was time to get started. This is where I encountered my first roadblock: I had no art. I needed some tilesets and character sprites to start off with. Luckily, there are plenty of freely licensed artwork packs available for those of us who are not artistically inclined. One such pack, Platformer Art Complete is a huge pack of tiles, items, character sprites and more made by an awesome dude named Kenney.

    After creating a small simple level with a few platforms, I loaded it into the engine and noticed that some platform tiles were not the ones I selected to use in Tiled. The initial spritesheet included in the pack that I was using had some excess art on the right margin. Spritesheets work by providing the size of each frame in the sheet, and the amount of rows and columns of frames. So if Tile N is on row 3, column 3 of the sheet, and each frame is 50 pixels square, then by grabbing the subsection of the image at x 100, y 100 should get us the desired frame. However, while Tiled was smart enough to remove the excess tiles from the spritesheet, there is no way Phaser could possibly know that; it just knows how big each frame is and the amount of frames per row and column. I found a version of Kenney’s platformer base pack that was made to work with Tiled. After using this, my problems went away. When I attempt to create my own art, I’ll be able to specify how the spritesheet is layed out. Until then, be mindful of your art!

    After ensuring the level was being rendering correctly, I added a simple character with basic move left/right controls. So far, so good. I decided to test out the camera functions by creating a level larger than the canvas/game viewport of 1280x720. For some reason, this caused my player sprite to get caught on some invisible walls. I did some research and found this thread with some else describing a similar issue. Luckily enough, a Phaser developer chimmed in stating that he found the cause and that it had been fixed in the dev branch. Thankfully, using the dev version of Phaser seemed to fix it.

    So far, I’m pretty happy with Phaser. Just getting things happening on a screen and reacting to input is pretty awesome. Hopefully I’ll have something to show off in my next post!


              Back to Blogging, Back to Game Dev        

    It’s been a few months since I’ve last written a post here on the blog. I’ve been working with Mozilla on the Webmaker project since school ended. Not only have I been having lots of fun doing a ton of front-end work but I’ve also been learning from the brilliant people on my team. Working at Mozilla has been and continues to be an awesome experience but that’s not what this blog post is about.

    Once again, I’ve gotten the game development itch. When I think back on the past few years, I realize that the itch never went away but school took a priority. Additionally, my RSI was so bad that I couldn’t really afford to use my hands for anything but programming assignments. Since then, my hands have significantly improved. I’m now able to work full work weeks and also do programming and gaming on the side. As things have been going so well, it seems like a good time to scratch the game development itch.

    As usual, I spent quite a bit of time agonizing over what language and technologies to dedicate my efforts towards. In the last year, I’ve worked a lot with C++ (with WebVTT in Firefox) and JavaScript (with Webmaker). I have had prior game development experience in C++ (SFML) and C# (XNA). I also understand that Unity is a popular choice for those who want to start designing a game right away. After careful thought, I realized that designing a game right away is the exact opposite of what I want to do. Perhaps I’m being stubborn, but the desire to learn how games actually work is far greater than the desire to started working on a game right away. I’m also interested in the demoscene, which creates audio/visual demos of… well, anything. Just do a YouTube search for ‘demoscene’ to see what I am talking about.

    Actually, while writing that last paragraph, I believe I thought of why I want to learn how games (and graphics) work. There is a lot of room to be creative through programming. The cool graphics or games one can create with code is proof of that. Right now, I have all these cool ideas in my head for potential demos and games. The problem is I have very little technical knowledge on how to get those ideas onto the screen. So it’s time to remedy that! The languages and technologies I’ve decided to go with are GLFW to create the window creation, OpenGL for graphics and… that is it for now. I’ll be working on a 2D tetris clone, and I’ll be blogging about it as I go. I figure that is a good project to start with. My first goal will be to draw a box on the screen. Once I learn exactly how to do that, I’ll be back with another post!


              WebVTT: The Middle        

    It’s been a while since my last post about WebVTT. A lot has been going on since that last post in the beginning of March. The OSD team gave two presentations about WebVTT to Mozilla Toronto: one during a class visit to MoTo and another during MoTo’s Open Web Open Mic event to some of the Toronto open source community. Both events were a lot of fun! I was surprised by how excited some people seemed to get when they saw WebVTT. When you work on a project, it can be hard to take a step back and see the impact your project has on others, especially when you can get so invested in said project. Good job team!

    I haven’t been able to spend as much time on WebVTT as I would have liked over the past month. After the push to get things working for the first Mozilla Toronto demo, I had an avalanche of final assignments fall onto me. Now that they are finally behind me, I’ve been able to get back into the swing of things.

    Review Issues

    While I’ve been busy with school, rillian has been working on the patch. Thanks a lot, rillian! There have been several iterations of the patch since. As always, you can see the latest updates on the Bugzilla bug. It’s been reviewed quite extensively by bz and Ms2ger who brought up a few issues.

    One of the issues had to do with nested templates. We were using nsTArrays like this: nsTArray<nsRefPtr<TextTrackCue>>, which reads as ‘an array of nsRefPtr which refer to TextTrackCue objects.’ Apparently, the >> at the very end was being interpreted as the >> operator on some older compilers. So we just added some whitespace to pad out the characters: nsTArray< nsRefPtr<TextTrackCue> >. Easy fix!

    In the review, it was suggested that we convert nsAString out parameters in class getters to DOMString, a relatively new class in the Mozilla codebase. I went ahead and did this, but it was not an easy fix. In fact, it was pretty messy, and involved extracting a StringBuffer from an nsAString object and using that to set the value of the DOMString out parameter.

    The code used to set getters went from this:

    void GetKind(nsAString& aKind) const
    {
      aKind = mKind;
    }

    to this:

    void GetKind(DOMString& aKind) const
    {
      aKind.SetStringBuffer( nsStringBuffer::FromString(mKind), mKind.Length() );
    }

    Yikes. That’s what I call messy. To be fair, this is the only way to set the value of a DOMString from an nsString, the type used internally to store strings.

    It didn’t get accepted. In retrospect, it would have been easier to just adjust the internal members of the TextTrack* objects to use a DOMString rather than a nsString. Once I clarify with others that this is the best way to go about with this fix, I’ll probably end up doing just that.

    The first fix ended up making its way into the patch on Bugzilla. The pull request on GitHub is still open due to the DOMString issue. If you’re interested in following that particular issue, you can check it out here.

    Exceptions

    Something I’ve wanted to start adding to the WebVTT DOM implementation for a while now is exception handling. Firefox’s C++ code doesn’t use exceptions; I’m talking about JavaScript exceptions. For instance, if one tries to use the removeCue(cue) method on a TextTrackList JavaScript object which doesn’t contain cue, a NotFoundError exception should be thrown.

    In order to do this, we first need to edit the WebIDL file which defines the DOM interface. We must add a [Throws] declaration in front of every method which throws an exception. For example, in TextTrack.webidl:

    [Throws]
    void addCue(TextTrackCue cue);
    [Throws]
    void removeCue(TextTrackCue cue);

    By using some crazy wizardry, this creates the necessary DOM bindings to use exceptions. More specifically, it passes an ErrorResult& as the last argument to our method. We can use this object to throw exceptions.

    Let’s take a look at TextTrack::RemoveCue and how we can throw an exception if the cue passed as an argument is not already in the internal TextTrackList.

    In our header file:

    void RemoveCue(TextTrackCue& aCue,
                   ErrorResult& aRv);

    In the implementation file:

    TextTrack::RemoveCue(TextTrackCue& aCue,
                         ErrorResult& aRv)
    {
      // If the given cue is not currently listed in the
      // method's TextTrack object's text track's text
      // track list of cues, then throw a NotFoundError
      // exception and abort these steps.
      if( DoesContainCue(aCue) == false ) {
        aRv.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
        return;
      }
      // Remove cue from the method's TextTrack object's text track's text track
      // list of cues.
      mCueList->RemoveCue(aCue);
    }

    The generated bindings make it very easy to throw an exception. Now that an ErrorResult& is being passed to our method, we simply call Throw on the object and pass the error. One could search on MXR for the particular error macro/constant they need; luckily, bz told me which to use in #content.

    Initially, I was a bit confused when trying to implement exceptions. While looking through MXR to see examples of how other classes implemented exceptions, I’d often see ErrorResult initialized as a local variable within a method. Apparently, this is only used for methods that catch exceptions. Methods that throw exceptions do it through an ErrorResult& argument passed in by the generated binding methods. Oh, you Mozilla engineers. You guys/gals are magic.

    That particular pull request is still open at the time of writing. You can check out that pull request here.

    “1.0”

    I’m really not sure if this release can be considered a 1.0 release. The code still hasn’t landed in Firefox (although it seems close). There are still things to do! Some of those things include: maintaining and using TextTracks.activeCueList, finish implementing exceptions on the rest of the TextTrack* classes, and fix all of the issues raised in the reviews done by bz and Ms2ger. Concurrently, I believe we are at the point where we can start using the MochiTests written by Marcuus and Jordan to bring other issues to light.

    A big issue is the ever-shifting nature of the WebVTT spec. It seems like every week, the spec changes - and not always for the better. For instance, there are now a list of rules associated with every TextTrack that defines how the text tracks should be rendered. Also, TextTrackCue is an abstract class from which we should be creating a new object: WebVTTCue. Not all these changes make sense to me (Rules for updating cues? Why?) but I guess that is a part of the age-old rift between spec writers and implementers.

    Between the spec being in flux and the other items still on my to do list, there is still quite a bit to be done before I’d be comfortable slapping the ol’ 1.0 tag on. Now that school is officially complete forever, I should have much more time to spend on WebVTT.

    The Middle

    Speaking of school being officially done forever, this is my last official ‘for school’ post on my blog. This isn’t the end though, not by a longshot. I’ll be continuing my work on WebVTT as a volunteer. I’m excited to see what happens with the project in the coming few months!

    Thanks to Humph for teaching the OSD classes to begin with. If you are a student at Seneca in CPA or BSD, do yourself a favour and take these classes. The OSD classes are the best professional options offered at Seneca, in my opinion. I’d also like to thank my OSD teammates for a crazy 8 months. We’re still alive! Success!


              How to change IE7 default 'View Page Source' text viewer in Windows XP/Vista        

    I really love Notepad</grin>, I think it does a wonderful job with the really simple things, like a quick and dirty way of opening text files, web.configs (if you are in a rush only of course).

    Now, if you are a web developer and say you want to see the source code of any given page or you might get a JavaScript error in line 1209 and want to have a look at it..then honestly NotePad does not cut it really.

    I use Notepad++ at work http://notepad-plus.sourceforge.net/uk/site.htm and so far I'm a very happy chap.

     

    So how do you change to say..Vi in Windows XP

    1. Download TweakUI from http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
    2. Start Tweak UI and update your view source editor under Internet Explorer | View Source, and then point it to the exe of your editor of choice.

     

    But mate, what about Vista?

    oh yeah!, TweakUI does not work in Vista so I read this IE7 blog entry in the msdn blogs

     

     http://blogs.msdn.com/ie/archive/2007/03/28/ie7-in-vista-configuring-your-view-source-editor.aspx

     

    You can also download this mini-app to do it for you ( preferred choice, since I could not find the HKey described above on my Vista sys)

     

    http://www.iconico.com/viewSourceEditor/  ( skip the registration!)

     

    Worked very well.

     

    Capture


              WCF Services - Part 2        

    In the last post I tried to show how to use HTTP GET to get data back from my Services. Now I want to put my thoughts in order and show how I created new Employees and updated them using programmatic POST using the ubiquitous Northwind database.

    My first attempts where at trying to update a record using values embedded in the querystring... easier said than done, it was quite an effort.. At then end it worked, it just required a shift in the way I was tackling the problem. I ended up having my contract accept a Stream parameter and then had to read the stream and get the values back.

     

    My contract was:

    //STREAM EXAMPLE
    [OperationContract]
    [WebInvoke(UriTemplate = "*", Method = "POST")]
    void UpdateEmployeeName(Stream id);

    My uri template was "*" since I wanted to have the querystring collection of values straight after the 'root' of my Service.svc

    My implementation was very simple...

    public void UpdateEmployeeName(Stream id)
     {
         StreamReader reader = new StreamReader(id);
         String res = reader.ReadToEnd();
         NameValueCollection coll = HttpUtility.ParseQueryString(res);
         
         int employeeID = Int32.Parse(coll["elid"]);
         String newName = coll["newName"];
    
         // Bless LinqToSql
         NorthwindDataContext cts = new NorthwindDataContext(ConnectionManager.GetHomeLocalConnectionString);
         Employee e = cts.Employees.Where(a => a.EmployeeID == employeeID ).Single();
         e.FirstName = newName;
         cts.SubmitChanges();
     }

    Now, how the heck do I make a programmatic POST to my contract?

    I just created a WebRequest and set the content type to form-urlencoded and set the request length to the length of my queryString collection.

    //set the data
    ASCIIEncoding enc = new ASCIIEncoding();
    string datatext = "elid=" + elEmployeeID.Text;
    datatext += "&newName=" + elEmployeeNewName.Text;
    
    byte[] data = enc.GetBytes(datatext);
    
    //HTTP POST query
    WebRequest request = HttpWebRequest.Create("http://localhost/DemoWCF/Service.svc");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    
    Stream datasteam = request.GetRequestStream();
    datasteam.Write(data, 0, data.Length);
    datasteam.Close();
    WebResponse response = request.GetResponse();
     

    To test it I threw a few textfields together and magic....

    part2_1

     

    And checking the db....

     

    part2_2

     

    I also wanted to create a new Employee using Javascript using a programmatic post as above but this time using Javascript Object Notation (JSON ) http://www.json.org/

     

    My contract..

    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "/CreateEmployee")]
    void CreateEmployee(string FirstName, string LastName);
    Implementation:
    public void CreateEmployee(string FirstName, string LastName)
    {
          NorthwindDataContext cts = new NorthwindDataContext();
          Employee e = new Employee();      
          e.LastName = LastName;
          e.FirstName = FirstName;
          cts.Employees.InsertOnSubmit(e);
          cts.SubmitChanges();           
    }

     

    To generate an HTTP POST call with JavaScript, I created a XMLHTTPRequest and then I just constructed the url, set the header content type to json and was careful to format my JSON pair's payload..

    <asp:Button  ID="btnJSONCreateEmployee" runat="server" OnClientClick="doEmployeeCreate()"
    function doEmployeeCreate()
    {            
           var newFirstName = document.getElementById('TextBox1').value;            
           var newLastName = document.getElementById('TextBox2').value;
                
           var xmlHttp = new XMLHttpRequest();            
              
           // Create result handler 
           xmlHttp.onreadystatechange=function()
           {
              if(xmlHttp.readyState == 4)
              {
                 document.getElementById("result").value = xmlHttp.responseText;
               }
           }
                
           var url = "Service.svc/CreateEmployee";
           var body = '{"FirstName": '+ '"' + newFirstName + '"';
           body += ', "LastName": ' + '"'+newLastName + '"' + '}';
                
           //Send the Http Request
           xmlHttp.open("POST", url, true);
           xmlHttp.setRequestHeader("Content-type", "application/json");
           xmlHttp.send(body); 
    }

     

    To create a JSON payload in C# is very simple, just format a string carefully, escaping the " and you'll be fine..

    protected void btnCallService_Clicked(object sender, EventArgs args)
    {
       ASCIIEncoding enc = new ASCIIEncoding();
       string employeeID = txtJsonEmpID.Text;
       string firstName = txtJsonFirstName.Text;
       string lastName = txtJsonLastName.Text;           
       string datatext = "{\"EmployeeID\":{0}, \"FirstName\":\"{1}\"  , \"LastName\":\"{2}\" }";
            
       datatext = datatext.Replace("{0}", employeeID)
                          .Replace("{1}",firstName)
                          .Replace("{2}", lastName);
                   
       byte[] data = enc.GetBytes(datatext);
    
       WebRequest request = HttpWebRequest.Create("http://localhost/DemoWCF/Service.svc/CallJason");
       request.Method = "POST";
       request.ContentType = "application/json";
       request.ContentLength = data.Length;
       
       Stream datasteam = request.GetRequestStream();
       datasteam.Write(data, 0, data.Length);
       datasteam.Close();
       WebResponse response = request.GetResponse();
    }

     

    Ok, now unfortunately one of the new Employees didn't leave good comments in SVN and el# got a bit upset when he had a look at the logs. So let's fire the guy, tough choice yes, but then also we need to demo a programmatic HTTP DELETE.

    part2_3 

    Simple contract...I just specify the request format, the response format and the method that my client will be using..

     
    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/FireEmployee",
        Method="DELETE" )]
    void FireEmployee(int EmployeeID);

    Implementation is dead simple...this has got nothing to do with WCF, but I just post it here for completeness.

    public void FireEmployee(int EmployeeID)
    {
        NorthwindDataContext ctx = new NorthwindDataContext();
        Employee emp = ctx.Employees.Where(e => e.EmployeeID == EmployeeID).Single();
        ctx.Employees.DeleteOnSubmit(emp);
        ctx.SubmitChanges();  
    }  

    Calling using JavaScript is v. simple too..

    function fireTheGuy()
    {
        var employeeID  =  document.getElementById('txtToDeleteEmployeeID').value;
        var xmlHttp = new XMLHttpRequest();            
              
        // Create result handler 
        xmlHttp.onreadystatechange=function()
        {
            if(xmlHttp.readyState == 4)
            {
              document.getElementById("result").value = xmlHttp.responseText;
            }
        }
                
        // void CreateEmployee(string FirstName, string LastName);
        var url = "Service.svc/FireEmployee";
        var body = ' { "EmployeeID": ' +  employeeID + ' }';
                
        //Send the Http Request
        xmlHttp.open("DELETE", url, true);
        xmlHttp.setRequestHeader("Content-type", "application/json");
        xmlHttp.send(body);       
    }
     

    And trust me, it works like a charm.

    Next post I would like to return complex types back to the client, as in Employee's objects etc..

     

              Playing around with Silverlight 2.0 Beta 1        

    Since Silverlight Beta was released a few days, I wanted to have a look around and see what can you do with it.

    After I did all the admins stuff like downloaded the beta, installed etc I started following ScottGu's tutorials on his blog to get an idea.

    I thought, hell what I'm going to do! I've got no idea and certainly no skills as a designer, so I thought ok, lets simulate the AjaxAutoComplete extender and see where it takes us.

    First of all I created a Silverlight application...

    image

    Then Visual Studio told me that in order to run a SL app, I need to host in a web page.

    image

    In project type above you can either choose, WebSite or WebAppliucation type..hrmm.

    Upon clicking ok you are presented with an empty xaml page called Page.xaml

    Now, the Silverlight control, because that is what we are creating, "lives" inside an html/aspx page. Note that the ctrl Source property is pointing to SuperApp.xap...

    image

    What the heck is this .xap file? I hear you ask..

    Nothing too exciting, it is the compiled Silverlight application in zip format. This file contains the dlls it needs to run like System.Windows.Controls.dll and System.Windows.Controls.Extended.dll and the dll of your app in our case SuperApp.dll.

    Dealing with the Xaml..

    First of all I need to build the GUI for the TextBox and ultimately my dodgy AutoCompleteExtender.

    What do we need?

    • Need a TexBox
    • Need some sort of DropDownList that is displayed as the user types in..
    • Need a button to submit the selected name eventually.

     

    I choose <Canvas> as my layout, there is Grid and StackPanel. I used Grid too and it looked very easy to use, it was like creating an html table and then referencing to the x,y cells..very cool.

    This is the Xaml for my text box. Note the Canvas.Top and Canvas.Left, no prize for guessing that it references the parent container of my textbox and it tells it to position it 100 pixels from the left and 20 from the top

    <TextBox x:Name="TextBox_EmployeeName" Canvas.Left="100" Canvas.Top="20" Width="200" BorderBrush="CornflowerBlue" BorderThickness="1" Height="30" />

    The button is very simple:

    <Button Click="Save_Click" Content="Save" Canvas.Left="310" Canvas.Top="20" x:Name="Save"Width="60" >

    I also added an event listener for the Click event.

    Now for the ComboBox-look a like. There is no ComboBox in Silverlight Beta, so the closest thing is a ListBox.

    Lets aligned right under the bottom of the TextBox and see what happens. At this stage of the game I was very hopeful that this will be able to be done.

    <ListBox  KeyDown="EmployeeNames_KeyDown"  
            MouseLeftButtonDown="EmployeeNames_MouseLeftButtonDown"  
            Visibility="Collapsed" x:Name="EmployeeNames" 
            Width="200" Canvas.Left="100" Canvas.Top="46" />

    Ok, so far so good, note I added two events to my ListBox, KeyDown and MouseLeftButtonDown. Basically these two events will 'listen' for when the user presses a key while this control has focus and also while the Mouse left button is pressed also while focus is on. ( I was thinking hrmm, this reminds me of SWING development back at uni in Java..)

    Resulting page is: ( beautiful )

    basic_Silver_Gui

    Next question I had was. Ok I have to get some data from my Northwind database. I want text to resolve back to an EmployeeName. How am I going to do this? WebServices with WCF..

    Note: This WebService has to be configured as BasicHttpBinding.

    You cannot add a WebService to the Silverlight application, you have to do it somewhere else. In this case I added it you my WebSite. AddNewItem --> WCF Service.

    I defined my [ServiceContract] Interface and my OperationContracts

    and then my DataContract, because I wanted to return a MyEmployee object from my WCF webService.

    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        int CountEmployees();
    
        [OperationContract]
        MyEmployee GetEmployee(int id);
    
        [OperationContract]
        List<MyEmployee> GetAllEmployees();
    
        [OperationContract]
        String[] GetAjaxyEmployeeNames(String prefixText);
    }
    
    [DataContract]
    public class MyEmployee
    {   
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public int GetEmployeeID { get; set;}
    
        [DataMember]
        public String Address { get; set; }
    
        [DataMember]
        public String Title { get; set; }  
    }

    Then I had my MyService class that implemented my IService interface.

    The function of interest is the GetAjaxyEmployeeNames, since it returns a String[] with the names that start with the prefixText passed on. Also note that you cannot add LinqToSql to Silverlight 2.0 Beta app, it is not supported at this stage, it does support LinqToXml though and one of ScottGu's tuts shows this. Since I added the Service to the WebSite, I just added a dbml file and drag-and-dropped the Employee table. Piece of cake.

    public string[] GetAjaxyEmployeeNames(String prefixText)
    {
           NorthwindDataContext ctx = new NorthwindDataContext();
           var emps = from e in ctx.Employees
                      where e.LastName.StartsWith(prefixText)
                      orderby e.LastName descending
                      select e.LastName + ", " + e.FirstName;
           return emps.ToArray<String>();        
    }

    Now we have the webService sorted out. We need to add a reference to our Silverlight app about this. The way to do it is very easy. Just right click on the project file Add Service Reference and you will be shown the dialog below..then discover and hopefully it will find the web service we just created.

    image

    Back to the Xaml now.

    We have to add an Even listener to our TextBox, so when the text changes in the txtBox, the webservice will be called. This is easy, we just add a TextChanged event handler.

    <TextBox TextChanged="TextBox_TextChanged"
            Canvas.Left="100" Canvas.Top="20" Width="200" Text=""
            x:Name="TextBox_EmployeeName"
            BorderBrush="CornflowerBlue" BorderThickness="1"
            Height="30">

    I love the way VS does this for xaml pages, as soon as you type KeyDown the intellisense will ask you if you want to create a new listener, and if you press enter, VS will create a function in the codefile with some real cool naming by default.. wish we had this for normal asp.net! ( ScottGu said this is coming soon!)

    I also added a KeyDown handler, so when the textbox has focus and the user presses the down arrow key, the behaviour of the real AutoCompleteExtender is simulated and the focus and control moves on to the ListBox.

    event_intellegince

    We have the handlers now, next we have to create a proxy to our WebService so they methods it exposes can be called. 

    1. Add two using statements to System.ServiceModel and System.ServiceModel.Channels.
    2. Create a binding element in the scope of the class ( so we can use it everywhere!). Binding binding = new BasicHttpBinding(); Bindings specify the details for a client to communicate with the Service. The only binding supported at this stage is BasicHttpBinding.
    3. Next we have to create an EndPointAddress. This gives the address of the Service to be called upon. So we just use the address where this service is being hosted.
    4. EndpointAddress address = new EndpointAddress("http://localhost:50740/SilverlightApplicationFirstEver_Web/Services/MyService.svc")
       

    We now have everything we need to create our proxy and call the Service. Remember we have a listener for when the user enters text in our TextBox and so the TextChanged event fires.

    To create the proxy to our service, the proxy's constructor takes in the binding and endpointAddress.

    To now call the methods in our service we have to realise that all calls in Silverlight are asynchronous. In this case I'm using the event driven pattern where the proxy contains two members for each potential call to the Service, these are an async method and a completed event that is raised once the async call returns. This results on the following members:

    resultingmethods 

    The complete function looks like this:

    completed_function

    And the proxy_AjaxyEmployeeCompleted function that handles the returned data from the WebService is:

    proxy_completed_call 

    Note that the ListBox is hidden unless there is a result to display.

    Now as soon as you type something in, the service will be displayed and the ListBox ItemsSource property ( think of it as a DataSource in Asp.net ) is bound to args.Result, which is a String[]

    extenderinaction 
     

    Thats basically it, I have more functions to simulate the real AutoCompleteExtender, like for example when the user clicks with the mouse on say "King, Robert" that Employee name will be selected and will be copied into the TextBox.

    Also I have a listener on the ListBox that listens for any down arrow key pressed and mouse left button events that copy the SelectedItem text to the TextBox again.

    mousedown

    And to finish up, when the TextBox has focus and the user presses the down arrow key, this means that she will like to go on an navigate through the employee names in the ListBox. To to this we added a KeyDown listener on the TextBox.

    keydowned_textarea 
     

    Out of interest I then opened the solution file in Expression Blend 2.5 March edition and got to play with colours etc etc. Very cool but well outside my domain all this designer stuff..

    image 

    Well, is all good, I learned heaps about Xaml etc. VEry powerful, but also learned that things can get very complicated very quickly. There are some sample apps that come with Blend that are plain scary.

    image 

    A photo book where you can "grab" the pages from the lower right corner..

    image 

    impressive this paint look-alike..