<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jacques L. Chereau on Medium]]></title>
        <description><![CDATA[Stories by Jacques L. Chereau on Medium]]></description>
        <link>https://medium.com/@jlchereau?source=rss-b97fb54a8cda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ERTp1TpXN4ZvOsW1Q25OvA.png</url>
            <title>Stories by Jacques L. Chereau on Medium</title>
            <link>https://medium.com/@jlchereau?source=rss-b97fb54a8cda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:19:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jlchereau/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Is NVDA in the AI trough of disillusionment?]]></title>
            <link>https://medium.com/@jlchereau/is-nvda-in-the-ai-trough-of-disillusionment-096b6089b93d?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/096b6089b93d</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[amd]]></category>
            <category><![CDATA[nvda]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 12:42:49 GMT</pubDate>
            <atom:updated>2024-09-16T12:34:20.286Z</atom:updated>
            <content:encoded><![CDATA[<p>The tech stock rout of August 2024 has raised the question “<a href="https://www.bloomberg.com/news/newsletters/2024-08-05/ai-rally-halts-abruptly-as-global-selloff-sinks-tech"><em>is there an AI bubble about to burst?</em></a><em>”. </em>Some analysts have claimed that AI (or GenAI) was entering the <em>“</em><a href="https://www.youtube.com/watch?v=qXKYOR3KqxQ"><em>trough of disillusionment</em></a><em>”.</em> As a consequence some believe the NVDA stock has peaked. This is not my opinion.</p><h3>Which trough of disillusionment?</h3><p>AI and more specifically deep learning is based on neural network designs which have emerged with the <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent">stochastic gradient descent algorithm invented by Herbert Robbins and Sutton Monro in 1951</a> and <a href="https://en.wikipedia.org/wiki/Multilayer_perceptron">the multi-layer perceptron invented by Frank Rosenblatt in 1958</a>. 70 years later, AI is certainly not in the trough of disillusionment.</p><p>In 1999 NVidia released <a href="https://en.wikipedia.org/wiki/GeForce_256">GeForce 256</a>, their first product marketed as a GPU, and in 2007 they released CUDA (Compute Unified Device Architecture), a proprietary programming interface for accelerated general-purpose processing on GPUs. CUDA allows deep learning frameworks like <a href="https://www.tensorflow.org/">TensorFlow</a>, <a href="https://pytorch.org/">PyTorch</a> and <a href="https://jax.readthedocs.io/en/latest/index.html">JAX</a> to process massively parallel computations on <a href="https://www.nvidia.com/en-us/data-center/dgx-platform/">large GPU systems</a>. Massively parallel computations are here to stay and one can expect demand to outpace offer for quite some time considering <a href="https://www.statista.com/statistics/871513/worldwide-data-created/">global data growth</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8rI9ZaIbbnFMNR0Y" /></figure><p>In November 2022, OpenAI released ChatGPT which suddenly became the <a href="https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/">fastest growing app in the history of web applications</a>, adding two new terms in everyone’s vocabulary: GenAI (Generative AI) and LLM (Large Language Model). <a href="https://openai.com/index/openai-pytorch/">Open AI standardize on PyTorch</a> to design their Generative Pre-trained Transformer (GPT) models following a network architecture unveiled in a <a href="https://arxiv.org/abs/1706.03762">research paper entitled “Attention is all you need’ published by Google in 2017</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NenUclBU9RBqHnFk.png" /></figure><p><a href="https://www.digillia.com//blog/cas-usage-llms/">Large Language Models have 4 main use cases</a> and their combinations: (1) text generation, (2) text analysis and question answering, (3) text summarization, and (4) translation, which they achieve with caveats including hallucinations.</p><p>LLM hype has certainly produced a <a href="https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard">plethoric offer</a> whereas <a href="https://paperswithcode.com/dataset/mmlu">4 winners are clearly emerging</a>: <a href="https://www.anthropic.com/">Anthropic’s Claude</a>, <a href="https://deepmind.google/technologies/gemini/">Google’s Gemini</a>, <a href="https://llama.meta.com/">Meta’s Llama</a> and <a href="https://openai.com/">OpenAI’s GPT</a>. From now on progresses are incremental and <a href="https://venturebeat.com/ai/ai-pioneer-lecun-to-next-gen-ai-builders-dont-focus-on-llms/">resources (talents, GPUs) are wasted competing in the field</a>. As a result, <a href="https://www.goldmansachs.com/images/migrated/insights/pages/gs-research/gen-ai--too-much-spend%2C-too-little-benefit-/TOM_AI%202.0_ForRedaction.pdf">analysts including Goldman Sachs, question the levels of CAPEX and the expected returns</a>.</p><p>In my opinion, LLMs are at risk of being overthrown as long as they rely on an expensive brute force approach in which improvements are directly linked to increasing the billions of parameters they rely on considering the <a href="https://arxiv.org/abs/2209.04881">unsustainable quadratic complexity of transformers</a>. <a href="https://www.ft.com/content/23fab126-f1d3-4add-a457-207a25730ad9">LLMs are simply not clever enough</a> and better solutions will emerge.</p><p><strong>LLMs have clearly entered the trough of disillusionment</strong>. But they have given us a glimpse at what GenAI, and ultimately AGI (<a href="https://www.mckinsey.com/featured-insights/mckinsey-explainers/what-is-artificial-general-intelligence-agi">Artificial General intelligence</a>) could be. This is only the beginning…</p><h3>What about NVDA?</h3><p>NVidia owns more than 80% of the GPU market and they struggle to meet demand. The other 20% are mainly shared between AMD and Intel. This is an enviable position in a concentrated market. As discussed above, the market of massively parallel computations will continue to grow unaffected by any possible disappointment in LLMs.</p><p>On the hardware side, <a href="https://cloud.google.com/blog/products/compute/introducing-trillium-6th-gen-tpus">Google develop their own AI chips, ie. TPUs</a>, and companies like <a href="https://machinelearning.apple.com/research/neural-engine-transformers">Apple</a> and <a href="https://www.qualcomm.com/products/technology/artificial-intelligence">Qualcomm</a> develop neural engines. <a href="https://www.chipstrat.com/p/nvidias-risk">Breakthrough innovations can be expected in the semiconductor industry in relation to AI</a> but developing chips is a large investment and such progresses do not happen overnight.</p><p>On the software side, NVidia benefits from a vibrant ecosystem integrated with the CUDA platform which is no match for AMD or Intel, but which is now threatened by <a href="https://www.bloomberg.com/news/articles/2024-09-03/nvidia-gets-doj-subpoena-in-escalating-antitrust-investigation">anti-trust regulators</a> and innovations like <a href="https://openai.com/index/triton/">Open AI Triton</a>. It will also take time for the ecosystem, including TensorFlow, PyTorch and Jax, to migrate their code to new APIs and hardware.</p><p>On the mid-to-long term (2 years or more), NVidia is exposed to significant threats, but it is my opinion that NVidia will maintain their leadership and double-digit growth rates on the short term.</p><p>Please consider sharing your opinion in comments.</p><blockquote>Disclaimer: I own the NVDA stock.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=096b6089b93d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do we need LangChain, LlamaIndex and Haystack, and are AI Agents dead?]]></title>
            <link>https://medium.com/@jlchereau/do-we-still-need-langchain-llamaindex-and-haystack-and-are-ai-agents-dead-522c77bed94e?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/522c77bed94e</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[haystack]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 17:44:30 GMT</pubDate>
            <atom:updated>2024-09-14T10:10:37.912Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>LangChain, LLamaIndex and Haystack are python frameworks for LLM development, especially Retrieval Augmented Generation (RAG) applications.</blockquote><h3>RAG Applications</h3><p>Generic Large Language Model (LLM) do not know about your business and cannot answer questions about your your organization’s proprietary knowledge, including your customer relationships.</p><p>To alleviate this limitation, Retrieval Augmented Generation (RAG) applications consist in searching a corpus of documents, and formulating the answer in plain text using the documents that match the search query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPNlQphvu2h369MTxr3oaw.png" /></figure><p>Typically a basic RAG application involves two steps:</p><ol><li>A query that is submitted to a vector database to retrieve relevant chunks of documents using their embeddings (a vector representation of text);</li><li>A call to a Large Language Model (LLM) to formulate an answer using the query and the chunks found.</li></ol><p>More advanced RAG applications might involve other steps to reformulate the query, rerank searched documents, manage history (memory), prevent hallucinations, mitigate prompt hacking and toxicity, or else.</p><h3>LangChain, LLamaIndex and HayStack</h3><p>RAG applications are often designed as a pipeline of steps, where each step output consists in the input of the following step. The first input is the query and the last output is the answer.</p><p><a href="https://www.langchain.com/">LangChain</a>, <a href="https://www.llamaindex.ai/">LLamaIndex</a> and <a href="https://haystack.deepset.ai/">HayStack</a> have followed very similar paths providing:</p><ul><li>an open source design for steps and a mechanism to connect steps in direct acyclic graphs (DAG),</li><li>integration with various services including vector databases and large language models (common steps supplied as configurable blocks),</li><li>paid cloud services for hosting, evaluating and monitoring.</li></ul><p>In my opinion, LangChain has more integrations and LLamaIndex and HayStack have a more intuitive design. You can find many blog articles comparing them.</p><h3>AI Agents and CrewAI</h3><p>As use cases have become more complex and requirements have become more stringent, prompt engineering has evolved to improve answers and include:</p><ul><li>a <a href="https://platform.openai.com/docs/guides/prompt-engineering/tactic-ask-the-model-to-adopt-a-persona">persona</a>, e.g. “<em>You are a marketing copywriter at a large pharmaceutical company</em>”,</li><li>a goal, e.g. “<em>You are tasked with drafting a blog article for the company web site</em>”,</li><li><a href="https://platform.openai.com/docs/guides/prompt-engineering/strategy-use-external-tools">tools</a> to achieve the goal with accurate and up-to-date data, including code execution, and database and online search.</li></ul><p>A persona, a goal, tools, and possibly memory (for conversational agents) make an AI Agent. <a href="https://python.langchain.com/v0.1/docs/modules/agents/">LangChain</a>, <a href="https://docs.llamaindex.ai/en/stable/use_cases/agents/">LlamaIndex</a>, and <a href="https://docs.haystack.deepset.ai/v1.25/docs/agent">HayStack</a> have all enhanced their offerings with agentic frameworks. Consider also <a href="https://microsoft.github.io/autogen/">AutoGen</a>. <a href="https://platform.openai.com/docs/assistants/overview">Open AI calls these agents “assistants”</a>.</p><p>3 key patterns have emerged:</p><ul><li><a href="https://www.deeplearning.ai/the-batch/issue-244/"><strong>Planning</strong></a>: An agent comes up with a plan to achieve its goal (for example, a planning agent writing an outline for a blog article).</li><li><a href="https://www.deeplearning.ai/the-batch/issue-242/"><strong>Reflection</strong></a>: An agent criticizes an outcome to come up with ways to improve it (for example, an editor agent reviewing a draft article).</li><li><a href="https://www.deeplearning.ai/the-batch/issue-245/"><strong>Multi-agent collaboration</strong></a>: More than one AI agent work together, to come up with better solutions than a single agent would (for example, an agent doing research, an agent writing a draft, an agent reviewing the draft with suggestions to improve it, and an agent optimizing for search engines).</li></ul><p><a href="https://www.crewai.com/">crewAI</a> even let the LLM orchestrate the work between AI agents (an approach I do not recommend for being too unpredictable and hard to debug and improve).</p><h3>Workflows, Graphs, and PromptFlow</h3><p>Large Language Models have demonstrated working better with clear and simple goals and instructions. Therefore, complex use cases are better implemented has a succession of small steps. Pipelines and direct acyclic graphs have limiting capabilities including a lack of loops for iterating and improving.</p><p>In fact most complex use cases are better implemented as workflows or complex graphs allowing loops. LangChain has recently released <a href="https://www.langchain.com/langgraph">LangGraph</a>, and LLamaIndex their <a href="https://docs.llamaindex.ai/en/stable/module_guides/workflow/">workflows</a>. Interestingly, the makers of <a href="https://www.prefect.io/">Prefect</a> have also released their agentic workflow framework, <a href="https://controlflow.ai/">ControlFlow</a>, and Microsoft has been promoting <a href="https://microsoft.github.io/promptflow/">PromptFlow</a>.</p><p>Workflows are in my opinion the better approach allowing maximum flexibility and easiest debugging and improving. <a href="https://blog.langchain.dev/what-is-an-agent/">Note that some vendors now call these agentic workflows, “<em>agents</em>”</a>.</p><p>A one-node graph printing “Hello, John!” can be implemented as follows with LangGraph:</p><pre># %pip install langgraph==0.2.19<br><br>from langgraph.graph import StateGraph<br><br>graph = StateGraph(str)<br><br>def hello(state: str) -&gt; str:<br>    text = f&quot;Hello, {state}!&quot;<br>    return text<br><br>graph.add_node(&quot;hello&quot;, hello)<br>graph.set_entry_point(&quot;hello&quot;)<br>graph.set_finish_point(&quot;hello&quot;)<br>compiled = graph.compile()<br>result = compiled.invoke(&quot;John&quot;)<br>print(result)<br><br># prints Hello, John!</pre><p>A one-step workflow printing “Hello, John!” can be implemented as follows with LlamaIndex workflows:</p><pre># %pip install llama-index==0.11.8<br><br>from llama_index.core.workflow import (<br>    StartEvent,<br>    StopEvent,<br>    Workflow,<br>    step,<br>)<br><br>class Hello(Workflow):<br>    @step<br>    async def print(self, ev: StartEvent) -&gt; StopEvent:<br>        return StopEvent(result=f&quot;Hello, {ev.text}!&quot;)<br><br><br>hello = Hello(timeout=10, verbose=False)<br>result = await hello.run(text=&quot;John&quot;)<br>print(result)<br><br># prints Hello, John!</pre><p>Interestingly these graphs/workflows are independent from LLMs and agents, and how LangChain or LLamaIndex integrate with them. They can easily be replaced with alternatives.</p><h3><strong>OpenAI API, Pydantic and Jinja2</strong></h3><p>I find that the <a href="https://platform.openai.com/docs/overview">Open AI API</a> provides everything you need to interact with most LLMs with tool function calling, especially with <a href="https://jinja.palletsprojects.com/">Jinja2</a> to format and store prompt templates and <a href="https://docs.pydantic.dev/latest/">Pydantic</a> to format outputs as JSON.</p><h3>Conclusion</h3><p>In my opinion, modern LLM applications should be implemented as workflows with the Open AI API (or <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/call-vertex-using-openai-library">equivalent from Google</a>). We do not need a wrapping layer.</p><p>Semantic search can be implemented with the relevant database driver for Python (<a href="https://faiss.ai/">FAISS</a>, <a href="https://www.trychroma.com/">chromaDB</a>, <a href="https://www.pinecone.io/">Pinecone</a>, <a href="https://qdrant.tech/">Qdrant</a>, <a href="https://www.mongodb.com/products/platform/atlas-vector-search">MongoDB Atlas</a> or else). Again, no need for a wrapper.</p><p>Observability and traceability during development can be obtained with <a href="https://mlflow.org/">MLFlow</a>, <a href="https://www.kubeflow.org/">KubeFlow</a> or equivalent, as a single platform for MLOps/MLDevOps.</p><p>I cannot foresee any need for LangChain, LlamaIndex or HayStack pipelines or agent frameworks, except maybe for rapid prototyping when it is convenient to try alternative architectural blocks. LangChain has raised doubts: “<a href="https://blog.langchain.dev/langgraph/"><em>However, so far we’ve lacked a method for easily introducing cycles into these chains</em></a>”. LlamaIndex too: “<a href="https://www.llamaindex.ai/blog/introducing-workflows-beta-a-new-way-to-create-complex-ai-applications-with-llamaindex"><em>A fundamental aspect of DAGs is the “A” in DAGs: they are acyclic, meaning there are no loops. But in a world that’s more and more agentic, the inability to perform loops in an AI application’s logic is simply unacceptable</em></a>”.</p><p>Do you agree? Have you reached a different conclusion? Please leave your opinion and share your experience in comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=522c77bed94e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a mini-MOOC?]]></title>
            <link>https://medium.com/@jlchereau/how-to-build-a-mini-mooc-2924be54f71?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/2924be54f71</guid>
            <category><![CDATA[quiz]]></category>
            <category><![CDATA[mooc]]></category>
            <category><![CDATA[kidoju]]></category>
            <category><![CDATA[questions-answers]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Mon, 31 Jul 2017 14:57:59 GMT</pubDate>
            <atom:updated>2017-07-31T14:59:20.880Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>… or how to embed great quizzes and practice questions in your web pages.</blockquote><p>There is a lot of work involved in building a massive open online course. It is a complex process involving video editing among other skills. You might have something to teach, but you might not have the time or capacity to build a comprehensive MOOC or you might simply want to try things and gather feedback before involving the costs of professional video editing and marketing.</p><p>Here comes the concept of mini-MOOC, which embeds on the same web page a YouTube Video, practice questions and comments to gather feedback. Although video embeds and comments are well-known features of any blog platform, including the mighty Medium this post is published on, how do you add exercises to a web page?</p><p>Kidoju at <a href="https://www.kidoju.com/">https://www.kidoju.com</a> is a platform (currently beta) to design and share smart quizzes. Kidoju quizzes offer more activities than basic multiple choice questions. Kidoju also allows anyone to embed exercises on any web page with two technical options.</p><h3>Use an iframe if you have access to the html code</h3><p>Go to the details page of any Kidoju quiz, click the embed tab and copy the code that you will paste within your html page as shown here below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTJS9w20VOaDFeX1xAw6uA.gif" /><figcaption>Copy-paste the iframe code</figcaption></figure><p>In our example the code to paste is:</p><pre>&lt;iframe src=&quot;<a href="https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f?embed=true&amp;theme=material">https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f?embed=true&amp;theme=material</a>&quot; style=&quot;height:500px;width:100%;&quot;&gt;&lt;/iframe&gt;</pre><h3>Otherwise, rely on embed.ly</h3><p>Embed.ly is a service that publishes <a href="http://oembed.com/">oEmbed</a> endpoints so that web sites which subscribe to this service can display the corresponding content. It is like publishing jigsaw pieces that subscribing web sites can safely arrange on a web page. Kidoju has an oembed endpoint and <a href="http://embed.ly/code?url=https%3A%2F%2Fwww.kidoju.com%2Fen%2Fx%2F570cc7f46d1dd91900729417%2F57f7da59011ff80019ea6c6f">it is published on embed.ly</a>. Medium subscribes to embed.ly so that such endpoint can be used automatically by simply pasting a url as shown here below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*GEtXP4SSlPk7aD1JjM6KdA.gif" /></figure><p>In our exampe, the url to paste is:</p><pre><a href="https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f?embed=true&amp;theme=material">https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f</a>?<a href="https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f?embed=true&amp;theme=material">theme=material</a></pre><h3>And this is what you get</h3><p>As a result, the following is the <a href="https://www.kidoju.com/en/x/570cc7f46d1dd91900729417/57f7da59011ff80019ea6c6f">Kidoju demonstration including all possible activities</a>. Obviously the way these activities are arranged does not limit your creativity especially when such activities can be combined on the same slide/page.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.kidoju.com%2Fen%2Fx%2F570cc7f46d1dd91900729417%2F57f7da59011ff80019ea6c6f%3Fembed%3Dtrue&amp;url=https%3A%2F%2Fwww.kidoju.com%2Fen%2Fx%2F570cc7f46d1dd91900729417%2F57f7da59011ff80019ea6c6f&amp;image=https%3A%2F%2Fdata%3A%2F%2Fs%2Fen%2F570cc7f46d1dd91900729417%2Fdropzone1.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kidoju" width="480" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/115ef4cd18960fdfbce24b4aa40195f0/href">https://medium.com/media/115ef4cd18960fdfbce24b4aa40195f0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2924be54f71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An extended kendo.drawing.Path with simplification and smoothing for pen drawing]]></title>
            <link>https://medium.com/@jlchereau/an-extended-kendo-drawing-path-for-pen-drawing-7c40b5a83059?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c40b5a83059</guid>
            <category><![CDATA[drawing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[kendo-ui]]></category>
            <category><![CDATA[bezier]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Mon, 10 Apr 2017 12:51:06 GMT</pubDate>
            <atom:updated>2017-04-11T09:14:26.499Z</atom:updated>
            <content:encoded><![CDATA[<p>Despite other priorities, I am slowly progressing a vector drawing widget using the <a href="https://github.com/jlchereau/kendo-ui-core">Kendo UI framework</a>, to be included in <a href="https://www.kidoju.com/">Kidoju</a>. Kidoju exercises and quizzes are actually PowerPoint presentations with the capacity to ask questions, record user interactions and calculate a score. Currently users cannot draw in Kidoju. They have to import their drawings as images. This is due for a change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*f43sw6Kq5gKrgYr3jKoMIA.png" /><figcaption><a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/kidoju.widgets.vectordrawing.html">https://github.com/kidoju/Kidoju-Widgets/blob/master/src/kidoju.widgets.vectordrawing.html</a></figcaption></figure><p>One of the tools a vector drawing widget needs, is the <strong>pen tool</strong> as found in Adobe Illustrator.</p><p>Implementing a nasic pen tool with Kendo UI is achieved with the kendo.drawing.Path class/prototype has follows:</p><pre><strong>function </strong><em>getPointAtMousePos</em>(e) {<br>    <strong>return new </strong>Point(<br>        e.pageX - offset.<strong>left</strong>,<br>        e.pageY - offset.<strong>top<br>    </strong>);<br>};<br><strong>var </strong>drawing = <strong>kendo</strong>.<strong>drawing</strong>;<br><strong>var </strong>geometry = <strong>kendo</strong>.geometry;<br><strong>var </strong>Point = geometry.<strong>Point</strong>;<br><strong>var </strong>Path = drawing.Path;<br><strong>var </strong>surface = <strong>new </strong>drawing.<strong>Surface</strong>(<strong>&#39;#surface&#39;</strong>);<br><strong>var </strong>offset = <strong>$</strong>(<strong>&#39;#surface&#39;</strong>).offset();<br><strong>var </strong>path;<br><br><strong>$</strong>(<strong>document</strong>)<br>    .on(<strong>&#39;mousedown&#39;</strong>, <strong>&#39;#surface&#39;</strong>, <strong>function</strong>(e) {<br>        path = <strong>new </strong>Path({ <strong>stroke</strong>: { <strong>color</strong>: <strong>&#39;#FF0000&#39;</strong>, <strong>width</strong>: 5 }} );<br>        path.moveTo(<em>getPointAtMousePos</em>(e));<br>        surface.draw(path);<br>    })<br>    .on(<strong>&#39;mousemove&#39;</strong>, <strong>function</strong>(e) {<br>        <strong>if </strong>(path instanceof Path) {<br>            path.lineTo(<em>getPointAtMousePos</em>(e));<br>        }<br>    })<br>    .on(<strong>&#39;mouseup&#39;</strong>, <strong>function</strong>() {<br>        path = <strong><em>undefined</em></strong>;<br>    });</pre><p>This code can be executed at <a href="http://dojo.telerik.com/USIRi">http://dojo.telerik.com/USIRi</a>. Note that <strong><em>getPointAtMousePos</em> </strong>would require some improvements in order to handle touch events, which is beyond the scope of this article<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*3jt49WWeMWunYqH70p8yfA.png" /><figcaption><a href="http://dojo.telerik.com/USIRi">http://dojo.telerik.com/USIRi</a></figcaption></figure><p>This implementation raises two issues:</p><ol><li><strong><em>mousemove </em></strong>generates a lot of events, which means a lot of points to persist.</li><li>A simplified path (optimized storage) requires smoothing.</li></ol><h4>Storing a kendo.drawing.Path</h4><p><a href="http://docs.telerik.com/kendo-ui/api/javascript/drawing/path#parse">kendo.drawing.Path has a parse method</a> for parsing a path encoded in <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG Path Data format</a>, but there is no method to do the round trip for persistence.</p><p>In order to use the SVG Path Data format as a storage format for paths, we need to extend kendo.drawing.Path with a <strong>stringify</strong> method, as follows (assuming the same naming convention as JSON):</p><pre>stringify: <strong>function </strong>() {<br>    <strong>var </strong>PathNode = drawing.svg.<strong>PathNode</strong>;<br>    <strong>return </strong>PathNode.fn.printPath(<strong>this</strong>);<br>}</pre><h4>Simplifying a kendo.drawing.Path</h4><p>The most common algorithm to simplify a path expressed as a series of Points, is <a href="https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm"><em>Ramer-Douglas-Peucker</em></a><em>.</em></p><p>There is a great JavaScript implementation provided by <a href="https://github.com/mourner/simplify-js">https://github.com/mourner/simplify-js</a> and, based on their <strong><em>simplifyRadialDist</em> </strong>and <strong><em>simplifyDouglasPeucker </em></strong>methods, we can extend kendo.drawing.Path with the following method:</p><pre>simplify: <strong>function </strong>(tolerance, useDistances) {<br>    <strong>if </strong>(<strong>this</strong>.<strong>segments</strong>.<strong>length </strong>&lt;= 2) {<br>        <strong>return this</strong>;<br>    }<br>    <strong>var </strong>sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;<br><br>    <em>// Calculate simplified anchors using </em><a href="https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm"><em>Ramer-Douglas-Peucker</em></a><em><br>    </em><strong>var </strong>anchors = Array.<strong>prototype</strong>.map.<strong>call</strong>(<strong>this</strong>.<strong>segments</strong>, <strong>function </strong>(segment) { <strong>return </strong>segment.anchor().clone() });<br>    anchors = useDistances ? <em>simplifyRadialDist</em>(anchors, sqTolerance) : anchors;<br>    anchors = <em>simplifyDouglasPeucker</em>(anchors, sqTolerance);<br><em><br>    // Modify the path<br>    </em><strong>var </strong>segments = anchors.map(<strong>function </strong>(anchor) { <strong>return new </strong>drawing.<strong>Segment</strong>(anchor) });<br>    <em>// ElementsArray is not public to call<br>    // ElementsArray.prototype.splice.apply and pass an array<br>    </em><strong>this</strong>.<strong>segments</strong>._splice(0, <strong>this</strong>.<strong>segments</strong>.<strong>length</strong>, segments);<br>    <strong>this</strong>.<strong>segments</strong>._change();<br><br>    <em>// return the path, especially to chain with smooth</em>    <br>    <strong>return this</strong>;<em><br></em>},</pre><p>Our <strong><em>mouseup </em></strong>event handler can be changed to the following, where the higher the value of simplification tolerance, the less points you get in the end: 10 makes the impact of simplification very visible.</p><pre><strong>$</strong>(<strong>document</strong>)<br>    .on(<strong>&#39;mouseup&#39;</strong>, <strong>function</strong>() {<br>        path.simplify(10);<br>        path = <strong><em>undefined</em></strong>;<br>    });</pre><p>This code can be executed at <a href="http://dojo.telerik.com/iJiDAQ">http://dojo.telerik.com/iJiDAQ</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*WT_nXZmrLzKfZPs0vn6r6Q.png" /><figcaption><a href="http://dojo.telerik.com/iJiDAQ">http://dojo.telerik.com/iJiDAQ</a></figcaption></figure><h4>Smoothing a kendo.drawing.Path</h4><p>Now that we have reduced the number of points from hundreds to dozens, we have a broken line that needs smoothing.</p><p>Smoothing a path is achieved by calculating the control points of a bezier spline as explained at <a href="https://www.particleincell.com/2012/bezier-splines"><em>https://www.particleincell.com/2012/bezier-splines</em></a><em>/. </em>Based on their<em> </em><strong><em>computeControlPoints </em></strong>method, we can extend kendo.drawing.Path with the following method:</p><pre>smooth: <strong>function </strong>() {<br><br>    <strong>var </strong>i;<br>    <strong>var </strong>length = <strong>this</strong>.<strong>segments</strong>.<strong>length</strong>;<br>    <strong>var </strong>xes = [];<br>    <strong>var </strong>yes = [];<br><br>    <em>// Collect anchor coordinates<br>    </em><strong>for </strong>(i = 0; i &lt; length; i++) {<br>        <strong>var </strong>segment = <strong>this</strong>.<strong>segments</strong>[i];<br>        xes.push(segment.anchor().x);<br>        yes.push(segment.anchor().y);<br>    }<br><br>    <em>// Compute control points p1 and p2 for x and y directions<br>    </em><strong>var </strong>pxes = <em>computeControlPoints</em>(xes);<br>    <strong>var </strong>pyes = <em>computeControlPoints</em>(yes);<br><br>    <em>// Update path with control points<br>    </em><strong>for </strong>(i = 0; i &lt; length - 1; i++) {<br>        <strong>this</strong>.<strong>segments</strong>[i].<strong>controlOut</strong>(<strong>new </strong>geometry.<strong>Point</strong>(pxes.<strong>p1</strong>[i], pyes.<strong>p1</strong>[i]));<br>        <strong>this</strong>.<strong>segments</strong>[i + 1].<strong>controlIn</strong>(<strong>new </strong>geometry.<strong>Point</strong>(pxes.<strong>p2</strong>[i], pyes.<strong>p2</strong>[i]));<br>    }</pre><pre>    return this;<br>},</pre><p>Our <strong><em>mouseup </em></strong>event handler can be changed to:</p><pre><strong>$</strong>(<strong>document</strong>)<br>    .on(<strong>&#39;mouseup&#39;</strong>, <strong>function</strong>() {<br>        path.simplify(10).smooth();<br>        path = <strong><em>undefined</em></strong>;<br>    });</pre><p>This code can be executed at <a href="http://dojo.telerik.com/uVOGE">http://dojo.telerik.com/uVOGE</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*LO9V_K3uq0ZoBJYcZ3Oy5g.png" /><figcaption><a href="http://dojo.telerik.com/uVOGE">http://dojo.telerik.com/uVOGE</a></figcaption></figure><h4><strong>A new kendo.drawing.PathEx prototype, implementing stringify, simplify and smooth</strong></h4><p>Until Telerik implements stringify, simplify and smooth in kendo.drawing.Path, you can use the following kendo.drawing.PathEx prototype as explained in the examples here above. Do not hesitate to contribute improvements via pull requests at <a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kendo.drawing.pathex.js">https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kendo.drawing.pathex.js</a>. This is free to use as you may see fit.</p><pre><em>/**<br> * Copyright (c) 2013-2017 Memba Sarl. All rights reserved.<br> * Sources at https://github.com/Memba<br> * Portions Copyright (c) 2015, Vladimir Agafonkin<br> */<br><br>/* jshint browser: true, jquery: true */<br>/* globals define: false */<br><br></em>(<strong>function </strong>(f, define) {<br>    <strong>&#39;use strict&#39;</strong>;<br>    define([<br>        <strong>&#39;./vendor/kendo/kendo.core&#39;</strong>,<br>        <strong>&#39;./vendor/kendo/kendo.drawing&#39;<br>    </strong>], f);<br>})(<strong>function </strong>() {<br><br>    <strong>&#39;use strict&#39;</strong>;<br><br>    (<strong>function </strong>($, undefined) {<br><br>        <strong>var </strong>kendo = <strong>window</strong>.<strong>kendo</strong>;<br>        <strong>var </strong>drawing = kendo.<strong>drawing</strong>;<br>        <strong>var </strong>geometry = kendo.geometry;<br><br>        <em>/**************************************************************************************************************<br>         * Algorithm to simplify a path<br>         * https://github.com/mourner/simplify-js<br>         * https://karthaus.nl/rdp/js/rdp2.js<br>         **************************************************************************************************************/<br><br>        /**<br>         * Square distance between 2 points<br>         * </em><strong><em>@param </em></strong><em>p1<br>         * </em><strong><em>@param </em></strong><em>p2<br>         * </em><strong><em>@returns </em></strong><em>{number}<br>         */<br>        </em><strong>function </strong><em>getSqDist</em>(p1, p2) {<br><br>            <strong>var </strong>dx = p1.x - p2.x,<br>                dy = p1.y - p2.y;<br><br>            <strong>return </strong>dx * dx + dy * dy;<br>        }<br><br>        <em>/**<br>         * Square distance from a point to a segment<br>         * </em><strong><em>@param </em></strong><em>p<br>         * </em><strong><em>@param </em></strong><em>p1<br>         * </em><strong><em>@param </em></strong><em>p2<br>         * </em><strong><em>@returns </em></strong><em>{number}<br>         */<br>        </em><strong>function </strong><em>getSqSegDist</em>(p, p1, p2) {<br><br>            <strong>var </strong>x = p1.x,<br>                y = p1.y,<br>                dx = p2.x - x,<br>                dy = p2.y - y;<br><br>            <strong>if </strong>(dx !== 0 || dy !== 0) {<br><br>                <strong>var </strong>t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);<br><br>                <strong>if </strong>(t &gt; 1) {<br>                    x = p2.x;<br>                    y = p2.y;<br><br>                } <strong>else if </strong>(t &gt; 0) {<br>                    x += dx * t;<br>                    y += dy * t;<br>                }<br>            }<br><br>            dx = p.x - x;<br>            dy = p.y - y;<br><br>            <strong>return </strong>dx * dx + dy * dy;<br>        }<br><br>        <em>/**<br>         * Basic distance-based simplification<br>         * </em><strong><em>@param </em></strong><em>points<br>         * </em><strong><em>@param </em></strong><em>sqTolerance<br>         * </em><strong><em>@returns </em></strong><em>{[*]}<br>         */<br>        </em><strong>function </strong><em>simplifyRadialDist</em>(points, sqTolerance) {<br><br>            <strong>var </strong>prevPoint = points[0],<br>                newPoints = [prevPoint],<br>                point;<br><br>            <strong>for </strong>(<strong>var </strong>i = 1, len = points.length; i &lt; len; i++) {<br>                point = points[i];<br><br>                <strong>if </strong>(<em>getSqDist</em>(point, prevPoint) &gt; sqTolerance) {<br>                    newPoints.push(point);<br>                    prevPoint = point;<br>                }<br>            }<br><br>            <strong>if </strong>(prevPoint !== point) newPoints.push(point);<br><br>            <strong>return </strong>newPoints;<br>        }<br><br>        <em>/**<br>         *<br>         * </em><strong><em>@param </em></strong><em>points<br>         * </em><strong><em>@param </em></strong><em>first<br>         * </em><strong><em>@param </em></strong><em>last<br>         * </em><strong><em>@param </em></strong><em>sqTolerance<br>         * </em><strong><em>@param </em></strong><em>simplified<br>         */<br>        </em><strong>function </strong><em>simplifyDPStep</em>(points, first, last, sqTolerance, simplified) {<br>            <strong>var </strong>maxSqDist = sqTolerance,<br>                index;<br><br>            <strong>for </strong>(<strong>var </strong>i = first + 1; i &lt; last; i++) {<br>                <strong>var </strong>sqDist = <em>getSqSegDist</em>(points[i], points[first], points[last]);<br><br>                <strong>if </strong>(sqDist &gt; maxSqDist) {<br>                    index = i;<br>                    maxSqDist = sqDist;<br>                }<br>            }<br><br>            <strong>if </strong>(maxSqDist &gt; sqTolerance) {<br>                <strong>if </strong>(index - first &gt; 1) <em>simplifyDPStep</em>(points, first, index, sqTolerance, simplified);<br>                simplified.push(points[index]);<br>                <strong>if </strong>(last - index &gt; 1) <em>simplifyDPStep</em>(points, index, last, sqTolerance, simplified);<br>            }<br>        }<br><br>        <em>/**<br>         * Simplification using Ramer-Douglas-Peucker algorithm<br>         * </em><strong><em>@param </em></strong><em>points<br>         * </em><strong><em>@param </em></strong><em>sqTolerance<br>         * </em><strong><em>@returns </em></strong><em>{[*]}<br>         */<br>        </em><strong>function </strong><em>simplifyDouglasPeucker</em>(points, sqTolerance) {<br>            <strong>var </strong>last = points.length - 1;<br><br>            <strong>var </strong>simplified = [points[0]];<br>            <em>simplifyDPStep</em>(points, 0, last, sqTolerance, simplified);<br>            simplified.push(points[last]);<br><br>            <strong>return </strong>simplified;<br>        }<br><br>        <em>/**************************************************************************************************************<br>         * Algorith to interpolate control points from a series of points<br>         * see https://www.particleincell.com/2012/bezier-splines/<br>         **************************************************************************************************************/<br><br>        /**<br>         * Computes a series of control points on an x or y axis to make a bezier spline<br>         * </em><strong><em>@param </em></strong><em>K<br>         * </em><strong><em>@returns </em></strong><em>{{p1: Array, p2: Array}}<br>         */<br>        </em><strong>function </strong><em>computeControlPoints</em>(K)<br>        {<br>            <strong>var </strong>p1 = [];<br>            <strong>var </strong>p2 = [];<br>            <strong>var </strong>i;<br>            <strong>var </strong>m;<br>            <strong>var </strong>n = K.length-1;<br><br>            <em>/*rhs vector*/<br>            </em><strong>var </strong>a = [];<br>            <strong>var </strong>b = [];<br>            <strong>var </strong>c = [];<br>            <strong>var </strong>r = [];<br><br>            <em>/*left most segment*/<br>            </em>a[0] = 0;<br>            b[0] = 2;<br>            c[0] = 1;<br>            r[0] = K[0] + 2 * K[1];<br><br>            <em>/*internal segments*/<br>            </em><strong>for </strong>(i = 1; i &lt; n - 1; i++)<br>            {<br>                a[i] = 1;<br>                b[i] = 4;<br>                c[i] = 1;<br>                r[i] = 4 * K[i] + 2 * K[i+1];<br>            }<br><br>            <em>/*right segment*/<br>            </em>a[n-1] = 2;<br>            b[n-1] = 7;<br>            c[n-1] = 0;<br>            r[n-1] = 8 * K[n - 1] + K[n];<br><br>            <em>/*solves Ax=b with the Thomas algorithm (from Wikipedia)*/<br>            </em><strong>for </strong>(i = 1; i &lt; n; i++)<br>            {<br>                m = a[i] / b[i-1];<br>                b[i] = b[i] - m * c[i - 1];<br>                r[i] = r[i] - m * r[i - 1];<br>            }<br><br>            p1[n - 1] = r[n - 1] / b[n - 1];<br>            <strong>for </strong>(i = n - 2; i &gt;= 0; --i)<br>                p1[i] = (r[i] - c[i] * p1[i + 1]) / b[i];<br><br>            <em>/*we have p1, now compute p2*/<br>            </em><strong>for </strong>(i = 0; i &lt; n - 1; i++)<br>                p2[i] = 2 * K[i + 1] - p1[i + 1];<br><br>            p2[n - 1] = 0.5 * (K[n] + p1[n - 1]);<br><br>            <strong>return </strong>{ <strong>p1</strong>:p1, <strong>p2</strong>:p2 };<br>        }<br><br>        <em>/**************************************************************************************************************<br>         * kendo.drawing.PathEx<br>         **************************************************************************************************************/<br><br>        /**<br>         * An extended class for kendo.drawing.Path<br>         */<br>        </em>drawing.<strong>PathEx </strong>= drawing.Path.extend({<br><br>            <em>/**<br>             * A combination of distance-based and Ramer-Douglas-Peucker algorithms to simplify a path (list of points)<br>             * </em><strong><em>@param </em></strong><em>points<br>             * </em><strong><em>@param </em></strong><em>tolerance - number of pixels (the higher the less precise but the quicker)<br>             * </em><strong><em>@param </em></strong><em>useDistances - false only applies Ramer-Douglas-Peucker<br>             */<br>            </em>simplify: <strong>function </strong>(tolerance, useDistances) {<br>                <strong>if </strong>(<strong>this</strong>.<strong>segments</strong>.<strong>length </strong>&lt;= 2) {<br>                    <strong>return this</strong>;<br>                }<br>                <strong>var </strong>sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;<br><br>                <em>// Calculate simplified anchors using Ramer-Douglas-Peucker<br>                </em><strong>var </strong>anchors = Array.<strong>prototype</strong>.map.<strong>call</strong>(<strong>this</strong>.<strong>segments</strong>, <strong>function </strong>(segment) { <strong>return </strong>segment.anchor().clone() });<br>                anchors = useDistances ? <em>simplifyRadialDist</em>(anchors, sqTolerance) : anchors;<br>                anchors = <em>simplifyDouglasPeucker</em>(anchors, sqTolerance);<br><br>                <em>// Modify the path<br>                </em><strong>var </strong>segments = anchors.map(<strong>function </strong>(anchor) { <strong>return new </strong>drawing.<strong>Segment</strong>(anchor) });<br>                <em>// We cannot use splice because of https://github.com/telerik/kendo-ui-core/issues/3030<br>                // this.segments.splice(0, this.segments.length, segments);<br>                </em><strong>this</strong>.<strong>segments</strong>._splice(0, <strong>this</strong>.<strong>segments</strong>.<strong>length</strong>, segments);<br>                <strong>this</strong>.<strong>segments</strong>._change();<br><br>                <em>// return the path, especially to chain with smooth<br>                </em><strong>return this</strong>;<br>            },<br><br>            <em>/**<br>             * Smooth the path<br>             */<br>            </em>smooth: <strong>function </strong>() {<br><br>                <strong>var </strong>i;<br>                <strong>var </strong>length = <strong>this</strong>.<strong>segments</strong>.<strong>length</strong>;<br>                <strong>var </strong>xes = [];<br>                <strong>var </strong>yes = [];<br><br>                <em>// Collect anchor coordinates<br>                </em><strong>for </strong>(i = 0; i &lt; length; i++) {<br>                    <strong>var </strong>segment = <strong>this</strong>.<strong>segments</strong>[i];<br>                    xes.push(segment.anchor().x);<br>                    yes.push(segment.anchor().y);<br>                }<br><br>                <em>// Compute control points p1 and p2 for x and y directions<br>                </em><strong>var </strong>pxes = <em>computeControlPoints</em>(xes);<br>                <strong>var </strong>pyes = <em>computeControlPoints</em>(yes);<br><br>                <em>// Update path with control points<br>                </em><strong>for </strong>(i = 0; i &lt; length - 1; i++) {<br>                    <strong>this</strong>.<strong>segments</strong>[i].<strong>controlOut</strong>(<strong>new </strong>geometry.<strong>Point</strong>(pxes.<strong>p1</strong>[i], pyes.<strong>p1</strong>[i]));<br>                    <strong>this</strong>.<strong>segments</strong>[i + 1].<strong>controlIn</strong>(<strong>new </strong>geometry.<strong>Point</strong>(pxes.<strong>p2</strong>[i], pyes.<strong>p2</strong>[i]));<br>                }<br><br>                <strong>return this</strong>;<br>            },<br><br>            <em>/**<br>             * Prints an SVG path<br>             * </em><strong><em>@returns </em></strong><em>{*}<br>             */<br>            </em>stringify: <strong>function </strong>() {<br>                <strong>var </strong>PathNode = drawing.svg.<strong>PathNode</strong>;<br>                <strong>return </strong>PathNode.fn.printPath(<strong>this</strong>);<br>            }<em><br><br>        </em>});<br><br>    }(<strong>window</strong>.<strong>jQuery</strong>));<br><br>    <strong>return window</strong>.<strong>kendo</strong>;<br><br>}, <strong>typeof <em>define </em></strong>=== <strong>&#39;function&#39; </strong>&amp;&amp; <strong><em>define</em></strong>.amd ? <strong><em>define </em></strong>: <strong>function </strong>(_, f) { <strong>&#39;use strict&#39;</strong>; f(); });</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c40b5a83059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telerik Kendo UI, a great commercial product with a wrong open-source mindset]]></title>
            <link>https://medium.com/@jlchereau/telerik-kendo-ui-open-sourcing-done-wrong-4853502d63af?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/4853502d63af</guid>
            <category><![CDATA[kendo-ui]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[telerik]]></category>
            <category><![CDATA[ui-framework]]></category>
            <category><![CDATA[jquery]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Wed, 29 Mar 2017 12:59:02 GMT</pubDate>
            <atom:updated>2017-03-29T14:00:18.322Z</atom:updated>
            <content:encoded><![CDATA[<p>Telerik is a great company making great products and Kendo UI is definitely one of those. But they are commercially driven (nothing wrong here) and they have embraced open source as a fashionable marketing gimmick instead of a collaboration tool (which is wrong).</p><p>As a result <a href="https://github.com/telerik/kendo-ui-core">Kendo UI Core only got 1636 stars on GitHub</a> (as of today), which does not reflect the quality and the popularity of the Kendo UI framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*pU_fDz3clby0gRl6c_j0Rg.png" /></figure><p>For the sake of comparison:</p><ul><li><a href="https://github.com/driftyco/ionic">Ionic has 28715 stars on GitHub</a> when it is mobile-only (Kendo UI also targets desktop browsers) for Angular-only (Kendo UI also works with several other frameworks and libraries);</li><li>Within the 1.5K-star range, you can find <a href="https://github.com/easysoft/zui">easysoft’s ZUI</a>, a chinese jQuery UI framework nobody has ever heard about.</li></ul><p>The numbers just do not add up.</p><h4>Too many communication channels</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*SpDYJgKcqpJS2D9mGvCKUg.png" /></figure><p>Telerik promotes four communication channels with their developer community:</p><ul><li>Ask your questions in the <a href="http://www.telerik.com/forums/kendo-ui">Telerik forums</a>, but these forums are only available to commercial licensees to post questions;</li><li>Make suggestions and requests for enhancements in <a href="http://kendoui-feedback.telerik.com/forums/127393-kendo-ui-feedback">UserVoice</a>, which is useless for most incremental improvements as votes naturally gather on new widgets as shown here above;</li><li>Submit open-source defects as <a href="https://github.com/telerik/kendo-ui-core/issues">Github issues</a>;</li><li>Submit commercial defects as support tickets on their web site.</li></ul><p>It is up to the developer to properly qualify his request before using the right channel or provoke the ire of Telerik staff (see below).</p><h4>No value of the developer community</h4><p>As shown here above, the two most voted entries on UserVoice are a treeview in a combobox and a grid in a combobox and these entries have been reopened because Telerik staff discarded them as not “mobile-friendly” UI patterns. <em>In other words, Telerik knows better.</em></p><p>I have been taught that a bug is a software behavior that does not comply with the documentation. But this definition supposes that the documentation is both exact and comprehensive which is rarely the case. Therefore I have also been told that a bug is a software behavior that the majority of users would not expect, assuming such users have read and comply with the documentation.</p><p>Telerik provides a <a href="http://docs.telerik.com/kendo-ui/api/javascript/ui/toolbar#methods-enable">toolbar and the documentation stated that commands could be enabled/disabled</a>. This toolbar features “split buttons” which display a popup with a list of commands so anyone would have expected to be able to enable-disable these commands individually. In fact you could only enable-disable split buttons at the top level which the documentation did not specify. By the aforementioned definition, this is a defect and not a new feature. I have therefore <a href="https://github.com/telerik/kendo-ui-core/issues/1296">filed a bug on GitHub</a>. The answer I got has been pretty harsh considering the toolbar is part of the open-source version of Kendo UI: “<em>Please notice that the issue tracker of this repository is meant to serve as a collaboration platform for the open source part of the Kendo UI project. We don’t accept escalation of issues or feature requests here, unless a pull request is submitted</em>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*io0FIrjY6QZGE9rXiENmsA.png" /></figure><p>A year later, Telerik implemented enabling/disabling commands of a splitButton, which did not even work. So I have <a href="https://github.com/telerik/kendo-ui-core/issues/2207">filed another bug report</a> which has been pending for now 6 months. <em>Their message is crystal clear: Telerik doesn’t care about your bug reports</em>.</p><p>As a commercial company, Telerik is focused on new business and they pull resources to develop new products and attract new customers: the Kendo UI for jQuery team is now focused on <a href="http://www.telerik.com/kendo-angular-ui/">Kendo UI for Angular</a> and <a href="http://www.telerik.com/blogs/kendo-ui-for-react-in-2017">Kendo UI for React</a> and the original product and the existing developer community do not receive the level of care they deserve.</p><p>My last example is a pull request. Pull requests are the bread and butter of open source because open-source is free and pull requests are free labor. On 21 February, I have <a href="https://github.com/telerik/kendo-ui-core/pull/2802">submitted a very simple pull request</a> (a fix limited to one line of code) which has not received any comment and is still pending approval on 29 March. <em>Once again their message is clear: Telerik doesn’t need your pull requests</em>.</p><p>I am constantly fixing bugs in the Kendo UI framework and I could submit pull requests every month. I have also developed UI widgets that I could contribute, including a <a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kidoju.widgets.dropdowntree.js">dropdown tree widget</a>, a <a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kidoju.widgets.markdown.js">markdown widget</a>, a <a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kidoju.widgets.rating.js">rating widget</a> and a <a href="https://github.com/kidoju/Kidoju-Widgets/blob/master/src/js/kidoju.widgets.propertygrid.js">property grid widget</a> which are featured in the <a href="https://www.kidoju.com/">Kidoju Web Site</a> and have all been requested on UserVoice. <em>I won’t contribute these because such contributions would normally require code reviews and iterations that won’t happen considering Telerik is not considering the simplest contributions</em>.</p><h4>Is Kendo UI really open source?</h4><p>Kendo UI Core is not an open source product. Telerik has not embraced the open source mindset and model. <a href="http://www.telerik.com/kendo-ui/open-source-core">Their marketing lures developers with an open-source branding on a commercial product</a>. And although I am only song and praise about Kendo UI as a commercial product, I vividly condemn being a leech of open-source to actually sell licenses: open-source should feed on services or it is like being a drug dealer giving free samples to hook junkies.</p><p>I suppose I am not the only one thinking likewise, considering the low number of stars Kendo UI Core got on GitHub and the fact that no member of the developer community has ever contributed any new piece of code to the Kendo UI framework.</p><h4>What’s next?</h4><p>Open-source is a mindset: it is a commitment to share and care, not a commercial opportunity per se. Telerik needs to make a decision whether to make that commitment, streamline communication channels and assign the resources necessary to animate and reward a vibrant community of contributing developers. If they cannot make that commitment, they should not pretend and fail to deliver.</p><p>Hopefully this is constructive criticism and they will make it right.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4853502d63af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Unbuntu bash on Windows for nodeJS development]]></title>
            <link>https://medium.com/@jlchereau/install-unbuntu-bash-on-windows-for-nodejs-development-652156a0a53a?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/652156a0a53a</guid>
            <category><![CDATA[windows-10]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Sun, 08 Jan 2017 12:30:43 GMT</pubDate>
            <atom:updated>2017-01-08T12:39:53.082Z</atom:updated>
            <content:encoded><![CDATA[<p>Microsoft provides a great <a href="https://msdn.microsoft.com/en-us/commandline/wsl/install_guide">installation guide for Ubuntu bash on Windows</a> but this guide won’t get you all the way to run nodeJS which I have found necessary to build projects using make (although nodeJS works great on Windows).</p><p>After <a href="https://msdn.microsoft.com/en-us/commandline/wsl/install_guide">installing Ubuntu bash on Windows</a>, any sudo command will trigger sudo: unable to resolve host &lt;COMPUTER_NAME&gt;. To fix this, you need to modify /etc/hosts.</p><p>You can either use vim to open /etc/hosts in Ubuntu bash, or open %localappdata%\lxss\etc\hosts in a windows text editor that uses line feed instead of carriage return + line feed. Add the second line and designate your &lt;COMPUTER_NAME&gt;:</p><pre>127.0.0.1 localhost<br>127.0.0.1 &lt;COMPUTER_NAME&gt;</pre><pre># The following lines are desirable for IPv6 capable hosts<br>::1 ip6-localhost ip6-loopback<br>fe00::0 ip6-localnet<br>ff00::0 ip6-mcastprefix<br>ff02::1 ip6-allnodes<br>ff02::2 ip6-allrouters<br>ff02::3 ip6-allhosts</pre><p>With vim, you would:</p><ol><li>type sudo vim /etc/hosts at the Ubuntu bash prompt (you need sudo because the file is readonly);</li><li>move to the second line with keybord navigation keys;</li><li>type i to enter instert mode;</li><li>type 127.0.0.1 &lt;COMPUTER_NAME&gt;;</li><li>type Esc to exit insert mode and : to access the command line;</li><li>type wq! + return to write and quit without confirmation.</li></ol><p>Now you can update your installation and install GCC which many nodejs projects require to compile node_gyp:</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install -y build-essential</pre><p>Finally you can install nodeJS as explained at:</p><p><a href="https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions">Installing Node.js via package manager | Node.js</a></p><pre>curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -<br>sudo apt-get install -y nodejs</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652156a0a53a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate monkey testing with Selenium, WebDriver.io and Mocha]]></title>
            <link>https://medium.com/@jlchereau/automate-monkey-testing-with-selenium-webdriver-io-and-mocha-337ea935e308?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/337ea935e308</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Tue, 03 Jan 2017 19:37:30 GMT</pubDate>
            <atom:updated>2017-01-04T09:52:10.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Developers and QA/Testers know how the software they build works and naturally limit their interactions to working combinations defined by use cases as they have implemented them.</p><p>Monkey testing (or chaos testing) is about triggering random interactions on a user interface to break it (like a monkey would do).</p><p>At <a href="http://www.memba.com/">Memba Sarl</a>, we write all our tests with Mocha, Chai and Sinon. We use Selenium and WebDriver.io to automate browsers for functional tests as explained in <a href="https://medium.com/@jlchereau/how-to-configure-webdrivier-io-with-selenium-standalone-and-additional-browsers-9369d38bc4d1">How to configure webdrivier.io with selenium-standalone and additional browsers?</a></p><p>I suggest here a way to implement monkey testing with <a href="https://github.com/marmelab/gremlins.js">Gremlins.js</a>. Gremlins provide random mouse events, touch events and keyboard inputs over a web page.</p><p>Assuming you are using mocha (and have therefore installed mocha and wdio-mocha-framework in nodeJS), you will need to increase the timeout in wdio.conf.js to let gremlins do their work:</p><pre>exports.config = {<br>  // ...<br>  framework: &#39;mocha&#39;,<br><em>  </em>mochaOpts: {<br>    ui: &#39;bdd&#39;,<br>    timeout: 60000 <em>// for gremlins<br>  </em>},<br>  // ...<br>};</pre><p>In your mocha test file, you will need a function to load gremlins.min.js into your web application:</p><pre>function loadScript(source, callback) {<br>  var head = document.getElementsByTagName(&#39;head&#39;)[0];<br>  var scripts = head.getElementsByTagName(&#39;script&#39;);<br>  var found = false;<br>  for (var i = 0; i &lt; scripts.length; i++) {<br>    if (scripts[i].src === source) {<br>      found = true;<br>      break;<br>    }<br>  }<br>  if (!found) {<br>    var script = document.createElement(&#39;script&#39;);<br>    script.type = &#39;text/javascript&#39;;<br>    if (script.readyState) {  //IE<br>      script.onreadystatechange = function () {<br>        if (script.readyState === &#39;loaded&#39; ||<br>            script.readyState === &#39;complete&#39;) {<br>          script.onreadystatechange = null;<br>          callback();<br>        }<br>      };<br>    } else {  //Others<br>      script.onload = callback;<br>    }<br>    script.src = source;<br>    head.appendChild(script);<br>  }<br>}</pre><p>You will also need a function to unleash gremlins on the web page where they have been loaded using the previous function:</p><pre>function unleashGremlins(ttl, callback) {<br>    function stop() {<br>        horde.stop();<br>        callback();<br>    }<br>    var horde = window.gremlins.createHorde();<br>    horde.seed(1234);<br>    horde.after(callback);<br>    window.onbeforeunload = stop;<br>    setTimeout(stop, ttl);<br>    horde.unleash();<br>}</pre><p>IMPORTANT! Make sure you call this function with a “time to live” (ttl) that is lower than the mocha timeout, considering there are 3 ways to end the test:</p><ul><li>the entire horde has executed within the ttl;</li><li>a gremlin has triggered a navigation to another web page which would require reloading the script and unleashing the gremlins again;</li><li>the test is forcefully ended after its ttl before reaching the mocha timeout which would otherwise cause failure.</li></ul><p>You might want to add a utility function to the wdio browser object to wait until a page is entirely loaded:</p><pre>browser.waitForReadyStateEx = function (state, timeout) {<br>  return browser.waitUntil(function () {<br>    return state ===  browser.execute(function () {<br>      return document.readyState;<br>    }).value;<br>  }, timeout);<br>};</pre><p>Now you can combine <strong>loadScript</strong>, <strong>unleashGremlins </strong>and <strong>waitForReadyStateEx </strong>into a selenium+webdriver mocha test:</p><pre>// ...<br>describe(&#39;When Monkey testing with gremlins&#39;, function () {<br>  it(&#39;it should not raise any error&#39;, function () {<br>    browser.url(https://medium.com/&#39;http://localhost:3000/page&#39;);<br>    browser.<strong><em>waitForReadyStateEx</em></strong>(&#39;complete&#39;, WAIT);<br>    <em>// Now load your gremlins<br>    </em>browser.timeoutsAsyncScript(5000);<br>    browser.executeAsync(<strong><em>loadScript</em></strong>, &#39;./path_to/gremlins.min.js&#39;);<br>    browser.logger.info(&#39;Gremlins loaded&#39;);<br>    <em>// And unleash them<br>    </em>browser.timeoutsAsyncScript(60000);<br>    browser.executeAsync(<strong><em>unleashGremlins</em></strong>, 50000);<br>  });<br>});<br>// ...</pre><p>.. and watch your gremlins try to break your user interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6XbPmmist3N-KiH4T6LSg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337ea935e308" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure webdrivier.io with selenium-standalone and additional browsers?]]></title>
            <link>https://medium.com/@jlchereau/how-to-configure-webdrivier-io-with-selenium-standalone-and-additional-browsers-9369d38bc4d1?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9369d38bc4d1</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[webdriver]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Fri, 23 Dec 2016 08:24:37 GMT</pubDate>
            <atom:updated>2018-12-28T11:30:35.393Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/vvo/selenium-standalone">selenium-standalone</a> ships with drivers for chrome, internet explorer and firefox out of the box but lacks support for other browsers. I have had a hard time configuring phantomJS, Microsoft Edge and Opera, which is worth sharing.</p><p>I’ll refer you to <a href="http://webdriver.io/guide/getstarted/configuration.html">the get started guide on the webdriver.io web site to configure it</a>. You might want to use <a href="https://github.com/webdriverio/grunt-webdriver">grunt-webdriver</a> or <a href="https://github.com/webdriverio/gulp-webdriver">gulp-webdriver</a> to automate your tests on Travis-CI via npm test. There is nothing really complicated here.</p><p>I am assuming that you are <a href="http://webdriver.io/guide/testrunner/gettingstarted.html">using the wdio test runner</a>, therefore you should have a wdio.conf.js file, which exports your wdio configuration:</p><pre>exports.config = {<br>  // configuration parameters <br>}</pre><h4>Chrome and Internet Explorer</h4><p>Chrome and Internet explorer are easy to configure because drivers are included with selenium-standalone. Simply add the corresponding browserName in capabilities:</p><pre>exports.config = {<br>  // ...<br>  capabilities: [<br>    { browserName: &#39;chrome&#39; },<br>    { browserName: &#39;internet explorer&#39; },<br>  ],<br>  // ...<br>  services: [&#39;selenium-standalone&#39;],<br>  // ...<br>}</pre><h4>Firefox</h4><p>The firefox driver is also included with selenium-standalone but you need marionette: true to <a href="https://github.com/vvo/selenium-standalone/issues/237">make it work</a>:</p><pre>exports.config = {<br>  // ...<br>  capabilities: [<br>    // ...<br>    { browserName: &#39;firefox&#39;, marionette: true }<br>  ],<br>  // ...<br>  services: [&#39;selenium-standalone&#39;],<br>  // ...<br>}</pre><h4>PhantomJS</h4><p><a href="http://phantomjs.org/">PhantomJS</a> and <a href="https://github.com/detro/ghostdriver">Ghostdriver</a> are not included with selenium-standalone, so you need to install <a href="https://github.com/Medium/phantomjs">phantomjs-prebuilt</a>. Specifying browserName is enough on Travis-CI, but Windows requires that you also add phantomjs.binary.path:</p><pre>exports.config = {<br>  // ...<br>  capabilities: [<br>    // ...<br>    { browserName: &#39;phantomjs&#39;, &#39;phantomjs.binary.path&#39;: &#39;&lt;path&gt;&#39; }<br>  ],<br>  // ...<br>  services: [&#39;selenium-standalone&#39;],<br>  // ...<br>}</pre><p>where &lt;path&gt; is either (if phantomJS has been installed on your computer and added to PATH):</p><pre>&#39;C:\\Program Files (x86)\\PhantomJS\\bin\\phantomjs.exe&#39;</pre><p>or (if phantomJS was not found on your computer when installing phantomjs-prebuilt):</p><pre>path.join(__dirname, &#39;./node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs.exe&#39;)</pre><h4>Microsoft Edge</h4><p>The Microsoft Edge driver must be installed specifically. Links to all selenium drivers are available at <a href="http://docs.seleniumhq.org/download/"><em>http://docs.seleniumhq.org/download/</em></a></p><p>Copy <strong>MicrosoftWebDriver.exe</strong> to any &lt;path&gt; on your hard drive and configure browserName and seleniumArgs as follows:</p><pre>exports.config = {<br>  // ...<br>  capabilities: [<br>    // ...<br>    {<br>      browserName: &#39;MicrosoftEdge&#39;,<br>      osPlatform: &#39;Windows&#39;,<br>      osVersion: &#39;10&#39;<br>    }<br>  ],<br>  // ...<br>  services: [&#39;selenium-standalone&#39;],<br>  seleniumArgs: {<br>    javaArgs: [<br>      &#39;-Dwebdriver.edge.driver=&lt;path_to_driver&gt;&#39;<br>    ]<br>  }<br>  // ...<br>}</pre><p>where &lt;path_to_driver&gt; designates the path to the driver:</p><pre>path.join(__dirname, &#39;./node_modules/selenium-standalone/.selenium/edgedriver/MicrosoftWebDriver.exe&#39;)</pre><h4>Opera</h4><p><a href="https://github.com/operasoftware/operachromiumdriver/releases/tag/v0.2.2">Opera driver 0.2.2</a> does not work with Opera 42+. Since Opera is built on Chromium, the trick is to use the chrome driver and designate the opera binary as follows:</p><pre>exports.config = {<br>  // ...<br>  capabilities: [<br>    // ...<br>    {<br>      browserName: &#39;operablink&#39;<br>      chromeOptions: {<br>        args: [],<br>        extensions: [],<br>        binary: &lt;path_to_opera&gt;<br>      }<br>    }<br>  ],<br>  // ...<br>  services: [&#39;selenium-standalone&#39;],<br>  seleniumArgs: {<br>    javaArgs: [<br>      &#39;-Dwebdriver.opera.driver=&lt;path_to_driver&gt;&#39;<br>    ]<br>  }<br>  // ...<br>}</pre><p>where &lt;path_to_opera&gt; designates the opera executable:</p><pre>&#39;C:\\Program Files (x86)\\Opera\\42.0.2393.94\\opera.exe&#39;</pre><p>and &lt;path_to_driver&gt; designates the chrome driver:</p><pre>path.join(__dirname, &#39;./node_modules/selenium-standalone/.selenium/chromedriver/2.25-x64-chromedriver&#39;)</pre><p>This configuration works on Windows 10 with latest versions of aforementioned nodeJS modules and browsers as of December 2016. Please use comments to let me know of any discrepancies you experience on other platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9369d38bc4d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop using InAppBrowser for your Cordova/Phonegap oAuth flow]]></title>
            <link>https://medium.com/@jlchereau/stop-using-inappbrowser-for-your-cordova-phonegap-oauth-flow-a806b61a2dc5?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/a806b61a2dc5</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[phonegap]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Wed, 30 Nov 2016 11:14:07 GMT</pubDate>
            <atom:updated>2016-11-30T11:14:07.945Z</atom:updated>
            <content:encoded><![CDATA[<h3>oAuth 2 flow</h3><p>There are several possible oAuth flows which are variations of the following flow depending on the constituents: app, browser, web server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*K2ZzEk4NUtT6HgEvI4LbGw.png" /><figcaption>Source: <a href="https://developers.google.com/identity/protocols/OAuth2">https://developers.google.com/identity/protocols/OAuth2</a></figcaption></figure><p>After registering your web server with an oAuth provider like Google, obtaining a client id and a client secret and designating your callback endpoint, the oAuth flow has the following steps:</p><ol><li>Upon clicking a sign-in button, the app/browser navigates to a sign-in url so as to request a token from the provider, e.g.:</li></ol><pre>https://accounts.google.com/o/oauth2/v2/auth?<br> scope=email%20profile&amp;<br> state=9876543210&amp;<br> redirect_uri=https%3A%2F%2Fwww.example.com%2Ftoken&amp;<br> response_type=code&amp;<br> client_id=812741506391.apps.googleusercontent.com</pre><p>2. Once redirected, the user fills in a form to sign in with the provider, i.e. Google, and authorizes the application;</p><p>3. Then, the designated callback endpoint at your server should receive a code, e.g.:</p><pre>https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7</pre><p>4. Then your server should exchange this code for a token by posting the code to another endpoint and receiving the token in the response, e.g.:</p><pre>https://www.googleapis.com/oauth2/v4/token</pre><p>5. While your server received the token, the user app/browser gets redirected to the redirect_uri defined in the sign-in url with the same token in the hash:</p><pre>https://www.example.com/token#access_token=1/fFBGRNJru1FQd44AzqT3Zg&amp;token_type=Bearer&amp;expires_in=3600</pre><p>6. Thereafter, both your app/browser and web server share a token to authenticate and authorize access.</p><p>More details at <a href="https://developers.google.com/identity/protocols/OAuth2UserAgent">https://developers.google.com/identity/protocols/OAuth2UserAgent</a>.</p><h3>InAppBrowser</h3><p>Let us now consider your Phonegap/Cordova mobile application.</p><p><a href="http://phonegap-tips.com/articles/google-api-oauth-with-phonegaps-inappbrowser.html">Many articles would advise to use the InAppBrowser and its loadstart event to read the token from the url returned by the corresponding event handler</a>.</p><p>If this might have been relevant a few years ago without any decent alternative, using the <a href="https://github.com/apache/cordova-plugin-inappbrowser">InAppBrowser</a> for oAuth flows is now obsolete.</p><p>There are several reasons not to do it:</p><ol><li><a href="https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html">Google has now deprecated the use of webviews to request oAuth tokens</a>;</li><li>InAppBrowser uses UIWebView on iOS and is incompatible with the more recent WKWebView Engine, i.e. <a href="http://devgirl.org/2016/01/11/a-faster-hybrid-app-for-the-new-year/">when WKWebView is enabled</a>, the <a href="https://issues.apache.org/jira/browse/CB-11136">InAppBrowser cannot be automatically closed at the end of the flow</a>. <a href="https://github.com/apache/cordova-plugin-inappbrowser/pull/187">A fix as yet to be released</a>.</li><li>But more importantly, the InAppBrowser breaks the single sign-on paradigm because it does not remember user credentials, which is a nightmare when MFA is enabled.</li></ol><h3>SafariViewController to the rescue</h3><p>The proper solution involves <a href="https://github.com/EddyVerbruggen/cordova-plugin-safariviewcontroller">SafariViewController</a> and a <a href="https://github.com/EddyVerbruggen/Custom-URL-scheme">Custom URL Scheme</a>.</p><ol><li><a href="https://github.com/EddyVerbruggen/Custom-URL-scheme">Register a custom url scheme with your app</a>, e.g. mycoolapp://</li><li>Define the following forward page on your server, e.g. at https://www.example.com/fw</li></ol><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src<br>    &#39;none&#39;;script-src &#39;unsafe-inline&#39;;&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script&gt;window.location.assign(&#39;mycoolapp://token&#39; +<br>    window.location.hash);&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>3. In your app, use <a href="https://github.com/EddyVerbruggen/cordova-plugin-safariviewcontroller">SafariViewController</a> to open the sign in url, consideringredirect_uri should target <a href="https://www.example.com/blank">https://www.example.com/f</a>w</p><pre>SafariViewController.isAvailable(function (available) {<br>  if (available) {<br>    SafariViewController.show(<br>      {<br>        url: &#39;https://accounts.google.com/o/oauth2/v2/auth?&#39; +<br>             &#39;scope=email%20profile&amp;&#39; +<br>             &#39;state=9876543210&amp;&#39; +<br>             &#39;redirect_uri=https%3A%2F%2Fwww.example.com%2Ffw&amp;&#39; +<br>             &#39;response_type=code&amp;&#39; +<br>             &#39;client_id=812741506391.apps.googleusercontent.com&#39;<br>      },<br>      function (result) {},<br>      function (error) {}<br>    );<br>  }<br>});</pre><p>4. This starts the oAuth in a SafariViewController. At the end, the redirection to redirect_uri:</p><pre>https://www.example.com/fw#access_token=1/fFBGRNJru1FQd44AzqT3Zg&amp;token_type=Bearer&amp;expires_in=3600</pre><p>5. Will be forwarded to:</p><pre>mycoolapp://token#access_token=1/fFBGRNJru1FQd44AzqT3Zg&amp;token_type=Bearer&amp;expires_in=3600</pre><p>6. Therefore in you app, implement the handleOpenURL event handler to close the SafariViewController and parse the token in the hash:</p><pre>handleOpenURL = <strong>function </strong>(url) {<br>  SafariViewController.<strong>hide</strong>();<br>  if (url.startsWith(&#39;mycollapp://token#&#39;) {<br>    <strong>var</strong> token = /access_token=([^&amp;]+)/.exec(url);<br>  }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a806b61a2dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get splash screens to show in android apps generated by Phonegap Build]]></title>
            <link>https://medium.com/@jlchereau/how-to-get-splash-screens-to-show-in-android-apps-generated-by-phonegap-build-c0210f2783ff?source=rss-b97fb54a8cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0210f2783ff</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cordova]]></category>
            <category><![CDATA[phonegap]]></category>
            <category><![CDATA[crosswalk]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jacques L. Chereau]]></dc:creator>
            <pubDate>Thu, 20 Oct 2016 13:46:22 GMT</pubDate>
            <atom:updated>2017-09-05T12:45:18.507Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have lost time trying to figure out what ought to be a simple task, and hopefully, you will have found this post before doing the same.</blockquote><p>I am part of a team developing the <a href="https://www.kidoju.com/">Kidoju </a>web site and mobile application.</p><p>We are running the Phonegap CLI version 6.3.4 with cordova-plugin-splashscreen version 4.0.0. Our Phonegap application was started from a skeleton generated using phonegap create and all files in the www/res directory have been replaced with Kidoju assets.</p><p>After pushing to Github and updating code on Phonegap Build (PGB), we successfully installed application packages that would display a splash screen on iOS devices but not on Android devices.</p><p>Searching the web yields several recommendations among which:</p><ol><li>Do not use the npm version of cordova-plugin-splashscreen, instead install using phonegap plugin add <a href="https://github.com/apache/cordova-plugin-splashscreen.git">https://github.com/apache/cordova-plugin-splashscreen.git</a>;</li><li>Manually copy files to the platforms subdirectories;</li><li>Add &lt;preference name=&quot;SplashScreen&quot; value=&quot;screen&quot; /&gt; to config.xml</li><li>Remove cordova-plugin-crosswalk-webview since Crosswalk is the culprit;</li></ol><p>These do not work.</p><h3>First step</h3><blockquote>Update: <a href="https://blog.phonegap.com/phonegap-7-0-1-now-on-build-and-it-includes-some-important-changes-89087fe465f5#1891">This is now fixed in Phonegap/Cordova 7 which properly uses <strong>density</strong></a>. Go to step 2 if using v7.</blockquote><p>We have changed the file extension of our application package for Android from .apk to .zip and realized that the package generated by PGB was missing our splash screen resources although they were copied to platforms/android/res in our development environment.</p><p>The config.xml file generated by the Phonegap CLI is wrong, especially:</p><pre>&lt;splash density=&quot;land-ldpi&quot; src=&quot;www/res/screen/android/drawable-land-ldpi-screen.png&quot; /&gt;</pre><p>land-ldpi is not a <strong>density </strong>but a <strong>qualifier </strong>as documented at <a href="http://docs.phonegap.com/phonegap-build/configuring/icons-and-splash/">http://docs.phonegap.com/phonegap-build/configuring/icons-and-splash/</a></p><p>Therefore the correct splash tag is:</p><pre>&lt;splash qualifier=&quot;land-ldpi&quot; src=&quot;www/res/screen/android/drawable-land-ldpi-screen.png&quot; /&gt;</pre><p>After correcting all splash tags for the Android platform in config.xml, we confirmed that our splash screen resources were <strong>copied </strong>into the application package generated by PGB for Android but a splash screen would still not show.</p><h3>Second step</h3><p>We have then noticed that our splash screens were named screen.png in the subdirectories of platforms/android/res in our development environment, but splash.png in the corresponding subdirectories of res in the application package generated by PGB for Android:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*KYu2Lqk6hK0I8ZMdjn4gNw.png" /></figure><p>We have therefore added the following preference to config.xml:</p><pre>&lt;platform name=&quot;android&quot;&gt;<br>    &lt;preference name=&quot;SplashScreen&quot; value=&quot;splash&quot; /&gt;<br>&lt;/platform&gt;</pre><blockquote>This is how we got splash screens to show in android apps generated by Phonegap Build. I hope this helps.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0210f2783ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>