text
stringlengths
2
1.04M
meta
dict
Phoenix controllers act as intermediary modules. Their functions - called actions - are invoked from the router in response to HTTP requests. The actions, in turn, gather all the necessary data and perform all the necessary steps before invoking the view layer to render a template or returning a JSON response. Phoenix controllers also build on the Plug package, and are themselves plugs. Controllers provide the functions to do almost anything we need to in an action. If we do find ourselves looking for something that Phoenix controllers don't provide, however, we might find what we're looking for in Plug itself. Please see the [Plug Guide](http://www.phoenixframework.org/docs/understanding-plug) or [Plug Documentation](http://hexdocs.pm/plug/) for more information. A newly generated Phoenix app will have a single controller, the `PageController`, which can be found at `web/controllers/page_controller.ex` and looks like this. ```elixir defmodule HelloPhoenix.PageController do use HelloPhoenix.Web, :controller def index(conn, _params) do render conn, "index.html" end end ``` The first line below the module definition invokes the `__using__/1` macro of the `HelloPhoenix.Web` module, which imports some useful modules. The `PageController` gives us the `index` action to display the Phoenix welcome page associated with the default route Phoenix defines in the router. ### Actions Controller actions are just functions. We can name them anything we like as long as they follow Elixir's naming rules. The only requirement we must fulfill is that the action name matches a route defined in the router. For example, in `web/router.ex` we could change the action name in the default route that Phoenix gives us in a new app from index: ```elixir get "/", HelloPhoenix.PageController, :index ``` To test: ```elixir get "/", HelloPhoenix.PageController, :test ``` As long as we change the action name in the `PageController` to `test` as well, the welcome page will load as before. ```elixir defmodule HelloPhoenix.PageController do . . . def test(conn, _params) do render conn, "index.html" end end ``` While we can name our actions whatever we like, there are conventions for action names which we should follow whenever possible. We went over these in the [Routing Guide](http://www.phoenixframework.org/docs/routing), but we'll take another quick look here. - index - renders a list of all items of the given resource type - show - renders an individual item by id - new - renders a form for creating a new item - create - receives params for one new item and saves it in a datastore - edit - retrieves and individual item by id and displays it in a form for editing - update - receives params for one edited item and saves it to a datastore - delete - receives an id for an item to be deleted and deletes it from a datastore Each of these actions takes two parameters, which will be provided by Phoenix behind the scenes. The first parameter is always `conn`, a struct which holds information about the request such as the host, path elements, port, query string, and much more. `conn`, comes to Phoenix via Elixir's Plug middleware framework. More detailed info about `conn` can be found in [plug's documentation](http://hexdocs.pm/plug/Plug.Conn.html). The second parameter is `params`. Not surprisingly, this is a map which holds any parameters passed along in the HTTP request. It is a good practice to pattern match against params in the function signature to provide data in a simple package we can pass on to rendering. We saw this in the [Adding Pages guide](http://www.phoenixframework.org/docs/adding-pages) when we added a messenger parameter to our `show` route in `web/controllers/hello_controller.ex`. ```elixir defmodule HelloPhoenix.HelloController do . . . def show(conn, %{"messenger" => messenger}) do render conn, "show.html", messenger: messenger end end ``` In some cases - often in `index` actions, for instance - we don't care about parameters because our behavior doesn't depend on them. In those cases, we don't use the incoming params, and simply prepend the variable name with an underscore, `_params`. This will keep the compiler from complaining about the unused variable while still keeping the correct arity. ### Gathering Data While Phoenix does not ship with its own data access layer, the Elixir project [Ecto](http://hexdocs.pm/ecto) provides a very nice solution for those using the [Postgres](http://www.postgresql.org/) relational database. (There are plans to offer other adapters for Ecto in the future.) We cover how to use Ecto in a Phoenix project in the [Ecto Models Guide](http://www.phoenixframework.org/docs/ecto-models). Of course, there are many other data access options. [Ets](http://www.erlang.org/doc/man/ets.html) and [Dets](http://www.erlang.org/doc/man/ets.html) are key value data stores built into [OTP](http://www.erlang.org/doc/). OTP also provides a relational database called [mnesia](http://www.erlang.org/doc/man/mnesia.html) with its own query language called QLC. Both Elixir and Erlang also have a number of libraries for working with a wide range of popular data stores. The data world is your oyster, but we won't be covering these options in these guides. ### Flash Messages There are times when we need to communicate with users during the course of an action. Maybe there was an error updating a model. Maybe we just want to welcome them back to the application. For this, we have flash messages. The `Phoenix.Controller` module provides the `put_flash/3` and `get_flash/2` functions to help us set and retrieve flash messages as a key value pair. Let's set two flash messages in our `HelloPhoenix.PageController` to try this out. To do this we modify the `index` action as follows: ```elixir defmodule HelloPhoenix.PageController do . . . def index(conn, _params) do conn |> put_flash(:info, "Welcome to Phoenix, from flash info!") |> put_flash(:error, "Let's pretend we have an error.") |> render("index.html") end end ``` The `Phoenix.Controller` module is not particular about the keys we use. As long as we are internally consistent, all will be well. `:info` and `:error`, however, are common. In order to see our flash messages, we need to be able to retrieve them and display them in a template/layout. One way to do the first part is with `get_flash/2` which takes `conn` and the key we care about. It then returns the value for that key. Fortunately, our application layout, `web/templates/layout/app.html.eex`, already has markup for displaying flash messages. ```html <p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p> <p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p> ``` When we reload the [Welcome Page](http://localhost:4000/), our messages should appear just above "Welcome to Phoenix!" Besides `put_flash/3` and `get_flash/2`, the `Phoenix.Controller` module has another useful function worth knowing about. `clear_flash/1` takes only `conn` and removes any flash messages which might be stored in the session. ### Rendering Controllers have several ways of rendering content. The simplest is to render some plain text using the `text/2` function which Phoenix provides. Let's say we have a `show` action which receives an id from the params map, and all we want to do is return some text with the id. For that, we could do the following. ```elixir def show(conn, %{"id" => id}) do text conn, "Showing id #{id}" end ``` Assuming we had a route for `get "/our_path/:id"` mapped to this `show` action, going to `/our_path/15` in your browser should display `Showing id 15` as plain text without any HTML. A step beyond this is rendering pure JSON with the `json/2` function. We need to pass it something that the [Poison library](https://github.com/devinus/poison) can parse into JSON, such as a map. (Poison is one of Phoenix's dependencies.) ```elixir def show(conn, %{"id" => id}) do json conn, %{id: id} end ``` If we again visit `our_path/15` in the browser, we should see a block of JSON with the key `id` mapped to the number `15`. ```elixir { id: "15" } ``` Phoenix controllers can also render HTML without a template. As you may have already guessed, the `html/2` function does just that. This time, we implement the `show` action like this. ```elixir def show(conn, %{"id" => id}) do html conn, """ <html> <head> <title>Passing an Id</title> </head> <body> <p>You sent in id #{id}</p> </body> </html> """ end ``` Hitting `/our_path/15` now renders the HTML string we defined in the `show` action, with the value `15` interpolated. Note that what we wrote in the action is not an `eex` template. It's a multi-line string, so we interpolate the `id` variable like this `#{id}` instead of this `<%= id %>`. It is worth noting that the `text/2`, `json/2`, and `html/2` functions require neither a Phoenix view, nor a template to render. The `json/2` function is obviously useful for writing APIs, and the other two may come in handy, but rendering a template into a layout with values we pass in is a very common case. For this, Phoenix provides the `render/3` function. Interestingly, `render/3` is defined in the `Phoenix.View` module instead of `Phoenix.Controller`, but it is aliased in `Phoenix.Controller` for convenience. We have already seen the render function in the [Adding Pages Guide](http://www.phoenixframework.org/docs/adding-pages). Our `show` action in `web/controllers/hello_controller.ex` looked like this. ```elixir defmodule HelloPhoenix.HelloController do use HelloPhoenix.Web, :controller def show(conn, %{"messenger" => messenger}) do render conn, "show.html", messenger: messenger end end ``` In order for the `render/3` function to work correctly, the controller must have the same root name as the individual view. The individual view must also have the same root name as the template directory where the `show.html.eex` template lives. In other words, the `HelloController` requires `HelloView`, and `HelloView` requires the existence of the `web/templates/hello` directory, which must contain the `show.html.eex` template. `render/3` will also pass the value which the `show` action received for `messenger` from the params hash into the template for interpolation. If we need to pass values into the template when using `render`, that's easy. We can pass a dictionary like we've seen with `messenger: messenger`, or we can use `Plug.Conn.assign/3`, which conveniently returns `conn`. ```elixir def index(conn, _params) do conn |> assign(:message, "Welcome Back!") |> render("index.html") end ``` Note: The `Phoenix.Controller` module imports `Plug.Conn`, so shortening the call to `assign/3` works just fine. We can access this message in our `index.html.eex` template, or in our layout, with this `<%= @message %>`. Passing more than one value in to our template is as simple as connecting `assign/3` functions together in a pipeline. ```elixir def index(conn, _params) do conn |> assign(:message, "Welcome Back!") |> assign(:name, "Dweezil") |> render("index.html") end ``` With this, both `@message` and `@name` will be available in the `index.html.eex` template. What if we want to have a default welcome message that some actions can override? That's easy, we just use `plug` and transform `conn` on its way towards the controller action. ```elixir plug :assign_welcome_message, "Welcome Back" def index(conn, _params) do conn |> assign(:name, "Dweezil") |> render("index.html") end defp assign_welcome_message(conn, msg) do assign(conn, :message, msg) end ``` What if we want to plug `assign_welcome_message`, but only for some of our actions? Phoenix offers a solution to this by letting us specify which actions a plug should be applied to. If we only wanted `plug :assign_welcome_message` to work on the `index` and `show` actions, we could do this. ```elixir defmodule HelloPhoenix.PageController do use HelloPhoenix.Web, :controller plug :assign_welcome_message, "Hi!" when action in [:index, :show] . . . ``` ### Sending responses directly If none of the rendering options above quite fits our needs, we can compose our own using some of the functions that Plug gives us. Let's say we want to send a response with a status of "201" and no body whatsoever. We can easily do that with the `send_resp/3` function. ```elixir def index(conn, _params) do conn |> send_resp(201, "") end ``` Reloading [http://localhost:4000](http://localhost:4000) should show us a completely blank page. The network tab of our browser's developer tools should show a response status of "201". If we would like to be really specific about the content type, we can use `put_resp_content_type/2` in conjunction with `send_resp/3`. ```elixir def index(conn, _params) do conn |> put_resp_content_type("text/plain") |> send_resp(201, "") end ``` Using Plug functions in this way, we can craft just the response we need. Rendering does not end with the template, though. By default, the results of the template render will be inserted into a layout, which will also be rendered. [Templates and layouts](http://www.phoenixframework.org/docs/templates) have their own guide, so we won't spend much time on them here. What we will look at is how to assign a different layout, or none at all, from inside a controller action. ### Assigning Layouts Layouts are just a special subset of templates. They live in `/web/templates/layout`. Phoenix created one for us when we generated our app. It's called `app.html.eex`, and it is the layout into which all templates will be rendered by default. Since layouts are really just templates, they need a view to render them. This is the `LayoutView` module defined in `/web/views/layout_view.ex`. Since Phoenix generated this view for us, we won't have to create a new one as long as we put the layouts we want to render inside the `/web/templates/layout` directory. Before we create a new layout, though, let's do the simplest possible thing and render a template with no layout at all. The `Phoenix.Controller` module provides the `put_layout/2` function for us to switch layouts. This takes `conn` as its first argument and a string for the basename of the layout we want to render. Another clause of the function will match on the boolean `false` for the second argument, and that's how we will render the Phoenix welcome page without a layout. In a freshly generated Phoenix app, edit the `index` action of the `PageController` module `web/controllers/page_controller.ex` to look like this. ```elixir def index(conn, params) do conn |> put_layout(false) |> render "index.html" end ``` After reloading [http://localhost:4000/](http://localhost:4000/), we should see a very different page, one with no title, logo image, or css styling at all. Very Important! For function calls in the middle of a pipeline, like `put_layout/2` here, it is critical to use parenthesis around the arguments because the pipe operator binds very tightly. This leads to parsing problems and very strange results. If you ever get a stack trace that looks like this, ```text **(FunctionClauseError) no function clause matching in Plug.Conn.get_resp_header/2 Stacktrace (plug) lib/plug/conn.ex:353: Plug.Conn.get_resp_header(false, "content-type") ``` where your argument replaces `conn` as the first argument, one of the first things to check is whether there are parens in the right places. This is fine. ```elixir def index(conn, params) do conn |> put_layout(false) |> render "index.html" end ``` Whereas this won't work. ```elixir def index(conn, params) do conn |> put_layout false |> render "index.html" end ``` Now let's actually create another layout and render the index template into it. As an example, let's say we had a different layout for the admin section of our application which didn't have the logo image. To do this, let's copy the existing `app.html.eex` to a new file `admin.html.eex` in the same directory `web/templates/layout`. Then let's remove the line in `admin.html.eex` that displays the logo. ```html <span class="logo"></span> <!-- remove this line --> ``` Then, pass the basename of the new layout into `put_layout/2` in our `index` action in `web/controllers/page_controller.ex`. ```elixir def index(conn, params) do conn |> put_layout("admin.html") |> render "index.html" end ``` When we load the page, and we should be rendering the admin layout without a logo. ### Overriding Rendering Formats Rendering HTML through a template is fine, but what if we need to change the rendering format on the fly? Let's say that sometimes we need HTML, sometimes we need plain text, and sometimes we need JSON. Then what? Phoenix allows us to change formats on the fly with the `format` query string parameter. To make this happen, Phoenix requires an appropriately named view and an appropriately named template in the correct directory. As an example, let's take the `PageController` index action from a newly generated app. Out of the box, this has the right view, `PageView`, the right templates directory, `/web/templates/page`, and the right template for rendering HTML, `index.html.eex`. ```elixir def index(conn, _params) do render conn, "index.html" end ``` What it doesn't have is an alternative template for rendering text. Let's add one at `/web/templates/page/index.text.eex`. Here is our example `index.text.eex` template. ```elixir "OMG, this is actually some text." ``` There are just few more things we need to do to make this work. We need to tell our router that it should accept the `text` format. We do that by adding `text` to the list of accepted formats in the `:browser` pipeline. Let's open up `web/router.ex` and change the `plug :accepts` to include `text` as well as `html` like this. ```elixir defmodule HelloPhoenix.Router do use HelloPhoenix.Web, :router pipeline :browser do plug :accepts, ["html", "text"] plug :fetch_session plug :protect_from_forgery end . . . ``` We also need to tell the controller to render a template with the same format as the one found in `conn.params["format"]`. We do that by substituting the atom version of the template `:index` for the string version `"index.html"`. ```elixir def index(conn, _params) do render conn, :index end ``` If we go to [http://localhost:4000/?format=text](http://localhost:4000/?format=text), we will see `OMG, this is actually some text.` Of course, we can pass data into our template as well. Let's change our action to take in a message parameter by removing the `_` in front of `params` in the function definition. This time, we'll use the somewhat less-flexible string version of our text template, just to see that it works as well. ```elixir def index(conn, params) do render conn, "index.text", message: params["message"] end ``` And let's add a bit to our text template. ```elixir "OMG, this is actually some text." <%= @message %> ``` Now if we go to `http://localhost:4000/?format=text&message=CrazyTown`, we will see "OMG, this is actually some text. CrazyTown" ### Setting the Content Type Analogous to the `format` query string param, we can render any sort of format we want by modifying the HTTP Accepts Header and providing the appropriate template. If we wanted to render an xml version of our `index` action, we might implement the action like this in `web/page_controller.ex`. ```elixir def index(conn, _params) do conn |> put_resp_content_type("text/xml") |> render "index.xml", content: some_xml_content end ``` We would then need to provide an `index.xml.eex` template which created valid xml, and we would be done. For a list of valid content mime-types, please see the [mime.types](https://github.com/elixir-lang/plug/blob/master/lib/plug/mime.types) documentation from the Plug middleware framework. ### Setting the HTTP Status We can also set the HTTP status code of a response similarly to the way we set the content type. The `Plug.Conn` module, imported into all controllers, has a `put_status/2` function to do this. `put_status/2` takes `conn` as the first parameter and as the second parameter either an integer or a "friendly name" used as an atom for the status code we want to set. Here is the list of supported [friendly names](https://github.com/elixir-lang/plug/blob/master/lib/plug/conn/status.ex#L7-L63). Let's change the status in our `PageController` `index` action. ```elixir def index(conn, _params) do conn |> put_status(202) |> render("index.html") end ``` The status code we provide must be valid - [Cowboy](https://github.com/ninenines/cowboy), the web server Phoenix runs on, will throw an error on invalid codes. If we look at our development logs (which is to say, the iex session), or use our browser's web inspection network tool, we will see the status code being set as we reload the page. If the action sends a response - either renders or redirects - changing the code will not change the behavior of the response. If, for example, we set the status to 404 or 500 and then `render "index.html"`, we do not get an error page. Similarly, no 300 level code will actually redirect. (It wouldn't know where to redirect to, even if the code did affect behavior.) The following implementation of the `HelloPhoenix.PageController` `index` action, for example, will _not_ render the default `not_found` behavior as expected. ```elixir def index(conn, _params) do conn |> put_status(:not_found) |> render("index.html") end ``` The correct way to render the 404 page from `HelloPhoenix.PageController` is: ```elixir def index(conn, _params) do conn |> put_status(:not_found) |> render(HelloPhoenix.ErrorView, "404.html") end ``` ### Redirection Often, we need to redirect to a new url in the middle of a request. A successful `create` action, for instance, will usually redirect to the `show` action for the model we just created. Alternately, it could redirect to the `index` action to show all the things of that same type. There are plenty of other cases where redirection is useful as well. Whatever the circumstance, Phoenix controllers provide the handy `redirect/2` function to make redirection easy. Phoenix differentiates between redirecting to a path within the application and redirecting to a url - either within our application or external to it. In order to try out `redirect/2`, let's create a new route in `web/router.ex`. ```elixir defmodule HelloPhoenix.Router do use HelloPhoenix.Web, :router . . . scope "/", HelloPhoenix do . . . get "/", PageController, :index end # New route for redirects scope "/", HelloPhoenix do get "/redirect_test", PageController, :redirect_test, as: :redirect_test end . . . end ``` Then we'll change the `index` action to do nothing but redirect to our new route. ```elixir def index(conn, _params) do redirect conn, to: "/redirect_test" end ``` Finally, let's define in the same file the action we redirect to, which simply renders the text `Redirect!`. ```elixir def redirect_test(conn, _params) do text conn, "Redirect!" end ``` When we reload our [Welcome Page](http://localhost:4000), we see that we've been redirected to `/redirect_test` which has rendered the text `Redirect!`. It works! If we care to, we can open up our developer tools, click on the network tab, and visit our root route again. We see two main requests for this page - a get to `/` with a status of `302`, and a get to `/redirect_test` with a status of `200`. Notice that the redirect function takes `conn` as well as a string representing a relative path within our application. It can also take `conn` and a string representing a fully-qualified url. ```elixir def index(conn, _params) do redirect conn, external: "http://elixir-lang.org/" end ``` We can also make use of the path helpers we learned about in the [Routing Guide](http://www.phoenixframework.org/docs/routing). It's useful to `alias` the helpers in `web/router.ex` in order to shorten the expression. ```elixir defmodule HelloPhoenix.PageController do use HelloPhoenix.Web, :controller def index(conn, _params) do redirect conn, to: redirect_test_path(conn, :redirect_test) end end ``` Note that we can't use the url helper here because `redirect/2` using the atom `:to`, expects a path. For example, the following will fail. ```elixir def index(conn, _params) do redirect conn, to: redirect_test_url(conn, :redirect_test) end ``` If we want to use the url helper to pass a full url to `redirect/2`, we must use the atom `:external`. Note that the url does not have to be truly external to our application to use `:external`, as we see in this example. ```elixir def index(conn, _params) do redirect conn, external: redirect_test_url(conn, :redirect_test) end ```
{ "content_hash": "dbf67eff6e5cf730c68a3f936f82afed", "timestamp": "", "source": "github", "line_count": 538, "max_line_length": 469, "avg_line_length": 46.5910780669145, "alnum_prop": 0.7411633288119365, "repo_name": "phoenixframework-Brazil/phoenix_guides", "id": "6f0e0d7daeac14870b2b0425d787b620b4551d0d", "size": "25066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "D_controllers.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "271108" }, { "name": "HTML", "bytes": "26450" } ], "symlink_target": "" }
SELECT * FROM t1 ORDER BY log;
{ "content_hash": "bfe5d768aa1c54c6cc2af774745491df", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 30, "avg_line_length": 30, "alnum_prop": 0.7333333333333333, "repo_name": "bkiers/sqlite-parser", "id": "0cfe1420911bd5e355acf786d1cbb4b7546c2a9b", "size": "106", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/resources/insert2.test_12.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "20112" }, { "name": "Java", "bytes": "6273" }, { "name": "PLpgSQL", "bytes": "324108" } ], "symlink_target": "" }
<bill session="115" type="s" number="1325" updated="2017-09-11T03:06:32Z"> <state datetime="2017-06-08">REFERRED</state> <status> <introduced datetime="2017-06-08"/> </status> <introduced datetime="2017-06-08"/> <titles> <title type="short" as="introduced">Better Workforce for Veterans Act of 2017</title> <title type="short" as="introduced">Better Workforce for Veterans Act of 2017</title> <title type="official" as="introduced">A bill to amend title 38, United States Code, to improve the authorities of the Secretary of Veterans Affairs to hire, recruit, and train employees of the Department of Veterans Affairs, and for other purposes.</title> <title type="display">Better Workforce for Veterans Act of 2017</title> </titles> <sponsor bioguide_id="T000464"/> <cosponsors> <cosponsor bioguide_id="C000880" joined="2017-06-08"/> <cosponsor bioguide_id="H001076" joined="2017-06-08"/> <cosponsor bioguide_id="K000384" joined="2017-06-08"/> <cosponsor bioguide_id="M001170" joined="2017-06-08"/> <cosponsor bioguide_id="M000934" joined="2017-06-08"/> <cosponsor bioguide_id="N000032" joined="2017-07-10"/> </cosponsors> <actions> <action datetime="2017-06-08"> <text>Introduced in Senate</text> </action> <action datetime="2017-06-08" state="REFERRED"> <text>Read twice and referred to the Committee on Veterans' Affairs.</text> </action> <action datetime="2017-07-11"> <text>Committee on Veterans' Affairs. Hearings held.</text> </action> </actions> <committees> <committee subcommittee="" code="SSVA" name="Senate Veterans' Affairs" activity="Hearings, Referral"/> </committees> <relatedbills> <bill type="h" session="115" relation="unknown" number="3158"/> </relatedbills> <subjects> <term name="Armed forces and national security"/> </subjects> <amendments/> <committee-reports/> </bill>
{ "content_hash": "bf4dc3046837d7ccc634e06a64a85231", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 261, "avg_line_length": 43.88636363636363, "alnum_prop": 0.6887622993267737, "repo_name": "peter765/power-polls", "id": "a09b263583afb8750b9f3e47ee0d4252af5c7d26", "size": "1931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/bills/s/s1325/data.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "58567" }, { "name": "JavaScript", "bytes": "7370" }, { "name": "Python", "bytes": "22988" } ], "symlink_target": "" }
namespace invalidation { using INVALIDATION_STL_NAMESPACE::string; using ::ipc::invalidation::ProtocolVersion; using ::google::protobuf::Message; using ::google::protobuf::RepeatedPtrField; using ::google::protobuf::TextFormat; // Functor to compare various protocol messages. struct ProtoCompareLess { bool operator()(const ObjectIdP& object_id1, const ObjectIdP& object_id2) const { // If the sources differ, then the one with the smaller source is the // smaller object id. int source_diff = object_id1.source() - object_id2.source(); if (source_diff != 0) { return source_diff < 0; } // Otherwise, the one with the smaller name is the smaller object id. return object_id1.name().compare(object_id2.name()) < 0; } bool operator()(const InvalidationP& inv1, const InvalidationP& inv2) const { const ProtoCompareLess& compare_less_than = *this; // If the object ids differ, then the one with the smaller object id is the // smaller invalidation. if (compare_less_than(inv1.object_id(), inv2.object_id())) { return true; } if (compare_less_than(inv2.object_id(), inv1.object_id())) { return false; } // Otherwise, the object ids are the same, so we need to look at the // versions. // We define an unknown version to be less than a known version. int64 known_version_diff = inv1.is_known_version() - inv2.is_known_version(); if (known_version_diff != 0) { return known_version_diff < 0; } // Otherwise, they're both known both unknown, so the one with the smaller // version is the smaller invalidation. return inv1.version() < inv2.version(); } bool operator()(const RegistrationSubtree& reg_subtree1, const RegistrationSubtree& reg_subtree2) const { const RepeatedPtrField<ObjectIdP>& objects1 = reg_subtree1.registered_object(); const RepeatedPtrField<ObjectIdP>& objects2 = reg_subtree2.registered_object(); // If they have different numbers of objects, the one with fewer is smaller. if (objects1.size() != objects2.size()) { return objects1.size() < objects2.size(); } // Otherwise, compare the object ids in order. RepeatedPtrField<ObjectIdP>::const_iterator iter1, iter2; const ProtoCompareLess& compare_less_than = *this; for (iter1 = objects1.begin(), iter2 = objects2.begin(); iter1 != objects1.end(); ++iter1, ++iter2) { if (compare_less_than(*iter1, *iter2)) { return true; } if (compare_less_than(*iter2, *iter1)) { return false; } } // The registration subtrees are the same. return false; } }; // Other protocol message utilities. class ProtoHelpers { public: // Converts a value to a printable/readable string format. template<typename T> static string ToString(const T& value); // Initializes |reg| to be a (un) registration for object |oid|. static void InitRegistrationP(const ObjectIdP& oid, RegistrationP::OpType op_type, RegistrationP* reg); static void InitInitializeMessage( const ApplicationClientIdP& application_client_id, const string& nonce, InitializeMessage* init_msg); // Initializes |protocol_version| to the current protocol version. static void InitProtocolVersion(ProtocolVersion* protocol_version); // Initializes |client_version| to the current client version. static void InitClientVersion(const string& platform, const string& application_info, ClientVersion* client_version); // Initializes |config_version| to the current config version. static void InitConfigVersion(Version* config_version); // Initializes |rate_limit| with the given window interval and count of // messages. static void InitRateLimitP(int window_ms, int count, RateLimitP *rate_limit); private: static const int NUM_CHARS = 256; static char CHAR_OCTAL_STRINGS1[NUM_CHARS]; static char CHAR_OCTAL_STRINGS2[NUM_CHARS]; static char CHAR_OCTAL_STRINGS3[NUM_CHARS]; // Have the above arrays been initialized or not. static bool is_initialized; }; } // namespace invalidation #endif // GOOGLE_CACHEINVALIDATION_IMPL_PROTO_HELPERS_H_
{ "content_hash": "d045ad814d9cd04732be2d7a0969b69f", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 80, "avg_line_length": 35.91525423728814, "alnum_prop": 0.6880604058518169, "repo_name": "leighpauls/k2cro4", "id": "3858877fe395827ddb50255a42ada0c4aa9ff4e3", "size": "5403", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Senecio fortunatus Cuatrec. ### Remarks null
{ "content_hash": "e9b3e918d1d94036086355fe7657ca56", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.461538461538462, "alnum_prop": 0.7315436241610739, "repo_name": "mdoering/backbone", "id": "b8cfc2a23e01576181e8d56f08173e023b2eca9f", "size": "219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Dendrophorbium fortunatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections.Generic; namespace PullRequestsViewer.WebApp.Models { public class OrganisationModel { public string Name { get; set; } public IReadOnlyList<RepositoryModel> Repositories { get; set; } } }
{ "content_hash": "7f7111fb0299a86189276691ec9a2c0a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 72, "avg_line_length": 22.272727272727273, "alnum_prop": 0.6938775510204082, "repo_name": "joaoasrosa/pullrequests-viewer", "id": "9111b7c0411007e6cae4d4f14e4fc8715ea50728", "size": "247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PullRequestsViewer.WebApp/Models/OrganisationModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "85770" }, { "name": "CSS", "bytes": "56030" }, { "name": "CoffeeScript", "bytes": "8474" }, { "name": "HTML", "bytes": "136327" }, { "name": "JavaScript", "bytes": "106810" }, { "name": "PowerShell", "bytes": "24792" }, { "name": "Ruby", "bytes": "1030" }, { "name": "Shell", "bytes": "3967" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <!-- build:css styles/popup-vendor.css --> <!-- bower:css --> <!-- endbower --> <!-- endbuild --> <!-- build:css styles/main.css --> <link href="styles/main.css" rel="stylesheet"> <!-- endbuild --> </head> <body> <div class="page-header"> <h1><a href="https://hasjob.co/" target="_blank">Hasjob <small>The HasGeek Job Board</small></a></h1> </div> <div class="page-content stickie"> <div class="page-info">Loading...</div> </div> <div class="page-footer"> <span>Developed by <a href="https://github.com/HemantPawar" target="_blank">Hemant Pawar</a></span> </div> <!-- build:js scripts/popup-vendor.js --> <!-- bower:js --> <!-- endbower --> <!-- endbuild --> <!-- build:js scripts/popup.js --> <script src="scripts/popup.js"></script> <!-- endbuild --> </body> </html>
{ "content_hash": "a113c2bc2b6131f8b7b5ae3df1db1e16", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 107, "avg_line_length": 26.742857142857144, "alnum_prop": 0.5448717948717948, "repo_name": "HemantPawar/hasjob-extension", "id": "1b981d1ab788ddefa4b5100f4e83d97b1fd4ee07", "size": "936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/popup.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1367" }, { "name": "HTML", "bytes": "1689" }, { "name": "JavaScript", "bytes": "7096" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.murillo.sdp.impl; import org.murillo.sdp.SSRCAttribute; import org.murillo.abnf.Rule$ssrc_attr; import org.murillo.abnf.Rule$ssrc_id; import org.murillo.abnf.Rule$att_field; import org.murillo.abnf.Rule$att_value; /** * * @author Sergio */ class SSRCAttributeBuilder extends Builder { private SSRCAttribute ssrc; @Override public Object visit(Rule$ssrc_attr rule) { //New attr ssrc = new SSRCAttribute(); //Generate it super.visit(rule); //Return it return ssrc; } @Override public Object visit(Rule$ssrc_id rule) { //Get type Long ssrcId = Long.parseLong(rule.toString()); //Set type ssrc.setSSRC(ssrcId); //Return it return ssrcId; } @Override public Object visit(Rule$att_field rule) { //Get type String field = rule.toString(); //Set type ssrc.setAttrField(field); //Return it return field; } @Override public Object visit(Rule$att_value rule) { //Get type String value = rule.toString(); //Set type ssrc.setAttrValue(value); //Return it return value; } }
{ "content_hash": "794776e09c33796eacba67ce8f3b3e16", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 54, "avg_line_length": 22.166666666666668, "alnum_prop": 0.5992481203007519, "repo_name": "medooze/sdp", "id": "a0e23c0bc917d50f143f4cc30370109d3abead4e", "size": "1330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/murillo/sdp/impl/SSRCAttributeBuilder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "237" }, { "name": "Java", "bytes": "1116557" } ], "symlink_target": "" }
package com.siyeh.ig.performance; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.CommonQuickFixBundle; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.dataFlow.DfaUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ManualArrayCopyInspection extends BaseInspection implements CleanupLocalInspectionTool { @Override public boolean isEnabledByDefault() { return true; } @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("manual.array.copy.problem.descriptor"); } @Override public BaseInspectionVisitor buildVisitor() { return new ManualArrayCopyVisitor(); } @Override public InspectionGadgetsFix buildFix(Object... infos) { final Boolean decrement = (Boolean)infos[0]; return new ManualArrayCopyFix(decrement.booleanValue()); } private static class ManualArrayCopyFix extends InspectionGadgetsFix { private final boolean decrement; ManualArrayCopyFix(boolean decrement) { this.decrement = decrement; } @Override @NotNull public String getFamilyName() { return CommonQuickFixBundle.message("fix.replace.with.x", "System.arraycopy()"); } @Override public void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement forElement = descriptor.getPsiElement(); final PsiForStatement forStatement = (PsiForStatement)forElement.getParent(); CommentTracker commentTracker = new CommentTracker(); final String newExpression = buildSystemArrayCopyText(forStatement, commentTracker); if (newExpression == null) { return; } PsiIfStatement ifStatement = (PsiIfStatement)commentTracker.replaceAndRestoreComments(forStatement, newExpression); if (Boolean.TRUE.equals(DfaUtil.evaluateCondition(ifStatement.getCondition()))) { PsiStatement copyStatement = ControlFlowUtils.stripBraces(ifStatement.getThenBranch()); assert copyStatement != null; new CommentTracker().replaceAndRestoreComments(ifStatement, copyStatement); } } private @Nullable @NonNls String buildSystemArrayCopyText(PsiForStatement forStatement, CommentTracker commentTracker) { final PsiExpression condition = forStatement.getCondition(); final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)PsiUtil.skipParenthesizedExprDown(condition); if (binaryExpression == null) { return null; } final IElementType tokenType = binaryExpression.getOperationTokenType(); final PsiExpression limit; if (decrement ^ JavaTokenType.LT.equals(tokenType) || JavaTokenType.LE.equals(tokenType)) { limit = binaryExpression.getROperand(); } else { limit = binaryExpression.getLOperand(); } if (limit == null) { return null; } final PsiStatement initialization = forStatement.getInitialization(); if (initialization == null) { return null; } if (!(initialization instanceof PsiDeclarationStatement)) { return null; } final PsiDeclarationStatement declaration = (PsiDeclarationStatement)initialization; final PsiElement[] declaredElements = declaration.getDeclaredElements(); if (declaredElements.length != 1) { return null; } final PsiElement declaredElement = declaredElements[0]; if (!(declaredElement instanceof PsiLocalVariable)) { return null; } final PsiLocalVariable variable = (PsiLocalVariable)declaredElement; final String lengthText; final PsiExpression initializer = variable.getInitializer(); if (decrement) { lengthText = buildLengthText(initializer, limit, JavaTokenType.LE.equals(tokenType) || JavaTokenType.GE.equals(tokenType), commentTracker); } else { lengthText = buildLengthText(limit, initializer, JavaTokenType.LE.equals(tokenType) || JavaTokenType.GE.equals(tokenType), commentTracker); } if (lengthText == null) { return null; } final PsiArrayAccessExpression lhs = getLhsArrayAccessExpression(forStatement); if (lhs == null) { return null; } final PsiExpression lArray = lhs.getArrayExpression(); final String toArrayText = commentTracker.text(lArray); final PsiArrayAccessExpression rhs = getRhsArrayAccessExpression(forStatement); if (rhs == null) { return null; } final PsiExpression rArray = rhs.getArrayExpression(); final String fromArrayText = commentTracker.text(rArray); final PsiExpression rhsIndexExpression = rhs.getIndexExpression(); final PsiExpression strippedRhsIndexExpression = PsiUtil.skipParenthesizedExprDown(rhsIndexExpression); final PsiExpression limitExpression; if (decrement) { limitExpression = limit; } else { limitExpression = initializer; } final String fromOffsetText = buildOffsetText(strippedRhsIndexExpression, variable, limitExpression, decrement && (JavaTokenType.LT.equals(tokenType) || JavaTokenType.GT.equals(tokenType)), commentTracker); final PsiExpression lhsIndexExpression = lhs.getIndexExpression(); final PsiExpression strippedLhsIndexExpression = PsiUtil.skipParenthesizedExprDown(lhsIndexExpression); final String toOffsetText = buildOffsetText(strippedLhsIndexExpression, variable, limitExpression, decrement && (JavaTokenType.LT.equals(tokenType) || JavaTokenType.GT.equals(tokenType)), commentTracker); return "if(" + lengthText + ">=0)" + "System.arraycopy(" + fromArrayText + "," + fromOffsetText + "," + toArrayText + "," + toOffsetText + "," + lengthText + ");"; } @Nullable private static PsiArrayAccessExpression getLhsArrayAccessExpression(PsiForStatement forStatement) { PsiStatement body = forStatement.getBody(); while (body instanceof PsiBlockStatement) { final PsiBlockStatement blockStatement = (PsiBlockStatement)body; final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); final PsiStatement[] statements = codeBlock.getStatements(); if (statements.length == 2) { body = statements[1]; } else if (statements.length == 1) { body = statements[0]; } else { return null; } } if (!(body instanceof PsiExpressionStatement)) { return null; } final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)body; final PsiExpression expression = expressionStatement.getExpression(); if (!(expression instanceof PsiAssignmentExpression)) { return null; } final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression; final PsiExpression lhs = assignmentExpression.getLExpression(); final PsiExpression deparenthesizedExpression = PsiUtil.skipParenthesizedExprDown(lhs); if (!(deparenthesizedExpression instanceof PsiArrayAccessExpression)) { return null; } return (PsiArrayAccessExpression)deparenthesizedExpression; } @Nullable private static PsiArrayAccessExpression getRhsArrayAccessExpression(PsiForStatement forStatement) { PsiStatement body = forStatement.getBody(); while (body instanceof PsiBlockStatement) { final PsiBlockStatement blockStatement = (PsiBlockStatement)body; final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); final PsiStatement[] statements = codeBlock.getStatements(); if (statements.length == 1 || statements.length == 2) { body = statements[0]; } else { return null; } } final PsiExpression arrayAccessExpression; if (body instanceof PsiDeclarationStatement) { final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)body; final PsiElement[] declaredElements = declarationStatement.getDeclaredElements(); if (declaredElements.length != 1) { return null; } final PsiElement declaredElement = declaredElements[0]; if (!(declaredElement instanceof PsiVariable)) { return null; } final PsiVariable variable = (PsiVariable)declaredElement; arrayAccessExpression = variable.getInitializer(); } else if (body instanceof PsiExpressionStatement) { final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)body; final PsiExpression expression = expressionStatement.getExpression(); if (!(expression instanceof PsiAssignmentExpression)) { return null; } final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression; arrayAccessExpression = assignmentExpression.getRExpression(); } else { return null; } final PsiExpression unparenthesizedExpression = PsiUtil.skipParenthesizedExprDown(arrayAccessExpression); if (!(unparenthesizedExpression instanceof PsiArrayAccessExpression)) { return null; } return (PsiArrayAccessExpression)unparenthesizedExpression; } @NonNls @Nullable private static String buildLengthText(PsiExpression max, PsiExpression min, boolean plusOne, CommentTracker commentTracker) { max = PsiUtil.skipParenthesizedExprDown(max); if (max == null) { return null; } min = PsiUtil.skipParenthesizedExprDown(min); if (min == null) { return buildExpressionText(max, plusOne, commentTracker); } final Object minConstant = ExpressionUtils.computeConstantExpression(min); if (minConstant instanceof Number) { final Number minNumber = (Number)minConstant; final int minValue = plusOne ? minNumber.intValue() - 1 : minNumber.intValue(); if (minValue == 0) { return buildExpressionText(max, false, commentTracker); } if (max instanceof PsiLiteralExpression) { final Object maxConstant = ExpressionUtils.computeConstantExpression(max); if (maxConstant instanceof Number) { final Number number = (Number)maxConstant; return String.valueOf(number.intValue() - minValue); } } final String maxText = buildExpressionText(max, false, commentTracker); if (minValue > 0) { return maxText + '-' + minValue; } else { return maxText + '+' + -minValue; } } // - 1 because of the increment inside the com.siyeh.ig.psiutils.CommentTracker.text(com.intellij.psi.PsiExpression, int) final String minText = commentTracker.text(min, ParenthesesUtils.ADDITIVE_PRECEDENCE - 1); final String maxText = buildExpressionText(max, plusOne, commentTracker); return maxText + '-' + minText; } private static String buildExpressionText(PsiExpression expression, boolean plusOne, CommentTracker commentTracker) { return plusOne ? JavaPsiMathUtil.add(expression, 1, commentTracker) : commentTracker.text(expression, ParenthesesUtils.ADDITIVE_PRECEDENCE); } @NonNls @Nullable private static String buildOffsetText(PsiExpression expression, PsiLocalVariable variable, PsiExpression limitExpression, boolean plusOne, CommentTracker commentTracker) { if (expression == null) { return null; } final String expressionText = commentTracker.text(expression); final String variableName = variable.getName(); if (expressionText.equals(variableName)) { final PsiExpression initialValue = PsiUtil.skipParenthesizedExprDown(limitExpression); if (initialValue == null) { return null; } return buildExpressionText(initialValue, plusOne, commentTracker); } else if (expression instanceof PsiBinaryExpression) { final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; final PsiExpression lhs = binaryExpression.getLOperand(); final PsiExpression rhs = binaryExpression.getROperand(); final String rhsText = buildOffsetText(rhs, variable, limitExpression, plusOne, commentTracker); final PsiJavaToken sign = binaryExpression.getOperationSign(); final IElementType tokenType = sign.getTokenType(); if (ExpressionUtils.isZero(lhs)) { return tokenType.equals(JavaTokenType.MINUS) ? '-' + rhsText : rhsText; } if (plusOne && tokenType.equals(JavaTokenType.MINUS) && ExpressionUtils.isOne(rhs)) { return buildOffsetText(lhs, variable, limitExpression, false, commentTracker); } final String lhsText = buildOffsetText(lhs, variable, limitExpression, plusOne, commentTracker); if (ExpressionUtils.isZero(rhs)) { return lhsText; } return collapseConstant(lhsText + sign.getText() + rhsText, variable); } return collapseConstant(commentTracker.text(expression), variable); } private static String collapseConstant(@NonNls String expressionText, PsiElement context) { final Project project = context.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory factory = psiFacade.getElementFactory(); final PsiExpression fromOffsetExpression = factory.createExpressionFromText(expressionText, context); final Object fromOffsetConstant = ExpressionUtils.computeConstantExpression(fromOffsetExpression); if (fromOffsetConstant != null) { return fromOffsetConstant.toString(); } else { return expressionText; } } } private static class ManualArrayCopyVisitor extends BaseInspectionVisitor { @Override public void visitForStatement(@NotNull PsiForStatement statement) { super.visitForStatement(statement); final CountingLoop countingLoop = CountingLoop.from(statement); if (countingLoop == null) { return; } final PsiStatement body = statement.getBody(); if (!bodyIsArrayCopy(body, countingLoop.getCounter())) { return; } registerStatementError(statement, Boolean.valueOf(countingLoop.isDescending())); } private static boolean bodyIsArrayCopy(PsiStatement body, PsiVariable variable) { if (body instanceof PsiExpressionStatement) { final PsiExpressionStatement exp = (PsiExpressionStatement)body; final PsiExpression expression = exp.getExpression(); return expressionIsArrayCopy(expression, variable); } else if (body instanceof PsiBlockStatement) { final PsiBlockStatement blockStatement = (PsiBlockStatement)body; final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); final PsiStatement[] statements = codeBlock.getStatements(); if (statements.length == 1) { return bodyIsArrayCopy(statements[0], variable); } else if (statements.length == 2) { final PsiStatement statement = statements[0]; if (!(statement instanceof PsiDeclarationStatement)) { return false; } final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)statement; final PsiElement[] declaredElements = declarationStatement.getDeclaredElements(); if (declaredElements.length != 1) { return false; } final PsiElement declaredElement = declaredElements[0]; if (!(declaredElement instanceof PsiVariable)) { return false; } final PsiVariable localVariable = (PsiVariable)declaredElement; final PsiExpression initializer = localVariable.getInitializer(); if (!ExpressionUtils.isOffsetArrayAccess(initializer, variable)) { return false; } return bodyIsArrayCopy(statements[1], variable); } } return false; } private static boolean expressionIsArrayCopy(@Nullable PsiExpression expression, @NotNull PsiVariable variable) { final PsiExpression strippedExpression = PsiUtil.skipParenthesizedExprDown(expression); if (strippedExpression == null) { return false; } if (!(strippedExpression instanceof PsiAssignmentExpression)) { return false; } final PsiAssignmentExpression assignment = (PsiAssignmentExpression)strippedExpression; final IElementType tokenType = assignment.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.EQ)) { return false; } final PsiExpression lhs = assignment.getLExpression(); if (SideEffectChecker.mayHaveSideEffects(lhs)) { return false; } if (!ExpressionUtils.isOffsetArrayAccess(lhs, variable)) { return false; } final PsiExpression rhs = assignment.getRExpression(); if (rhs == null) { return false; } if (SideEffectChecker.mayHaveSideEffects(rhs)) { return false; } if (!areExpressionsCopyable(lhs, rhs)) { return false; } final PsiType type = lhs.getType(); if (type instanceof PsiPrimitiveType) { final PsiExpression strippedLhs = PsiUtil.skipParenthesizedExprDown(lhs); final PsiExpression strippedRhs = PsiUtil.skipParenthesizedExprDown(rhs); if (!areExpressionsCopyable(strippedLhs, strippedRhs)) { return false; } } if (!ExpressionUtils.isOffsetArrayAccess(rhs, variable)) { return false; } return !isSameSourceAndDestination(lhs, rhs); } private static boolean isSameSourceAndDestination(PsiExpression lhs, PsiExpression rhs) { lhs = PsiUtil.skipParenthesizedExprDown(lhs); rhs = PsiUtil.skipParenthesizedExprDown(rhs); assert lhs != null && rhs != null; /// checked in ExpressionUtils.isOffsetArrayAccess() PsiArrayAccessExpression left = (PsiArrayAccessExpression)lhs; PsiArrayAccessExpression right = (PsiArrayAccessExpression)rhs; return EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(left.getArrayExpression(), right.getArrayExpression()); } private static boolean areExpressionsCopyable(@Nullable PsiExpression lhs, @Nullable PsiExpression rhs) { if (lhs == null || rhs == null) { return false; } final PsiType lhsType = lhs.getType(); if (lhsType == null) { return false; } final PsiType rhsType = rhs.getType(); if (rhsType == null) { return false; } if (lhsType instanceof PsiPrimitiveType) { if (!lhsType.equals(rhsType)) { return false; } } else { if (!lhsType.isAssignableFrom(rhsType) || rhsType instanceof PsiPrimitiveType) { return false; } } return true; } } }
{ "content_hash": "faf99f5520c4aaad48944827c7b3182e", "timestamp": "", "source": "github", "line_count": 469, "max_line_length": 147, "avg_line_length": 42.22814498933902, "alnum_prop": 0.6849785407725322, "repo_name": "dahlstrom-g/intellij-community", "id": "5b21feb56974b83b3d53afa6cc4d1a678325b5c1", "size": "20419", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/ManualArrayCopyInspection.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class Adjust_dialog : public Javelin::Dialog { public : Adjust_dialog() ; void Set_position( POINT& point ) ; void Set_target(HWND target); protected : virtual INT_PTR Dialog_proc( UINT message, WPARAM wparam, LPARAM lparam ) ; void On_initdialog() ; void On_command( WPARAM wparam ) ; void On_cancel() ; void On_adjust_button( WPARAM wparam ) ; void Set_icon( int control_id, int icon_id ) ; private : WINDOWPLACEMENT Last_window_placement ; POINT Point ; HICON Icon03 ; HICON Icon06 ; HWND Target; // ƒRƒs[‹ÖŽ~ˆ— Adjust_dialog( const Adjust_dialog& ) ; Adjust_dialog& operator =( const Adjust_dialog& ) ; } ; // [[[[[ End of this header ]]]]]
{ "content_hash": "5a8d4c245f84031baab157cc9962e107", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 76, "avg_line_length": 21.677419354838708, "alnum_prop": 0.6711309523809523, "repo_name": "sanadan/Window_adjuster", "id": "9c7c401c84c6a26077b3e8ad4425cae29cf9458c", "size": "873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Window_adjuster/Adjust_dialog.hpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "5586" }, { "name": "C++", "bytes": "106139" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>shuffled property - ShuffleLinkedList class - torrent_util library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the shuffled property from the ShuffleLinkedList class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="torrent_util/torrent_util-library.html">torrent_util</a></li> <li><a href="torrent_util/ShuffleLinkedList-class.html">ShuffleLinkedList</a></li> <li class="self-crumb">shuffled</li> </ol> <div class="self-name">shuffled</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="torrent_util/torrent_util-library.html">torrent_util</a></li> <li><a href="torrent_util/ShuffleLinkedList-class.html">ShuffleLinkedList</a></li> <li class="self-crumb">shuffled</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">property</div> shuffled </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">hetimatorrent</a></h5> <h5><a href="torrent_util/torrent_util-library.html">torrent_util</a></h5> <h5><a href="torrent_util/ShuffleLinkedList-class.html">ShuffleLinkedList</a></h5> <ol> <li class="section-title"><a href="torrent_util/ShuffleLinkedList-class.html#instance-properties">Properties</a></li> <li><a href="torrent_util/ShuffleLinkedList/iterator.html">iterator</a> </li> <li><a href="torrent_util/ShuffleLinkedList/length.html">length</a> </li> <li><a href="torrent_util/ShuffleLinkedList/max.html">max</a> </li> <li><a href="torrent_util/ShuffleLinkedList/rawsequential.html">rawsequential</a> </li> <li><a href="torrent_util/ShuffleLinkedList/rawshuffled.html">rawshuffled</a> </li> <li><a href="torrent_util/ShuffleLinkedList/sequential.html">sequential</a> </li> <li><a href="torrent_util/ShuffleLinkedList/shuffled.html">shuffled</a> </li> <li class="section-title"><a href="torrent_util/ShuffleLinkedList-class.html#constructors">Constructors</a></li> <li><a href="torrent_util/ShuffleLinkedList/ShuffleLinkedList.html">ShuffleLinkedList</a></li> <li class="section-title"><a href="torrent_util/ShuffleLinkedList-class.html#methods">Methods</a></li> <li><a href="torrent_util/ShuffleLinkedList/addHead.html">addHead</a> </li> <li><a href="torrent_util/ShuffleLinkedList/addLast.html">addLast</a> </li> <li><a href="torrent_util/ShuffleLinkedList/clearAll.html">clearAll</a> </li> <li><a href="torrent_util/ShuffleLinkedList/getSequential.html">getSequential</a> </li> <li><a href="torrent_util/ShuffleLinkedList/getShuffled.html">getShuffled</a> </li> <li><a href="torrent_util/ShuffleLinkedList/getWithFilter.html">getWithFilter</a> </li> <li><a href="torrent_util/ShuffleLinkedList/removeHead.html">removeHead</a> </li> <li><a href="torrent_util/ShuffleLinkedList/removeWithFilter.html">removeWithFilter</a> </li> <li><a href="torrent_util/ShuffleLinkedList/shuffle.html">shuffle</a> </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">List&lt;X&gt;</span> <span class="name ">shuffled</span> <div class="readable-writable"> read-only </div> </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> hetimatorrent 0.0.1 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
{ "content_hash": "99c7e298725b19eb439f96ef2f2234a6", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 143, "avg_line_length": 37.22222222222222, "alnum_prop": 0.6092868988391377, "repo_name": "kyorohiro/dart_hetimatorrent", "id": "9efa99fbf2c7b64d2b0c444600a9dedd4690ccff", "size": "6030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/torrent_util/ShuffleLinkedList/shuffled.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "165425" }, { "name": "Dart", "bytes": "453550" }, { "name": "HTML", "bytes": "19043" }, { "name": "JavaScript", "bytes": "2312" } ], "symlink_target": "" }
<?php use Mockery as m; class FilesystemCleanerTest extends PHPUnit_Framework_TestCase { public function tearDown() { m::close(); } public function setUp() { $this->environment = m::mock('Basset\Environment'); $this->manifest = m::mock('Basset\Manifest\Manifest'); $this->files = m::mock('Illuminate\Filesystem\Filesystem'); $this->cleaner = new Basset\Builder\FilesystemCleaner($this->environment, $this->manifest, $this->files, 'path/to/builds'); $this->manifest->shouldReceive('save')->atLeast()->once(); } public function testForgettingCollectionFromManifestThatNoLongerExistsOnEnvironment() { $this->environment->shouldReceive('offsetExists')->once()->with('foo')->andReturn(false); $this->manifest->shouldReceive('get')->once()->with('foo')->andReturn($entry = m::mock('Basset\Manifest\Entry')); $this->manifest->shouldReceive('forget')->once()->with('foo'); $entry->shouldReceive('hasProductionFingerprints')->once()->andReturn(false); $this->files->shouldReceive('glob')->with('path/to/builds/foo-*.*')->andReturn(array('path/to/builds/foo-123.css')); $this->files->shouldReceive('delete')->with('path/to/builds/foo-123.css'); $entry->shouldReceive('resetProductionFingerprints')->once(); $entry->shouldReceive('hasDevelopmentAssets')->once()->andReturn(false); $this->files->shouldReceive('deleteDirectory')->once()->with('path/to/builds/foo'); $entry->shouldReceive('resetDevelopmentAssets')->once(); $this->cleaner->clean('foo'); } public function testCleaningOfManifestFilesOnFilesystem() { $this->manifest->shouldReceive('get')->once()->with('foo')->andReturn($entry = m::mock('Basset\Manifest\Entry')); $this->environment->shouldReceive('offsetExists')->times(3)->with('foo')->andReturn(true); $this->environment->shouldReceive('offsetGet')->once()->with('foo')->andReturn($collection = m::mock('Basset\Collection')); $collection->shouldReceive('getIdentifier')->twice()->andReturn('foo'); $entry->shouldReceive('getProductionFingerprints')->once()->andReturn(array( 'foo-37b51d194a7513e45b56f6524f2d51f2.css', 'bar-acbd18db4cc2f85cedef654fccc4a4d8.js' )); $this->files->shouldReceive('glob')->once()->with('path/to/builds/foo-*.css')->andReturn(array( 'path/to/builds/foo-37b51d194a7513e45b56f6524f2d51f2.css', 'path/to/builds/foo-asfjkb8912h498hacn8casc8h8942102.css' )); $this->files->shouldReceive('delete')->once()->with('path/to/builds/foo-asfjkb8912h498hacn8casc8h8942102.css')->andReturn(true); $this->files->shouldReceive('glob')->once()->with('path/to/builds/bar-*.js')->andReturn(array()); $entry->shouldReceive('getDevelopmentAssets')->once()->andReturn(array( 'stylesheets' => array('bar/baz-37b51d194a7513e45b56f6524f2d51f2.css', 'bar/qux-acbd18db4cc2f85cedef654fccc4a4d8.css'), 'javascripts' => array() )); $this->files->shouldReceive('glob')->once()->with('path/to/builds/foo/bar/baz-*.css')->andReturn(array('path/to/builds/foo/bar/baz-37b51d194a7513e45b56f6524f2d51f2.css')); $this->files->shouldReceive('glob')->once()->with('path/to/builds/foo/bar/qux-*.css')->andReturn(array()); $entry->shouldReceive('hasProductionFingerprints')->once()->andReturn(true); $entry->shouldReceive('hasDevelopmentAssets')->once()->andReturn(true); $this->cleaner->clean('foo'); } }
{ "content_hash": "9b307069fb82a1c7cfe2caa0dc9bc338", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 179, "avg_line_length": 45.1625, "alnum_prop": 0.6548574591752007, "repo_name": "coreywagehoft/laravel-4-base", "id": "5deece93739028ecb211a5fa0d57a16e0ed82e74", "size": "3613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/jasonlewis/basset/tests/Basset/Builder/FilesystemCleanerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "417936" }, { "name": "JavaScript", "bytes": "1073042" }, { "name": "PHP", "bytes": "500131" }, { "name": "Perl", "bytes": "2658" } ], "symlink_target": "" }
package org.apache.tez.runtime.library.common.task.impl; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.serializer.Deserializer; import org.apache.hadoop.io.serializer.SerializationFactory; import org.apache.hadoop.util.Progressable; import org.apache.tez.runtime.library.common.sort.impl.TezRawKeyValueIterator; /** * Iterates values while keys match in sorted input. * * Usage: Call moveToNext to move to the next k, v pair. This returns true if another exists, * followed by getKey() and getValues() to get the current key and list of values. * */ public class ValuesIterator<KEY,VALUE> implements Iterator<VALUE> { protected TezRawKeyValueIterator in; //input iterator private KEY key; // current key private KEY nextKey; private VALUE value; // current value private boolean hasNext; // more w/ this key private boolean more; // more in file private RawComparator<KEY> comparator; protected Progressable reporter; private Deserializer<KEY> keyDeserializer; private Deserializer<VALUE> valDeserializer; private DataInputBuffer keyIn = new DataInputBuffer(); private DataInputBuffer valueIn = new DataInputBuffer(); public ValuesIterator (TezRawKeyValueIterator in, RawComparator<KEY> comparator, Class<KEY> keyClass, Class<VALUE> valClass, Configuration conf, Progressable reporter) throws IOException { this.in = in; this.comparator = comparator; this.reporter = reporter; SerializationFactory serializationFactory = new SerializationFactory(conf); this.keyDeserializer = serializationFactory.getDeserializer(keyClass); this.keyDeserializer.open(keyIn); this.valDeserializer = serializationFactory.getDeserializer(valClass); this.valDeserializer.open(this.valueIn); readNextKey(); key = nextKey; nextKey = null; // force new instance creation hasNext = more; } TezRawKeyValueIterator getRawIterator() { return in; } /// Iterator methods public boolean hasNext() { return hasNext; } private int ctr = 0; public VALUE next() { if (!hasNext) { throw new NoSuchElementException("iterate past last value"); } try { readNextValue(); readNextKey(); } catch (IOException ie) { throw new RuntimeException("problem advancing post rec#"+ctr, ie); } reporter.progress(); return value; } public void remove() { throw new RuntimeException("not implemented"); } /// Auxiliary methods /** Start processing next unique key. */ public void nextKey() throws IOException { // read until we find a new key while (hasNext) { readNextKey(); } ++ctr; // move the next key to the current one KEY tmpKey = key; key = nextKey; nextKey = tmpKey; hasNext = more; } /** True iff more keys remain. */ public boolean more() { return more; } /** The current key. */ public KEY getKey() { return key; } /** * read the next key */ private void readNextKey() throws IOException { more = in.next(); if (more) { DataInputBuffer nextKeyBytes = in.getKey(); keyIn.reset(nextKeyBytes.getData(), nextKeyBytes.getPosition(), nextKeyBytes.getLength()); nextKey = keyDeserializer.deserialize(nextKey); hasNext = key != null && (comparator.compare(key, nextKey) == 0); } else { hasNext = false; } } /** * Read the next value * @throws IOException */ private void readNextValue() throws IOException { DataInputBuffer nextValueBytes = in.getValue(); valueIn.reset(nextValueBytes.getData(), nextValueBytes.getPosition(), nextValueBytes.getLength()); value = valDeserializer.deserialize(value); } }
{ "content_hash": "cfccaf239ed2355f97d5cabb193cb803", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 102, "avg_line_length": 30.67669172932331, "alnum_prop": 0.6754901960784314, "repo_name": "sungsoo/tez-0.4.0", "id": "88cb7506306afccf467a2e683fed187c1e8d1b87", "size": "4870", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/task/impl/ValuesIterator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3887732" }, { "name": "Python", "bytes": "3444" }, { "name": "TeX", "bytes": "19322" } ], "symlink_target": "" }
layout: page title: All about Luke. excerpt: "All about Luke." modified: 2014-08-08T19:44:38.564948-04:00 image: feature: photo-1454540723233-f0b9ff08b132.jpg credit: unsplash creditlink: https://hd.unsplash.com --- Luke is a passionate and highly focused individual, dedicated to learning about technology and its implementation primarily with the Windows stack. Coming from an operations background centring heavily on infrastructure management, his current role is focused on bringing automation through agile development methods being able to assess project requirements and break down the required stories and tasks working from concept and design bringing projects through to the implementation and delivery. With the experience of delivering code to thousands of production nodes, he understands the requirements that modern software developments need, like test driven development and modular programming along with keeping to DRY principles. He is enthusiastic to learn about the development world and exploring different methodologies like Scrum and XP. He has exposure to a number of programming and scripting languages primarily Powershell, and C# but also including Python, C++ and Javascript. ## Experience # G-Research (Oct 2015 - Present) **Automation Engineering** *KeySkills* - Windows Scripting (PowerShell) - Process Automation - Release Pipeline - Continuous Delivery - Infrastructure as code - Package Management Architecture # Attenda (Oct 2011 - Oct 2015) **Infrastructure Engineering** *KeySkills* - Windows Infrastructure Management & Troubleshooting - Application Hosting - Fault Analysis - Network Configuration & Troubleshooting - Automation - ITIL # EasyNet (April 2010 - October 2011) **Data Engineering** *KeySkills* - Network Troubleshooting - Escalation Management - Customer Care
{ "content_hash": "8464e8db17b83c1b62ed8d9ee487a4ad", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 499, "avg_line_length": 33.527272727272724, "alnum_prop": 0.7998915401301518, "repo_name": "lukemgriffith/JekyllBlog_Config", "id": "a44031189dd34466a50ddb4aa4002b300444347b", "size": "1848", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "50339" }, { "name": "HTML", "bytes": "18928" }, { "name": "JavaScript", "bytes": "78233" }, { "name": "PowerShell", "bytes": "1075" }, { "name": "Ruby", "bytes": "1297" } ], "symlink_target": "" }
"""The Vilfo Router integration.""" from datetime import timedelta import logging from vilfo import Client as VilfoClient from vilfo.exceptions import VilfoException from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.util import Throttle from .const import ATTR_BOOT_TIME, ATTR_LOAD, DOMAIN, ROUTER_DEFAULT_HOST PLATFORMS = [Platform.SENSOR] DEFAULT_SCAN_INTERVAL = timedelta(seconds=30) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Vilfo Router from a config entry.""" host = entry.data[CONF_HOST] access_token = entry.data[CONF_ACCESS_TOKEN] vilfo_router = VilfoRouterData(hass, host, access_token) await vilfo_router.async_update() if not vilfo_router.available: raise ConfigEntryNotReady hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = vilfo_router hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok class VilfoRouterData: """Define an object to hold sensor data.""" def __init__(self, hass, host, access_token): """Initialize.""" self._vilfo = VilfoClient(host, access_token) self.hass = hass self.host = host self.available = False self.firmware_version = None self.mac_address = self._vilfo.mac self.data = {} self._unavailable_logged = False @property def unique_id(self): """Get the unique_id for the Vilfo Router.""" if self.mac_address: return self.mac_address if self.host == ROUTER_DEFAULT_HOST: return self.host return self.host def _fetch_data(self): board_information = self._vilfo.get_board_information() load = self._vilfo.get_load() return { "board_information": board_information, "load": load, } @Throttle(DEFAULT_SCAN_INTERVAL) async def async_update(self): """Update data using calls to VilfoClient library.""" try: data = await self.hass.async_add_executor_job(self._fetch_data) self.firmware_version = data["board_information"]["version"] self.data[ATTR_BOOT_TIME] = data["board_information"]["bootTime"] self.data[ATTR_LOAD] = data["load"] self.available = True except VilfoException as error: if not self._unavailable_logged: _LOGGER.error( "Could not fetch data from %s, error: %s", self.host, error ) self._unavailable_logged = True self.available = False return if self.available and self._unavailable_logged: _LOGGER.info("Vilfo Router %s is available again", self.host) self._unavailable_logged = False
{ "content_hash": "e21f675c9cc12058f2e30bde7be24907", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 82, "avg_line_length": 30.935185185185187, "alnum_prop": 0.6477102663873092, "repo_name": "GenericStudent/home-assistant", "id": "ac3b8b87f3ff78f9dfe1bd4bb7e702fcc5799c72", "size": "3341", "binary": false, "copies": "4", "ref": "refs/heads/dev", "path": "homeassistant/components/vilfo/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3070" }, { "name": "Python", "bytes": "44491729" }, { "name": "Shell", "bytes": "5092" } ], "symlink_target": "" }
<?php namespace Blogger\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Blogger\BlogBundle\Entity\Comment; use Blogger\BlogBundle\Form\CommentType; class CommentController extends Controller { public function newAction($blog_id) { $blog = $this->getBlog($blog_id); $comment = new Comment(); $comment->setBlog($blog); $form = $this->createForm(new CommentType(), $comment); return $this->render('BloggerBlogBundle:Comment:form.html.twig', array( 'comment' => $comment, 'form' => $form->createView() )); } public function createAction($blog_id) { $blog = $this->getBlog($blog_id); $comment = new Comment(); $comment->setBlog($blog); $request = $this->getRequest(); $form = $this->createForm(new CommentType(), $comment); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($comment); $em->flush(); return $this->redirect($this->generateUrl('BloggerBlogBundle_blog_show', array( 'id' => $comment->getBlog()->getId(), 'slug' => $comment->getBlog()->getSlug())) . '#comment-' . $comment->getId() ); } return $this->render('BloggerBlogBundle:create.html.twig', array( 'comment' => $comment, 'form' => $form->createView() )); } protected function getBlog($blog_id) { $em = $this->getDoctrine()->getEntityManager(); $blog = $em->getRepository('BloggerBlogBundle:Blog')->find($blog_id); if (!$blog) { throw $this->createNotFoundException("Unable to find blog post"); } return $blog; } }
{ "content_hash": "f745d7cc001bc8657afc3c99c659b4cc", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 88, "avg_line_length": 23.742857142857144, "alnum_prop": 0.6269554753309265, "repo_name": "carbamide/symblog.dev", "id": "d54bc3e0f9752ec7beaefc2ac4b2010f974c66bb", "size": "1662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Blogger/BlogBundle/Controller/CommentController.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "49501" } ], "symlink_target": "" }
var mldb = require('mldb') var unittest = require('mldb/unittest') var functionConfig = { type: 'sql.expression', params: { expression: 'horizontal_sum(input) AS result', prepared: true, raw: true, autoInput: true } }; var fn = mldb.put('/v1/functions/score_one', functionConfig); unittest.assertEqual(fn.responseCode, 201); mldb.log(fn); var res = mldb.get('/v1/functions/score_one/batch', { input: [[1,2,3],[4,5],[6],[]] }); mldb.log(res); var expected = [ 6, 9, 6, 0 ]; unittest.assertEqual(res.json, expected); var functionConfig = { type: 'sql.query', params: { query: 'select horizontal_sum(value) as value, column FROM row_dataset($input)', output: 'NAMED_COLUMNS' } }; var fn = mldb.put('/v1/functions/score_many', functionConfig); mldb.log(fn); unittest.assertEqual(fn.responseCode, 201); var functionConfig2 = { type: 'sql.expression', params: { expression: 'score_many({input: rowsToScore})[output] AS *', prepared: true } }; var fn2 = mldb.put('/v1/functions/scorer', functionConfig2); mldb.log(fn2); unittest.assertEqual(fn2.responseCode, 201); var input = { rowsToScore: [ { x: 1, y: 2}, {a: 2, b: 3, c: 4} ] }; var res = mldb.get('/v1/functions/scorer/application', { input: input, outputFormat: 'json' }); var expected = [ 3, 9 ]; unittest.assertEqual(res.json, expected); mldb.log(res); var functionSource = ` var fnconfig = { type: "sql.expression", params: { expression: "horizontal_sum({*}) AS result", prepared: true } }; var predictfn = mldb.createFunction(fnconfig); function handleRequest(relpath, verb, resource, params, payload, contentType, contentLength, headers) { if (verb == "GET" && relpath == "/predict") { mldb.log(params); if (params[0][0] != "rowsToScore") throw "Unknown parameter name " + params[0][0]; var allParams = JSON.parse(params[0][1]); for (p in allParams) { allParams[p] = predictfn.callJson(allParams[p])['result']; } return allParams; } throw "Unknown route " + verb + " " + relpath; } plugin.setRequestHandler(handleRequest); `; var pluginConfig = { type: 'javascript', params: { source: { main: functionSource } } }; var pl = mldb.put('/v1/plugins/myapi', pluginConfig); mldb.log(pl); var res = mldb.get('/v1/plugins/myapi/routes/predict', input); mldb.log(res); unittest.assertEqual(res.json, expected); "success"
{ "content_hash": "0698b6bd368b33ba5a1f3786e462292f", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 92, "avg_line_length": 22.47008547008547, "alnum_prop": 0.5983263598326359, "repo_name": "mldbai/mldb", "id": "6e21f9c0134b96f8f9ed0db086c65f9535d99501", "size": "2709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testing/MLDB-2022-multiple-prediction-example.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "643" }, { "name": "C", "bytes": "11754639" }, { "name": "C++", "bytes": "14072572" }, { "name": "CMake", "bytes": "2737" }, { "name": "CSS", "bytes": "17037" }, { "name": "Dockerfile", "bytes": "1591" }, { "name": "Fortran", "bytes": "16349" }, { "name": "HTML", "bytes": "311171" }, { "name": "JavaScript", "bytes": "2209253" }, { "name": "Jupyter Notebook", "bytes": "7661154" }, { "name": "Makefile", "bytes": "290745" }, { "name": "Perl", "bytes": "3890" }, { "name": "Python", "bytes": "1422764" }, { "name": "Shell", "bytes": "32489" }, { "name": "Smarty", "bytes": "2938" }, { "name": "SourcePawn", "bytes": "52752" } ], "symlink_target": "" }
package net.dirtydeeds.discordsoundboard.utils; import java.awt.*; import java.text.BreakIterator; import java.text.SimpleDateFormat; import java.util.List; import java.util.*; public class StringUtils { private static final int MAX_NUMBER_OF_CACHED_WORDS = 32; private static final int MIN_WORD_SIZE = 3; private static final String STARTING_CACHE_WORD = "Noot"; private static final List<String> PREPOSITIONS = Arrays.asList( "of", "by", "as", "at", "for", "in", "into", "on", "with", "in the", "of the", "for the", "at the", "with the", "on the", "the", "under", "between", "after", "before", "without"); public static List<String> wordCache = initializeCache(); public static String truncate(String str) { return truncate(str, 10); } public static String truncate(String str, int len) { String truncated = str.substring(0, Math.min(str.length(), len)); if (str.length() > len) truncated += "..."; return truncated; } public static boolean containsOnly(String str, char c) { for (char s : str.toCharArray()) { if (s != c) return false; } return true; } public static boolean containsAny(String str, char c) { if (str == null) return false; for (char s : str.toCharArray()) { if (s == c) return true; } return false; } public static String randomString(Collection<String> strings) { if (strings.isEmpty()) return ""; Random rng = new Random(); int i = rng.nextInt(strings.size()), k = 0; for (String string : strings) { if (k == i) return string; ++k; } return null; } public static String randomWord() { return randomString(wordCache); } public static String randomPreposition() { return randomString(PREPOSITIONS); } public static String randomPhrase(int numWords) { String[] words = new String[numWords]; for (int i = 0; i < numWords; ++i) { words[i] = (i % 2 == 1 && i != numWords - 1) ? (String) RandomUtils.chooseOne( capitalizeIfNotPreposition(randomWord()), randomPreposition()) : capitalizeIfNotPreposition(randomWord()); } return String.join(" ", words); } public static String randomPhrase() { return randomPhrase(RandomUtils.smallNumber() + 1); } public static <T> String listToString(List<T> list) { if (list.size() == 1) { return list.get(0).toString(); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); ++i) { sb.append(list.get(i).toString()); if (i + 1 < list.size() - 1) sb.append(", "); else if (i + 1 == list.size() - 1) sb.append(", and "); } return sb.toString(); } public static String humanize(String s) { if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } public static String capitalize(String s) { if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static String capitalizeIfNotPreposition(String s) { if (PREPOSITIONS.contains(s.toLowerCase())) return s; return capitalize(s); } public static String dayTimeStamp(Date date) { if (date == null) return ""; SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); return formatter.format(date); } public static Color toColor(String s) { int hash = s.hashCode(), r = (hash & 0x0000FF), g = (hash & 0x00FF00) >> 8, b = (hash & 0xFF0000) >> 16; return new Color(r, g, b); } public static void cacheString(String s) { if (!wordCache.contains(s)) wordCache.add(s); } public static boolean containsDigit(String s) { for (int i = 0; i < s.length(); ++i) { if (Character.isDigit(s.charAt(i))) return true; } return false; } public static void cacheWords(String message) { BreakIterator iter = BreakIterator.getWordInstance(); iter.setText(message); int last = iter.first(); while (BreakIterator.DONE != last) { int first = last; last = iter.next(); if (last == BreakIterator.DONE) continue; String word = message.substring(first, last); if (!containsDigit(word) && word.length() >= MIN_WORD_SIZE) { cacheString(word); } } } private static LimitedQueue<String> initializeCache() { LimitedQueue<String> cache = new LimitedQueue<>(MAX_NUMBER_OF_CACHED_WORDS); cache.add(STARTING_CACHE_WORD); return cache; } }
{ "content_hash": "fd747c082e7cbb2e4e6e2bc332590b35", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 80, "avg_line_length": 29.863636363636363, "alnum_prop": 0.6162209175907806, "repo_name": "AlexSafatli/NootBot", "id": "c7a60c52d00a0b5ee8065b82e95b85a95547bac6", "size": "4599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/dirtydeeds/discordsoundboard/utils/StringUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22" }, { "name": "Java", "bytes": "259990" } ], "symlink_target": "" }
require 'hpricot' require 'pathname' require "set" require "uri" module TaliaCore module ActiveSourceParts module Xml # Superclass for importers/readers of generic xml files. The idea is that the # user can very easily create subclasses of this that can import almost any XML # format imaginable - see the SourceReader class for a simple example. # # The result of the "import" is a hash (available through #sources) which contains # all the data from the import file in a standardized format. This hash can then # be processed by the ActiveSource class to create the actual sources. # # = Writing XML importers # # Writing an importer is quite easy, all it takes is to subclass this class and # then describe the structure of the element using the methods defined here. # # The reader subclass should declare handlers for the various XML tags that are # in the file. See GenericReaderImportStatements for an explanation of how the # handlers work and how they are declared. This module also contains methods to # retrieve data from the XML in order to use it in the import # # The GenericReaderAddStatements contain the methods that are used to add data # to the source that is currently being imported. # # In addition to the SourceReader class that can be used as an example, the # other modules also contain some code examples for the mechanism. # # There are also some GenericReaderHelpers that can be used during the import. # # = Using an Importer # # The default way of using an importer is usually indirectly, through # ActiveSource.create_from_xml. For direct use the sources_from_url or # sources_from methods can be called - these are the entry points for the # import process. # # = Result of the import operation # # The result of an import is an Array that contains a number of hashes. Each # of those can be passed to ActiveSource.new to create a new source object # with the given attributes. # # = Progress Reporting # # The class implements the TaliaUtil::Progressable interface, and if a # progressor object is assigned, it will report the progress to it during # the import operation. class GenericReader extend TaliaUtil::IoHelper include TaliaUtil::IoHelper include TaliaUtil::Progressable include TaliaUtil::UriHelper # Include all the parts include GenericReaderImportStatements extend GenericReaderImportStatements::Handlers include GenericReaderAddStatements include GenericReaderHelpers # Class for the current import state. This contains the XML element that # is currently imported, and the hash with the attributes for the currently # importing source. In the importer, the current State will be available as # @current class State attr_accessor :attributes, :element end class << self # See the IoHelper class for help on the options. A progressor may # be supplied on which the importer will report it's progress. def sources_from_url(url, options = nil, progressor = nil) open_generic(url, options) { |io| sources_from(io, progressor, url) } end # Read the sources from the given IO stream. You may specify a base # url to help the reader to decide from where files should be opened. def sources_from(source, progressor = nil, base_url=nil) reader = self.new(source) reader.base_file_url = base_url if(base_url) reader.progressor = progressor reader.sources end # Set the reader to allow the use of root elements for import def can_use_root @use_root = true end # True if the reader should also check the root element, instead of # only checking the children def use_root @use_root || false end # Returns the registered handlers attr_reader :create_handlers private # Adds an handler for the the given element. This will basically create an instance method # <element_name>_handler, and add some bookkeeping information to the class. # # See call_handler to see how handlers are called. # # The creating parameter will indicate wether the handler, when called, will create a new # method or not. def element_handler(element_name, creating, &handler_block) element_name = "#{element_name}_handler".to_sym raise(ArgumentError, "Duplicate handler for #{element_name}") if(self.respond_to?(element_name)) raise(ArgumentError, "Must pass block to handler for #{element_name}") unless(handler_block) @create_handlers ||= {} @create_handlers[element_name] = creating # Indicates whether a soure is created # Define the handler block method define_method(element_name, handler_block) end end # End class methods # Create a new reader. This parses the XML contained from the source and makes # the resulting XML document available to the reader def initialize(source) @doc = Hpricot.XML(source) end # Build a list of sources. This will return an array of hashes, and each # hash can be used to create a new source with ActiveSource.new. # # The result will be cached and once read, subsequent calls will return # the same set of "sources" again # # *Example of Result*: # # [ # { # 'uri' => 'http://foobar.com', # 'type' => 'TaliaCore::Collection', # 'http://rdfbar/foo' => '<http://taliainstall/otherthing' # }, # { # 'uri' => 'http://taliainstall/otherthing', # 'type' => 'TaliaCore::DataTypes::DummySource' # } # ] def sources return @sources if(@sources) @sources = {} if(use_root && self.respond_to?("#{@doc.root.name}_handler".to_sym)) run_with_progress('XmlRead', 1) { read_source(@doc.root) } else read_children_with_progress(@doc.root) end @sources.values end # This is the "base" for resolving file URLs. If a file URL is found # to be relative, it will be relative to this URL. # # If no base URL was specified this will use the file system path to # TALIA_ROOT def base_file_url @base_file_url ||= TALIA_ROOT end # Assign a new base_file_url def base_file_url=(new_base_url) @base_file_url = base_for(new_base_url) end # This will add the given source to the global result. source_attribs is a hash # with the attributes of one source. If that source already exists in the global # results, the two versions will be merged: # # * If the property is a list of values (an Array) in both the new and the old # version, these lists will be joined. # * Otherwise, the old property will be overwritten by the new one # # The source_attribs *must* contain a URI, and they *must not* change a type # field that is anything else than nil or TaliaCore::SourceTypes::DummySource def add_source_with_check(source_attribs) assit_kind_of(Hash, source_attribs) # Check if we have a URI if((uri = source_attribs['uri']).blank?) raise(RuntimeError, "Problem reading from XML: Source without URI (#{source_attribs.inspect})") else source_attribs['uri'] = irify(uri) # "Irify" the URI (see UriHelper module) @sources[uri] ||= {} # This is the hash in the global result for our uri @sources[uri].each do |key, value| # Loop through existing results next unless(new_value = source_attribs.delete(key)) # Skip all existing that are not in the new attributes # Assert that we don't change a type away from DummySource - this would indicate some problem w/ the data assit(!((key.to_sym == :type) && (value != 'TaliaCore::SourceTypes::DummySource') && (value != new_value)), "Type should not change during import, may be a format problem. (From #{value} to #{new_value})") if(new_value.is_a?(Array) && value.is_a?(Array)) # If both new and old are Array-types, the new elements will be appended # and duplicates will be removed @sources[uri][key] = (value + new_value).uniq else # Otherwise just replace the old value with the new one @sources[uri][key] = new_value end end # Everything that is only in the new attributes can be merged in @sources[uri].merge!(source_attribs) end end # Returns a hash with all handlers that "create" (that is, they # create a new source when called). This is taken from the class' # create_handlers accessor def create_handlers @handlers ||= (self.class.create_handlers || {}) end # Read a single source from a XML elem. # Pass in the XML element and an (optional) # block. This will call the handler (or block, see call_handler) # and add the result to the global result set using # add_source_with_check def read_source(element, &block) attribs = call_handler(element, &block) add_source_with_check(attribs) if(attribs) end # As read_children of, using the standard progressor of the reader def read_children_with_progress(element, &block) run_with_progress('Xml Read', element.children.size) do |prog| read_children_of(element, prog, &block) end end # Read source data from each child of the given element # using read_source. Optionally reports the progress to # the given progressor. def read_children_of(element, progress = nil, &block) element.children.each do |element| progress.inc if(progress) next unless(element.is_a?(Hpricot::Elem)) # only use XML elements read_source(element, &block) end end # Same as use_root of the current class def use_root self.class.use_root end # Call the handler method for the given element. If a block is given, that # will be called instead. Pass in the XML element to read from. # # This saves the @current State object before calling the handler, and # restores it after the call is complete. Thus nested calls will have their # own state, but the state will be restored once you return to the # parent handler. # # If a block is given, that block will be executed as the handler. Otherwise # the system checks for the "<element.name>_handler" method, and calls it. # (See also element_handler) # # If no block is given and no handler is found, an error is logged. def call_handler(element) handler_name = "#{element.name}_handler".to_sym if(self.respond_to?(handler_name) || block_given?) parent_state = @current # Save the state for recursive calls attributes = nil begin creating = (create_handlers[handler_name] || block_given?) @current = State.new @current.attributes = creating ? {} : nil @current.element = element block_given? ? yield : self.send(handler_name) attributes = @current.attributes ensure @current = parent_state # Reset the state to previous value end attributes else TaliaCore.logger.warn("Unknown element in import: #{element.name}") false end end # Checks if the current status has an attribute hash, which means that there # is a "current" source being created at the moment. def chk_create raise(RuntimeError, "Illegal operation when not creating a source") unless(@current.attributes) end # Add a property to the source that is currently being imported. If no object is given, the method # just exits, unless required is set, in which case an error will be raised for an empty object. # # Database properties will be added as a single string, while other (semantic) properties will # always be added into an array (even if there is just a single object). # # This is the base code for adding elements, which is used for the add_* methods in # GenericReaderAddStatements. This method should not usually be used directly. def set_element(predicate, object, required) chk_create object = check_objects(object) if(!object) raise(ArgumentError, "No object given, but is required for #{predicate}.") if(required) return end predicate = predicate.respond_to?(:uri) ? predicate.uri.to_s : predicate.to_s if(ActiveSource.db_attr?(predicate)) assit(!object.is_a?(Array)) @current.attributes[predicate] = object else @current.attributes[predicate] ||= [] @current.attributes[predicate] << object end end # Pass in a list of elements that are to be used as objects in RDF triples. # This method will check the objects and remove any blank ones (which should # not be added). # # If no non-blank element is found in the input, this will always return nil def check_objects(objects) if(objects.kind_of?(Array)) objects.reject! { |obj| obj.blank? } (objects.size == 0) ? nil : objects else objects.blank? ? nil : objects end end end end end end
{ "content_hash": "e4a89d59881e3a27f19b88b6db6966fd", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 219, "avg_line_length": 43.3026706231454, "alnum_prop": 0.6091961899540875, "repo_name": "net7/talia_core", "id": "3b2cc82e29be97592b68c66e6b3c0863df5c9a85", "size": "14766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/talia_core/active_source_parts/xml/generic_reader.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "52111" }, { "name": "Ruby", "bytes": "677119" }, { "name": "Shell", "bytes": "1210" }, { "name": "Tcl", "bytes": "7721" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.avc.avcinstaller.activity.MainActivity" > <item android:id="@+id/clear_cache" android:icon="@android:drawable/ic_menu_delete" android:showAsAction="never" android:title="@string/clear_cache_menu"/> <item android:id="@+id/menu_home" android:orderInCategory="100" android:showAsAction="always" android:icon="@drawable/ic_home" android:title="@string/menu_home"/> <item android:id="@+id/menu_logout" android:orderInCategory="101" android:showAsAction="always" android:icon="@drawable/ic_logout" android:title="@string/menu_logout"/> </menu>
{ "content_hash": "2aab08307ec0867c63180589a30cf061", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 64, "avg_line_length": 32.80769230769231, "alnum_prop": 0.6014067995310668, "repo_name": "NikhilVijayakumar/Installer", "id": "ce229e4938dcbc706ffc9692ea6ef70d06776d9f", "size": "853", "binary": false, "copies": "1", "ref": "refs/heads/v.3.0", "path": "AVCInstaller/res/menu/menu_cache.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "92028" }, { "name": "PHP", "bytes": "9662" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in C. S. Sargent, Pl. wilson. 1:373. 1913 #### Original name null ### Remarks null
{ "content_hash": "e55625795e8fdff8ef373d3537b8ca03", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 38, "avg_line_length": 12.307692307692308, "alnum_prop": 0.6875, "repo_name": "mdoering/backbone", "id": "1832754cecff69fba75ff6682daf9508f84c8e42", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Berberidaceae/Berberis/Berberis lecomtei/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package net.meisen.general.sbconfigurator.factories; import java.util.ArrayList; import java.util.Collection; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.AbstractFactoryBean; /** * Implementation of a {@code FactoryBean} which can be used to merge a * {@code Collection} of {@code Collections} into one collection. * * @see FactoryBean * @author pmeisen * */ public class MergedCollection extends AbstractFactoryBean<Collection<?>> { @SuppressWarnings("rawtypes") private Class<? extends Collection> collectionClass = ArrayList.class; private Collection<Collection<?>> collections; @Override public Class<?> getObjectType() { return Collection.class; } /** * Sets the class of the collection to be created, by default an * {@code ArrayList} is used. * * @param collectionClass * the class of the collection to be created */ @SuppressWarnings("rawtypes") public void setCollectionClass( final Class<? extends Collection> collectionClass) { this.collectionClass = collectionClass; } /** * Set the collections to be merged. * * @param collections * thec collections to be merged */ public void setCollections(final Collection<Collection<?>> collections) { this.collections = collections; } @Override protected Collection<?> createInstance() throws Exception { @SuppressWarnings("unchecked") final Collection<Object> mergedRes = BeanUtils .instantiateClass(collectionClass); if (collections == null || collections.size() == 0) { // nothing to do } else { // add all the colletions together for (final Collection<?> collection : collections) { if (collection != null) { mergedRes.addAll(collection); } } } return mergedRes; } }
{ "content_hash": "c69b97f984345562edcd4836a79d106a", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 74, "avg_line_length": 25.791666666666668, "alnum_prop": 0.715670436187399, "repo_name": "pmeisen/gen-sbconfigurator", "id": "502ba1be5ec6d88a8bde4336e30b3aea01171374", "size": "1857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/net/meisen/general/sbconfigurator/factories/MergedCollection.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "311655" }, { "name": "XSLT", "bytes": "2446" } ], "symlink_target": "" }
'use strict'; var raveLogo = 'https://res.cloudinary.com/dkbfehjxf/image/upload/v1511542310/Pasted_image_at_2017_11_09_04_50_PM_vc75kz.png' var amount = flw_payment_args.amount, cbUrl = flw_payment_args.cb_url, country = flw_payment_args.country, curr = flw_payment_args.currency, desc = flw_payment_args.desc, email = flw_payment_args.email, form = jQuery( '#flw-pay-now-button' ), logo = flw_payment_args.logo || raveLogo, p_key = flw_payment_args.p_key, title = flw_payment_args.title, txref = flw_payment_args.txnref, paymentMethod = flw_payment_args.payment_method, redirect_url; if ( form ) { form.on( 'click', function( evt ) { evt.preventDefault(); processPayment(); } ); } var processPayment = function() { getpaidSetup({ amount: amount, country: country, currency: curr, custom_description: desc, custom_title: title, custom_logo: logo, customer_email: email, txref: txref, payment_method: paymentMethod, PBFPubKey: p_key, onclose: function(){ if (redirect_url) { redirectTo( redirect_url ); } }, callback: function(d){ sendPaymentRequestResponse( d ); } }); }; var sendPaymentRequestResponse = function( res ) { jQuery .post( cbUrl, res.tx ) .success( function(data) { var response = JSON.parse( data ); redirect_url = response.redirect_url; setTimeout( redirectTo, 5000, redirect_url ); } ); }; var redirectTo = function( url ) { location.href = url; };
{ "content_hash": "0c4111ae297ec773c116ffcca3aa0567", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 125, "avg_line_length": 24.515625, "alnum_prop": 0.6309751434034416, "repo_name": "bosunolanrewaju/WooCommerce-Rave-Payment-Gateway", "id": "d14dd60a35575b145b442b49b985e079b1b3a251", "size": "1569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/js/flw.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1569" }, { "name": "PHP", "bytes": "13472" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>HE_Mesh: src/geom/wblut/geom/WB_MutableCoordinateFull3D.java File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">HE_Mesh &#160;<span id="projectnumber">6.0.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('_w_b___mutable_coordinate_full3_d_8java.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Packages</a> </div> <div class="headertitle"> <div class="title">WB_MutableCoordinateFull3D.java File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">interface &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_full3_d.html">wblut.geom.WB_MutableCoordinateFull3D</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Packages</h2></td></tr> <tr class="memitem:namespacewblut_1_1geom"><td class="memItemLeft" align="right" valign="top">package &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacewblut_1_1geom.html">wblut.geom</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_abb63ba6bdd980ee47e7becce32622d5.html">src</a></li><li class="navelem"><a class="el" href="dir_28039f23bdc84069801247037dab54b5.html">geom</a></li><li class="navelem"><a class="el" href="dir_5e6470d91fe28ff2551452ee3fa30f4b.html">wblut</a></li><li class="navelem"><a class="el" href="dir_f78523ae0426caa5c66821e8fc2afc74.html">geom</a></li><li class="navelem"><a class="el" href="_w_b___mutable_coordinate_full3_d_8java.html">WB_MutableCoordinateFull3D.java</a></li> <li class="footer">Generated on Tue Dec 19 2017 21:20:07 for HE_Mesh by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
{ "content_hash": "fc8220426db77648ceead232e2f8b18e", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 514, "avg_line_length": 45.911764705882355, "alnum_prop": 0.6601537475976937, "repo_name": "DweebsUnited/CodeMonkey", "id": "22c52d621d7ce948790c05e8ddeea455e79014ab", "size": "6244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/hemesh/ref/html/_w_b___mutable_coordinate_full3_d_8java.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "718" }, { "name": "C++", "bytes": "2748240" }, { "name": "CMake", "bytes": "11221" }, { "name": "CSS", "bytes": "896" }, { "name": "GLSL", "bytes": "1116" }, { "name": "HTML", "bytes": "887" }, { "name": "Java", "bytes": "132732" }, { "name": "Makefile", "bytes": "23824" }, { "name": "Meson", "bytes": "246" }, { "name": "Objective-C", "bytes": "810" }, { "name": "Processing", "bytes": "205574" }, { "name": "Python", "bytes": "65902" }, { "name": "Shell", "bytes": "6253" } ], "symlink_target": "" }
/** * */ package org.javarosa.core.services.locale; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.javarosa.core.util.OrderedHashtable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * @author Clayton Sims * @date Jun 1, 2009 * */ public class ResourceFileDataSource implements LocaleDataSource { String resourceURI; /** * NOTE: FOR SERIALIZATION ONLY! */ public ResourceFileDataSource() { } /** * Creates a new Data Source for Locale data with the given resource URI. * * @param resourceURI a URI to the resource file from which data should be loaded * @throws NullPointerException if resourceURI is null */ public ResourceFileDataSource(String resourceURI) { if(resourceURI == null) { throw new NullPointerException("Resource URI cannot be null when creating a Resource File Data Source"); } this.resourceURI = resourceURI; } /* (non-Javadoc) * @see org.javarosa.core.services.locale.LocaleDataSource#getLocalizedText() */ public OrderedHashtable getLocalizedText() { return loadLocaleResource(resourceURI); } /* (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory) */ public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { resourceURI = in.readUTF(); } /* (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream) */ public void writeExternal(DataOutputStream out) throws IOException { out.writeUTF(resourceURI); } /** * @param resourceName A path to a resource file provided in the current environment * * @return a dictionary of key/value locale pairs from a file in the resource directory */ private OrderedHashtable loadLocaleResource(String resourceName) { InputStream is = System.class.getResourceAsStream(resourceName); // TODO: This might very well fail. Best way to handle? OrderedHashtable locale = new OrderedHashtable(); int chunk = 100; InputStreamReader isr; try { isr = new InputStreamReader(is,"UTF-8"); } catch (Exception e) { throw new RuntimeException("Failed to load locale resource " + resourceName + ". Is it in the jar?"); } boolean done = false; char[] cbuf = new char[chunk]; int offset = 0; int curline = 0; try { String line = ""; while (!done) { int read = isr.read(cbuf, offset, chunk - offset); if(read == -1) { done = true; if(line != "") { parseAndAdd(locale, line, curline); } break; } String stringchunk = String.valueOf(cbuf,offset,read); int index = 0; while(index != -1) { int nindex = stringchunk.indexOf('\n',index); //UTF-8 often doesn't encode with newline, but with CR, so if we //didn't find one, we'll try that if(nindex == -1) { nindex = stringchunk.indexOf('\r',index); } if(nindex == -1) { line += stringchunk.substring(index); break; } else { line += stringchunk.substring(index,nindex); //Newline. process our string and start the next one. curline++; parseAndAdd(locale, line, curline); line = ""; } index = nindex + 1; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { System.out.println("Input Stream for resource file " + resourceURI + " failed to close. This will eat up your memory! Fix Problem! [" + e.getMessage() + "]"); e.printStackTrace(); } } return locale; } private void parseAndAdd(OrderedHashtable locale, String line, int curline) { //trim whitespace. line = line.trim(); //clear comments while(line.indexOf("#") != -1) { line = line.substring(0, line.indexOf("#")); } if(line.indexOf('=') == -1) { // TODO: Invalid line. Empty lines are fine, especially with comments, // but it might be hard to get all of those. if(line.trim().equals("")) { //Empty Line } else { System.out.println("Invalid line (#" + curline + ") read: " + line); } } else { //Check to see if there's anything after the '=' first. Otherwise there //might be some big problems. if(line.indexOf('=') != line.length()-1) { String value = line.substring(line.indexOf('=') + 1,line.length()); locale.put(line.substring(0, line.indexOf('=')), value); } else { System.out.println("Invalid line (#" + curline + ") read: '" + line + "'. No value follows the '='."); } } } }
{ "content_hash": "1d2e053a0113a14294e6f31ab6384e82", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 162, "avg_line_length": 28.680473372781066, "alnum_prop": 0.6682484010728286, "repo_name": "wpride/javarosa", "id": "fd7c1064c5b286c24e5048a7db6ff67f7bbb58ec", "size": "5438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/org/javarosa/core/services/locale/ResourceFileDataSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "46621" }, { "name": "Java", "bytes": "2699604" }, { "name": "Python", "bytes": "33735" } ], "symlink_target": "" }
''' A program with bugs. Try to fix them all! ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 12.2.2 of the book "Managing Biological Data with Python". ----------------------------------------------------------- ''' def evaluate_data(data, lower=100, upper=300): """Counts data points in three bins.""" import pdb pdb.set_trace() smaller = 0 between = 0 bigger = 0 for length in data: if length < lower: smaller = smaller + 1 elif lower < length < upper: between = between + 1 elif length > upper: bigger += 1 # bigger = 1 return smaller, between, bigger def read_data(filename): """Reads neuron lengths from a text file.""" primary, secondary = [], [] for line in open(filename): category, length = line.split("\t") length = float(length) if category == "Primary": primary.append(length) elif category == "Secondary": # print(dir()) secondary.append(length) return primary, secondary def write_output(filename, count_pri, count_sec): """Writes counted values to a file.""" output = open(filename,"w") output.write("category <100 100-300 >300\n") output.write("Primary : %5i %5i %5i\n" % count_pri) output.write("Secondary: %5i %5i %5i\n" % count_sec) output.close() primary, secondary = read_data('neuron_data.txt') count_pri = evaluate_data(primary) count_sec = evaluate_data(secondary) write_output('results.txt' , count_pri,count_sec)
{ "content_hash": "c2200dbc054a71a490d16f8e86dbfbd3", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 61, "avg_line_length": 30.350877192982455, "alnum_prop": 0.5630057803468208, "repo_name": "raymonwu/Managing_Your_Biological_Data_with_Python_3", "id": "19964a4d8d9da39ef3d2937bd95f9c20a91b25cd", "size": "1730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "12-debugging/12.3.3.1_program_with_bugs.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "96353" }, { "name": "Jupyter Notebook", "bytes": "3309089" }, { "name": "Python", "bytes": "103196" } ], "symlink_target": "" }
package com.equalinformation.fpps /** * Created by bpupadhyaya on 9/8/15. * * Implement logical and without using && */ object LogicalAndWithMain { def infiniteLoop: Boolean = infiniteLoop def and(x: Boolean, y: => Boolean): Boolean = { if(x) y else false } def main(args: Array[String]): Unit = { println("true and true : "+and(true,true)) println("true and false : "+and(true,false)) println("false and true : "+and(false,true)) println("false and false : "+and(false,false)) println("false and loop : "+and(false,infiniteLoop)) //expected false because of call by name // Note : see equivalent class without main and unit tests } }
{ "content_hash": "f9f57869fc5c7fcaa059ba6fb81f269c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 97, "avg_line_length": 26.26923076923077, "alnum_prop": 0.6632503660322109, "repo_name": "EqualInformation/fpps", "id": "3277e57e86e4d5eae2f045eb81afd8507c92bf54", "size": "683", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/scala/com/equalinformation/fpps/LogicalAndWithMain.scala", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9300" }, { "name": "Java", "bytes": "246" }, { "name": "Scala", "bytes": "11148" }, { "name": "XSLT", "bytes": "43014" } ], "symlink_target": "" }
package edu.gemini.spModel.gemini.nifs.blueprint; import edu.gemini.pot.sp.SPComponentType; import edu.gemini.spModel.core.Site; import edu.gemini.spModel.gemini.nifs.InstNIFS; import edu.gemini.spModel.gemini.nifs.NIFSParams.Disperser; import edu.gemini.spModel.pio.ParamSet; import edu.gemini.spModel.pio.Pio; import edu.gemini.spModel.pio.PioFactory; import edu.gemini.spModel.template.SpBlueprint; public abstract class SpNifsBlueprintBase extends SpBlueprint { public static final String DISPERSER_PARAM_NAME = "disperser"; public final Disperser disperser; protected SpNifsBlueprintBase(Disperser disperser) { this.disperser = disperser; } protected SpNifsBlueprintBase(ParamSet paramSet) { this.disperser = Pio.getEnumValue(paramSet, DISPERSER_PARAM_NAME, Disperser.DEFAULT); } public SPComponentType instrumentType() { return InstNIFS.SP_TYPE; } public ParamSet toParamSet(PioFactory factory) { ParamSet paramSet = factory.createParamSet(paramSetName()); Pio.addEnumParam(factory, paramSet, DISPERSER_PARAM_NAME, disperser); return paramSet; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpNifsBlueprintBase that = (SpNifsBlueprintBase) o; if (disperser != that.disperser) return false; return true; } @Override public int hashCode() { return disperser.hashCode(); } }
{ "content_hash": "908e02b1cbd905cc8cd23635a7ee5ebf", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 93, "avg_line_length": 31.102040816326532, "alnum_prop": 0.7152230971128609, "repo_name": "spakzad/ocs", "id": "a7a94817f54af2381c9268f1dfdd47d57f04e8aa", "size": "1524", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/nifs/blueprint/SpNifsBlueprintBase.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "497994" }, { "name": "Java", "bytes": "13980248" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "5229267" }, { "name": "Shell", "bytes": "3368" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
#ifndef ScrollAnimatorMac_h #define ScrollAnimatorMac_h #include "platform/Timer.h" #include "platform/geometry/FloatPoint.h" #include "platform/geometry/FloatSize.h" #include "platform/geometry/IntRect.h" #include "platform/mac/ScrollElasticityController.h" #include "platform/scroll/ScrollAnimator.h" #include "wtf/RetainPtr.h" OBJC_CLASS WebScrollAnimationHelperDelegate; OBJC_CLASS WebScrollbarPainterControllerDelegate; OBJC_CLASS WebScrollbarPainterDelegate; typedef id ScrollbarPainterController; #if !USE(RUBBER_BANDING) class ScrollElasticityControllerClient { }; #endif namespace blink { class Scrollbar; class PLATFORM_EXPORT ScrollAnimatorMac : public ScrollAnimator, private ScrollElasticityControllerClient { public: ScrollAnimatorMac(ScrollableArea*); virtual ~ScrollAnimatorMac(); void immediateScrollToPointForScrollAnimation(const FloatPoint& newPosition); bool haveScrolledSincePageLoad() const { return m_haveScrolledSincePageLoad; } void updateScrollerStyle(); bool scrollbarPaintTimerIsActive() const; void startScrollbarPaintTimer(); void stopScrollbarPaintTimer(); void sendContentAreaScrolledSoon(const FloatSize& scrollDelta); void setVisibleScrollerThumbRect(const IntRect&); static bool canUseCoordinatedScrollbar(); private: RetainPtr<id> m_scrollAnimationHelper; RetainPtr<WebScrollAnimationHelperDelegate> m_scrollAnimationHelperDelegate; RetainPtr<ScrollbarPainterController> m_scrollbarPainterController; RetainPtr<WebScrollbarPainterControllerDelegate> m_scrollbarPainterControllerDelegate; RetainPtr<WebScrollbarPainterDelegate> m_horizontalScrollbarPainterDelegate; RetainPtr<WebScrollbarPainterDelegate> m_verticalScrollbarPainterDelegate; void initialScrollbarPaintTimerFired(Timer<ScrollAnimatorMac>*); Timer<ScrollAnimatorMac> m_initialScrollbarPaintTimer; void sendContentAreaScrolledTimerFired(Timer<ScrollAnimatorMac>*); Timer<ScrollAnimatorMac> m_sendContentAreaScrolledTimer; FloatSize m_contentAreaScrolledTimerScrollDelta; virtual ScrollResultOneDimensional scroll(ScrollbarOrientation, ScrollGranularity, float step, float delta) override; virtual void scrollToOffsetWithoutAnimation(const FloatPoint&) override; #if USE(RUBBER_BANDING) virtual ScrollResult handleWheelEvent(const PlatformWheelEvent&) override; #endif virtual void handleWheelEventPhase(PlatformWheelEventPhase) override; virtual void cancelAnimations() override; virtual void setIsActive() override; virtual void contentAreaWillPaint() const override; virtual void mouseEnteredContentArea() const override; virtual void mouseExitedContentArea() const override; virtual void mouseMovedInContentArea() const override; virtual void mouseEnteredScrollbar(Scrollbar*) const override; virtual void mouseExitedScrollbar(Scrollbar*) const override; virtual void willStartLiveResize() override; virtual void contentsResized() const override; virtual void willEndLiveResize() override; virtual void contentAreaDidShow() const override; virtual void contentAreaDidHide() const override; void didBeginScrollGesture() const; void didEndScrollGesture() const; void mayBeginScrollGesture() const; virtual void finishCurrentScrollAnimations() override; virtual void didAddVerticalScrollbar(Scrollbar*) override; virtual void willRemoveVerticalScrollbar(Scrollbar*) override; virtual void didAddHorizontalScrollbar(Scrollbar*) override; virtual void willRemoveHorizontalScrollbar(Scrollbar*) override; virtual bool shouldScrollbarParticipateInHitTesting(Scrollbar*) override; virtual void notifyContentAreaScrolled(const FloatSize& delta) override; FloatPoint adjustScrollPositionIfNecessary(const FloatPoint&) const; void immediateScrollTo(const FloatPoint&); virtual bool isRubberBandInProgress() const override; #if USE(RUBBER_BANDING) /// ScrollElasticityControllerClient member functions. virtual IntSize stretchAmount() override; virtual bool allowsHorizontalStretching() override; virtual bool allowsVerticalStretching() override; virtual bool pinnedInDirection(const FloatSize&) override; virtual bool canScrollHorizontally() override; virtual bool canScrollVertically() override; virtual IntPoint absoluteScrollPosition() override; virtual void immediateScrollByWithoutContentEdgeConstraints(const FloatSize&) override; virtual void immediateScrollBy(const FloatSize&) override; virtual void startSnapRubberbandTimer() override; virtual void stopSnapRubberbandTimer() override; virtual void adjustScrollPositionToBoundsIfNecessary() override; bool pinnedInDirection(float deltaX, float deltaY); void snapRubberBandTimerFired(Timer<ScrollAnimatorMac>*); ScrollElasticityController m_scrollElasticityController; Timer<ScrollAnimatorMac> m_snapRubberBandTimer; #endif bool m_haveScrolledSincePageLoad; bool m_needsScrollerStyleUpdate; IntRect m_visibleScrollerThumbRect; }; } // namespace blink #endif // ScrollAnimatorMac_h
{ "content_hash": "3c4bf98a571bd13b9c9de73b17c9a63b", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 121, "avg_line_length": 37.36231884057971, "alnum_prop": 0.8068269976726145, "repo_name": "CTSRD-SOAAP/chromium-42.0.2311.135", "id": "e2503b1bdfc4f8857797c3f82958dfa77446d9f4", "size": "6516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "8402" }, { "name": "Assembly", "bytes": "241154" }, { "name": "C", "bytes": "12370053" }, { "name": "C++", "bytes": "266788423" }, { "name": "CMake", "bytes": "27829" }, { "name": "CSS", "bytes": "813488" }, { "name": "Emacs Lisp", "bytes": "2360" }, { "name": "Go", "bytes": "13628" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "20131029" }, { "name": "Java", "bytes": "8495790" }, { "name": "JavaScript", "bytes": "12980966" }, { "name": "LLVM", "bytes": "1169" }, { "name": "Logos", "bytes": "6893" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "208709" }, { "name": "Objective-C", "bytes": "1509363" }, { "name": "Objective-C++", "bytes": "7960581" }, { "name": "PLpgSQL", "bytes": "215882" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "432373" }, { "name": "Python", "bytes": "11147426" }, { "name": "Ragel in Ruby Host", "bytes": "104923" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "1207731" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "VimL", "bytes": "4075" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
<div class="body"> <!-- first use --> <div ng-show="completedRoutines.length < 1"> <div class="welcome-container"> <div class="welcome-user"> </div> <h2>Welcome to PPL!</h2> <div class="animated fadeIn question-container"> <div class="question-title">What are your fitness goals?</div> <div class="answer-container"> <div class="answer"> I want to lose fat. </div> <div class="answer"> I want to gain strength </div> </div> </div> <p>Let's start you off with a great routine.</p> </div> </div> <!-- user has completed at least one workout --> <div class="body-container" ng-show="completedRoutines.length > 0"> <div class="welcome-container"> <div class="welcome-user"> </div> Hello! Ready to start your workout? </div> <div class="workout-container" style="margin-bottom:.5em;"> <div class="workout-header"> <div class="workout-header-date"> {{previousRoutine.dateCompleted | date:'medium'}} </div> <div class="workout-header-name"> Last time: {{previousRoutine.name}} </div> </div> </div> <div class="workout-container"> <div class="workout-header"> <div ng-if="inProgress" class="workout-header-name"> In progress: {{nextRoutine.name}} </div> <div ng-if="!inProgress" class="workout-header-name"> Next up: {{nextRoutine.name}} </div> </div> </div> <ul class="nextup-block"> <li> <div class="workout-block-container" ng-repeat="movement in nextRoutine.movements"> <div class="workout-block-name"> {{movement.movement.name}} </div> <div class="workout-block-reps"> {{ movement.sets }} x {{ movement.reps }} </div> </div> </li> </ul> </div> </div> <div class="sticky" ng-class="{'down':$root.menu}" ng-show="!previousRoutine"> <div ng-click="startFirstWorkout()" class="start-container"> <div style="width:auto;padding:15px;"> <img class="start-flag" src="assets/img/flag.svg"> <div style="position:relative;top:-5px;margin-left:5px;display:inline-block"> START FIRST WORKOUT </div> </div> </div> </div> <div class="sticky" ng-class="{'down':$root.menu}" ng-show="previousRoutine"> <div ng-click="startWorkout(previousRoutine)" class="start-container"> <div style="width:auto;padding:15px;"> <img class="start-flag" src="assets/img/flag.svg"> <div style="position:relative;top:-5px;margin-left:5px;display:inline-block"> START WORKOUT </div> </div> </div> </div>
{ "content_hash": "92d7804ce58e630eb4ec867c8ce0a1c5", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 87, "avg_line_length": 27.467391304347824, "alnum_prop": 0.6264345073209339, "repo_name": "samjhill/ppl", "id": "90bf116258056f52ba1b95bb5b3b22fd74cce707", "size": "2528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/workout.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16588" }, { "name": "HTML", "bytes": "89578" }, { "name": "JavaScript", "bytes": "108807" }, { "name": "Shell", "bytes": "16880" } ], "symlink_target": "" }
namespace blink { class DedicatedWorkerThreadForTest; class DedicatedWorkerMessagingProxyForTest; class DedicatedWorkerTest : public PageTestBase { public: DedicatedWorkerTest() = default; void SetUp() override; void TearDown() override; void DispatchMessageEvent(); DedicatedWorkerMessagingProxyForTest* WorkerMessagingProxy(); DedicatedWorkerThreadForTest* GetWorkerThread(); void StartWorker(); void EvaluateClassicScript(const String& source_code); void WaitUntilWorkerIsRunning(); private: Persistent<DedicatedWorkerMessagingProxyForTest> worker_messaging_proxy_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_DEDICATED_WORKER_TEST_H_
{ "content_hash": "50c17c395a060f65af27e3133f2b780e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 23.433333333333334, "alnum_prop": 0.7923186344238976, "repo_name": "scheib/chromium", "id": "80e86127f547b3c3342f4e500bd89e94ad3be8d4", "size": "1150", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/workers/dedicated_worker_test.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<form model="template"> <field name="name"/> <field name="theme_id"/> <field name="module_id"/> <newline/> <field name="template" width="800" height="500" view="field_code" mode="handlebars"/> </form>
{ "content_hash": "e5cf0bae10e2026e7d74f33e6228aed8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 89, "avg_line_length": 31.571428571428573, "alnum_prop": 0.6108597285067874, "repo_name": "anastue/netforce", "id": "035e562344d044bcf9113e623df1a34d8ead0794", "size": "221", "binary": false, "copies": "4", "ref": "refs/heads/stable-3.1", "path": "netforce_cms/netforce_cms/layouts/template_form.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "CSS", "bytes": "407336" }, { "name": "Groff", "bytes": "15858" }, { "name": "HTML", "bytes": "477928" }, { "name": "Java", "bytes": "11870" }, { "name": "JavaScript", "bytes": "3711952" }, { "name": "Makefile", "bytes": "353" }, { "name": "PHP", "bytes": "2274" }, { "name": "Python", "bytes": "3455528" }, { "name": "Shell", "bytes": "117" } ], "symlink_target": "" }
 #include <aws/dms/model/OrderableReplicationInstance.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DatabaseMigrationService { namespace Model { OrderableReplicationInstance::OrderableReplicationInstance() : m_engineVersionHasBeenSet(false), m_replicationInstanceClassHasBeenSet(false), m_storageTypeHasBeenSet(false), m_minAllocatedStorage(0), m_minAllocatedStorageHasBeenSet(false), m_maxAllocatedStorage(0), m_maxAllocatedStorageHasBeenSet(false), m_defaultAllocatedStorage(0), m_defaultAllocatedStorageHasBeenSet(false), m_includedAllocatedStorage(0), m_includedAllocatedStorageHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_releaseStatus(ReleaseStatusValues::NOT_SET), m_releaseStatusHasBeenSet(false) { } OrderableReplicationInstance::OrderableReplicationInstance(JsonView jsonValue) : m_engineVersionHasBeenSet(false), m_replicationInstanceClassHasBeenSet(false), m_storageTypeHasBeenSet(false), m_minAllocatedStorage(0), m_minAllocatedStorageHasBeenSet(false), m_maxAllocatedStorage(0), m_maxAllocatedStorageHasBeenSet(false), m_defaultAllocatedStorage(0), m_defaultAllocatedStorageHasBeenSet(false), m_includedAllocatedStorage(0), m_includedAllocatedStorageHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_releaseStatus(ReleaseStatusValues::NOT_SET), m_releaseStatusHasBeenSet(false) { *this = jsonValue; } OrderableReplicationInstance& OrderableReplicationInstance::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("EngineVersion")) { m_engineVersion = jsonValue.GetString("EngineVersion"); m_engineVersionHasBeenSet = true; } if(jsonValue.ValueExists("ReplicationInstanceClass")) { m_replicationInstanceClass = jsonValue.GetString("ReplicationInstanceClass"); m_replicationInstanceClassHasBeenSet = true; } if(jsonValue.ValueExists("StorageType")) { m_storageType = jsonValue.GetString("StorageType"); m_storageTypeHasBeenSet = true; } if(jsonValue.ValueExists("MinAllocatedStorage")) { m_minAllocatedStorage = jsonValue.GetInteger("MinAllocatedStorage"); m_minAllocatedStorageHasBeenSet = true; } if(jsonValue.ValueExists("MaxAllocatedStorage")) { m_maxAllocatedStorage = jsonValue.GetInteger("MaxAllocatedStorage"); m_maxAllocatedStorageHasBeenSet = true; } if(jsonValue.ValueExists("DefaultAllocatedStorage")) { m_defaultAllocatedStorage = jsonValue.GetInteger("DefaultAllocatedStorage"); m_defaultAllocatedStorageHasBeenSet = true; } if(jsonValue.ValueExists("IncludedAllocatedStorage")) { m_includedAllocatedStorage = jsonValue.GetInteger("IncludedAllocatedStorage"); m_includedAllocatedStorageHasBeenSet = true; } if(jsonValue.ValueExists("AvailabilityZones")) { Aws::Utils::Array<JsonView> availabilityZonesJsonList = jsonValue.GetArray("AvailabilityZones"); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { m_availabilityZones.push_back(availabilityZonesJsonList[availabilityZonesIndex].AsString()); } m_availabilityZonesHasBeenSet = true; } if(jsonValue.ValueExists("ReleaseStatus")) { m_releaseStatus = ReleaseStatusValuesMapper::GetReleaseStatusValuesForName(jsonValue.GetString("ReleaseStatus")); m_releaseStatusHasBeenSet = true; } return *this; } JsonValue OrderableReplicationInstance::Jsonize() const { JsonValue payload; if(m_engineVersionHasBeenSet) { payload.WithString("EngineVersion", m_engineVersion); } if(m_replicationInstanceClassHasBeenSet) { payload.WithString("ReplicationInstanceClass", m_replicationInstanceClass); } if(m_storageTypeHasBeenSet) { payload.WithString("StorageType", m_storageType); } if(m_minAllocatedStorageHasBeenSet) { payload.WithInteger("MinAllocatedStorage", m_minAllocatedStorage); } if(m_maxAllocatedStorageHasBeenSet) { payload.WithInteger("MaxAllocatedStorage", m_maxAllocatedStorage); } if(m_defaultAllocatedStorageHasBeenSet) { payload.WithInteger("DefaultAllocatedStorage", m_defaultAllocatedStorage); } if(m_includedAllocatedStorageHasBeenSet) { payload.WithInteger("IncludedAllocatedStorage", m_includedAllocatedStorage); } if(m_availabilityZonesHasBeenSet) { Aws::Utils::Array<JsonValue> availabilityZonesJsonList(m_availabilityZones.size()); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { availabilityZonesJsonList[availabilityZonesIndex].AsString(m_availabilityZones[availabilityZonesIndex]); } payload.WithArray("AvailabilityZones", std::move(availabilityZonesJsonList)); } if(m_releaseStatusHasBeenSet) { payload.WithString("ReleaseStatus", ReleaseStatusValuesMapper::GetNameForReleaseStatusValues(m_releaseStatus)); } return payload; } } // namespace Model } // namespace DatabaseMigrationService } // namespace Aws
{ "content_hash": "e3e8822d5ca701e3d3d82f31f9d5656a", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 134, "avg_line_length": 27.020725388601036, "alnum_prop": 0.7675934803451582, "repo_name": "aws/aws-sdk-cpp", "id": "8a556b40420c9208c5cea9165cbe461c0ad3d493", "size": "5334", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-dms/source/model/OrderableReplicationInstance.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
title: Telerik.Web.UI.FileFilterCollection page_title: Telerik.Web.UI.FileFilterCollection description: Telerik.Web.UI.FileFilterCollection --- # Telerik.Web.UI.FileFilterCollection This class implements a strongly typed state managed collection. ## Inheritance Hierarchy * System.Object * System.Web.UI.StateManagedCollection * Telerik.Web.StronglyTypedStateManagedCollection`1 * Telerik.Web.UI.FileFilterCollection ## Properties ### Item `ItemType` ItemType collection indexer. ## Methods ### Add Add an item to the collection #### Parameters #### item ``0` Item to be added to the collection #### Returns `System.Void` ### AddRange Adds the items to the end of the collection #### Parameters #### items `System.Collections.Generic.IEnumerable{`0}` Items to be added #### Returns `System.Void` ### Contains Determines whether an element is in the collection #### Parameters #### item ``0` The item to locate in the collection #### Returns `System.Boolean` true if item is found in the collection; otherwise, false. ### CopyTo Copies the array or portion of it to the collection #### Parameters #### array ``0` One-dimensional array that serves as a destination #### index `System.Int32` Zero-based index #### Returns `System.Void` ### IndexOf Returns the zero-based index of the first occurrence of a value in the collection or in a portion of it. #### Parameters #### item ``0` Target item #### Returns `System.Int32` The zero-based index of the first occurrence of item within the entire collection ### Insert Inserts an element into the collection at the specified index. #### Parameters #### index `System.Int32` The zero-based index at which item should be inserted. #### item ``0` The object to insert. #### Returns `System.Void` ### Remove Removes the first occurrence of a specific object from the collection. #### Parameters #### item ``0` The object to remove from the collection #### Returns `System.Void` ### RemoveAt Removes the element at the specified index of the collection. #### Parameters #### index `System.Int32` The zero-based index of the element to remove. #### Returns `System.Void`
{ "content_hash": "8e90906418c964d331e12480bcebc3c8", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 104, "avg_line_length": 15.23611111111111, "alnum_prop": 0.7160437556973565, "repo_name": "telerik/ajax-docs", "id": "5160e70de2a12afcff74c1b1f2ee0253a90535b4", "size": "2198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/server/Telerik.Web.UI/FileFilterCollection.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "2253" }, { "name": "C#", "bytes": "6026" }, { "name": "HTML", "bytes": "2240" }, { "name": "JavaScript", "bytes": "3052" }, { "name": "Ruby", "bytes": "3275" } ], "symlink_target": "" }
"""This module offers methods and user interaction widgets/windows for handling the table-like step functions of elementary cellular automatons. * A bit of functionality to generate a rule number from arbitrary step functions by running them on a pre-generated target and finding out how it behaved. * ... .. testsetup :: from zasim import elementarytools """ # This file is part of zasim. zasim is licensed under the BSD 3-clause license. # See LICENSE.txt for details. from __future__ import absolute_import from .cagen.utils import elementary_digits_and_values, rule_nr_to_rule_arr neighbourhood_actions = {} def neighbourhood_action(name): def appender(fun): neighbourhood_actions[name] = fun return fun return appender def digits_and_values_to_rule_nr(digits_and_values, base=2): if isinstance(digits_and_values[0], dict): digits_and_values = [val["result_value"] for val in digits_and_values] num = 0 for digit, value in enumerate(digits_and_values): num += value * (base ** digit) return num _minimize_cache = {} def minimize_rule_number(neighbourhood, number, base=2): digits = base ** len(neighbourhood.offsets) rule_arr = rule_nr_to_rule_arr(number, digits, base) cache = {number: ([], rule_arr)} tries = [([name], rule_arr) for name in neighbourhood_actions] for route, data in tries: new = neighbourhood_actions[route[-1]](neighbourhood, data) rule_nr = digits_and_values_to_rule_nr(new) if rule_nr in cache: oldroute, olddata = cache[rule_nr] if len(oldroute) > len(route): cache[rule_nr] = (route, new) tries.extend([(route + [name], new) for name in neighbourhood_actions]) else: cache[rule_nr] = (route, new) tries.extend([(route + [name], new) for name in neighbourhood_actions]) lowest_number = min(cache.keys()) return lowest_number, cache[lowest_number], cache def minimize_rule_values(neighbourhood, digits_and_values): number = digits_and_values_to_rule_nr(digits_and_values) return minimize_rule_number(neighbourhood, number) @neighbourhood_action("flip all bits") def flip_all(neighbourhood, results, base=2): if isinstance(results[0], dict): nres = [val.copy() for val in results] for val in nres: val["result_value"] = base - 1 - val["result_value"] return nres else: return [base - 1 - res for res in results] def permutation_to_index_map(neighbourhood, permutation, base=2): """Figure out from the given neighbourhood and the permutation what position in the old array each entry in the new array is supposed to come from to realize the permutations. :attr neighbourhood: The neighbourhood object to use. :attr permutations: A dictionary that says what cell to take the value from for any given cell.""" resultless_dav = elementary_digits_and_values(neighbourhood, base) index_map = range(len(resultless_dav)) for index, dav in enumerate(resultless_dav): ndav = dict((k, dav[permutation[k]]) for k in neighbourhood.names) other_index = resultless_dav.index(ndav) index_map[index] = other_index return index_map def apply_index_map_values(digits_and_values, index_map): new = [value.copy() for value in digits_and_values] for i, _ in enumerate(digits_and_values): new[index_map[i]]["result_value"] = digits_and_values[i]["result_value"] return new def apply_index_map(results, index_map): if isinstance(results[0], dict): return apply_index_map_values(results, index_map) return [results[index_map[i]] for i in range(len(results))] def flip_offset_to_permutation(neighbourhood, permute_func): """Apply the permute_func, which takes in the offset and returns a new offset to the neighbourhood offsets and return a permutation dictionary that maps each name of a cell to the name of the cell its data is supposed to come from.""" offs_to_name = dict(zip(neighbourhood.offsets, neighbourhood.names)) permutation = dict(zip(neighbourhood.names, neighbourhood.names)) for offset, old_name in offs_to_name.iteritems(): new_offset = permute_func(offset) new_name = offs_to_name[new_offset] permutation[old_name] = new_name return permutation def mirror_by_axis(neighbourhood, axis=[0], base=2): def mirror_axis_permutation(position, axis=tuple(axis)): return tuple(-a if num in axis else a for num, a in enumerate(position)) permutation = flip_offset_to_permutation(neighbourhood, mirror_axis_permutation) return permutation_to_index_map(neighbourhood, permutation, base) @neighbourhood_action("flip vertically") def flip_v(neighbourhood, results, cache={}, base=2): if neighbourhood not in cache: cache[neighbourhood] = mirror_by_axis(neighbourhood, [1], base) return apply_index_map(results, cache[neighbourhood]) @neighbourhood_action("flip horizontally") def flip_h(neighbourhood, results, cache={}, base=2): if neighbourhood not in cache: cache[neighbourhood] = mirror_by_axis(neighbourhood, [0], base) return apply_index_map(results, cache[neighbourhood]) @neighbourhood_action("rotate clockwise") def rotate_clockwise(neighbourhood, results, cache={}, base=2): if neighbourhood not in cache: def rotate((a, b)): return b, -a permutation = flip_offset_to_permutation(neighbourhood, rotate) cache[neighbourhood] = permutation_to_index_map(neighbourhood, permutation, base) return apply_index_map(results, cache[neighbourhood])
{ "content_hash": "2a79f41f9678461a1868cf5c6b3041b9", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 89, "avg_line_length": 38.93877551020408, "alnum_prop": 0.6865828092243187, "repo_name": "timo/zasim", "id": "f0743713349db2dc282c936c9167a66546cda8c1", "size": "5724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zasim/elementarytools.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "423165" }, { "name": "Shell", "bytes": "4509" } ], "symlink_target": "" }
package org.sufficientlysecure.rootcommands; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Mount { protected final File mDevice; protected final File mMountPoint; protected final String mType; protected final Set<String> mFlags; Mount(File device, File path, String type, String flagsStr) { mDevice = device; mMountPoint = path; mType = type; mFlags = new HashSet<String>(Arrays.asList(flagsStr.split(","))); } public File getDevice() { return mDevice; } public File getMountPoint() { return mMountPoint; } public String getType() { return mType; } public Set<String> getFlags() { return mFlags; } @Override public String toString() { return String.format("%s on %s type %s %s", mDevice, mMountPoint, mType, mFlags); } }
{ "content_hash": "6e3281414493df8126d4cd07751a4169", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 89, "avg_line_length": 22.674418604651162, "alnum_prop": 0.6061538461538462, "repo_name": "toiosdeveloper/root-commands", "id": "6f5ef78733260e44b29ee0262a5066ee59781e67", "size": "1710", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "libraries/RootCommands/src/main/java/org/sufficientlysecure/rootcommands/Mount.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Option Infer On Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim models As SolidEdgePart.Models = Nothing Dim model As SolidEdgePart.Model = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument) If partDocument IsNot Nothing Then models = partDocument.Models model = models.Item(1) Dim slots = model.Slots End If Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
{ "content_hash": "1cfcb00be29c93420cb39c55215385a5", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 122, "avg_line_length": 36.486486486486484, "alnum_prop": 0.62, "repo_name": "SolidEdgeCommunity/docs", "id": "7fc3c3e72305ad3ff77bcec4fa2a01f990bff454", "size": "1352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docfx_project/snippets/SolidEdgePart.Model.Slots.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "C#", "bytes": "5048212" }, { "name": "C++", "bytes": "2265" }, { "name": "CSS", "bytes": "148" }, { "name": "PowerShell", "bytes": "180" }, { "name": "Smalltalk", "bytes": "1996" }, { "name": "Visual Basic", "bytes": "10236277" } ], "symlink_target": "" }
package org.vertexium.accumulo; import org.vertexium.accumulo.models.AccumuloEdgeInfo; import org.vertexium.util.LookAheadIterable; import java.util.Iterator; class GetVertexIdsIterable extends LookAheadIterable<AccumuloEdgeInfo, String> { private final Iterable<AccumuloEdgeInfo> edgeInfos; private final String[] labels; public GetVertexIdsIterable(Iterable<AccumuloEdgeInfo> edgeInfos, String[] labels) { this.edgeInfos = edgeInfos; this.labels = labels; } @Override protected boolean isIncluded(AccumuloEdgeInfo edgeInfo, String vertexId) { if (labels == null || labels.length == 0) { return true; } for (String label : labels) { if (edgeInfo.getLabel().equals(label)) { return true; } } return false; } @Override protected String convert(AccumuloEdgeInfo edgeInfo) { return edgeInfo.getVertexId(); } @Override protected Iterator<AccumuloEdgeInfo> createIterator() { return edgeInfos.iterator(); } }
{ "content_hash": "d3e5648fc3396a93c3e712bbf5838fed", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 88, "avg_line_length": 27.871794871794872, "alnum_prop": 0.6614535418583257, "repo_name": "visallo/vertexium", "id": "ac90a773d08bdc2cfb7e939b201157326c7ad6f2", "size": "1087", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "accumulo/graph/src/main/java/org/vertexium/accumulo/GetVertexIdsIterable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "31058" }, { "name": "Dockerfile", "bytes": "448" }, { "name": "Gherkin", "bytes": "747158" }, { "name": "Java", "bytes": "4006071" }, { "name": "Shell", "bytes": "346" }, { "name": "XSLT", "bytes": "726" } ], "symlink_target": "" }
<?php /** * @author @jenschude <jens.schulze@commercetools.de> */ namespace Commercetools\Core\Request\Channels; use Commercetools\Core\Model\Common\Context; use Commercetools\Core\Request\AbstractUpdateRequest; use Commercetools\Core\Model\Channel\Channel; use Commercetools\Core\Response\ApiResponseInterface; use Commercetools\Core\Model\MapperInterface; /** * @package Commercetools\Core\Request\Channels * @link https://docs.commercetools.com/http-api-projects-channels.html#update-channel * @method Channel mapResponse(ApiResponseInterface $response) * @method Channel mapFromResponse(ApiResponseInterface $response, MapperInterface $mapper = null) */ class ChannelUpdateRequest extends AbstractUpdateRequest { protected $resultClass = Channel::class; /** * @param string $id * @param int $version * @param array $actions * @param Context $context */ public function __construct($id, $version, array $actions = [], Context $context = null) { parent::__construct(ChannelsEndpoint::endpoint(), $id, $version, $actions, $context); } /** * @param string $id * @param int $version * @param Context $context * @return static */ public static function ofIdAndVersion($id, $version, Context $context = null) { return new static($id, $version, [], $context); } }
{ "content_hash": "7ab55699ed4f601ec794be79bd499eb9", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 98, "avg_line_length": 30.533333333333335, "alnum_prop": 0.7008733624454149, "repo_name": "sphereio/sphere-php-sdk", "id": "00879694d932c1d777625f56aa62c535f0a28488", "size": "1374", "binary": false, "copies": "2", "ref": "refs/heads/renovate/all", "path": "src/Core/Request/Channels/ChannelUpdateRequest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "288" }, { "name": "CSS", "bytes": "7510" }, { "name": "Cucumber", "bytes": "205537" }, { "name": "HTML", "bytes": "49434" }, { "name": "JavaScript", "bytes": "35176" }, { "name": "PHP", "bytes": "1743251" }, { "name": "Shell", "bytes": "1990" } ], "symlink_target": "" }
package org.jetbrains.jps.incremental.storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.io.IOUtil; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.builders.BuildTargetLoader; import org.jetbrains.jps.builders.BuildTargetType; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author nik */ public class BuildTargetTypeState { private static final int VERSION = 1; private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildTargetTypeState"); private final Map<BuildTarget<?>, Integer> myTargetIds; private final List<Pair<String, Integer>> myStaleTargetIds; private final ConcurrentMap<BuildTarget<?>, BuildTargetConfiguration> myConfigurations; private final BuildTargetType<?> myTargetType; private final BuildTargetsState myTargetsState; private final File myTargetsFile; private volatile long myAverageTargetBuildTimeMs = -1; public BuildTargetTypeState(BuildTargetType<?> targetType, BuildTargetsState state) { myTargetType = targetType; myTargetsState = state; myTargetsFile = new File(state.getDataPaths().getTargetTypeDataRoot(targetType), "targets.dat"); myConfigurations = new ConcurrentHashMap<>(16, 0.75f, 1); myTargetIds = new HashMap<>(); myStaleTargetIds = new ArrayList<>(); load(); } private boolean load() { if (!myTargetsFile.exists()) { return false; } try (DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(myTargetsFile)))) { int version = input.readInt(); int size = input.readInt(); BuildTargetLoader<?> loader = myTargetType.createLoader(myTargetsState.getModel()); while (size-- > 0) { String stringId = IOUtil.readString(input); int intId = input.readInt(); myTargetsState.markUsedId(intId); BuildTarget<?> target = loader.createTarget(stringId); if (target != null) { myTargetIds.put(target, intId); } else { myStaleTargetIds.add(Pair.create(stringId, intId)); } } if (version >= 1) { myAverageTargetBuildTimeMs = input.readLong(); } return true; } catch (IOException e) { LOG.info("Cannot load " + myTargetType.getTypeId() + " targets data: " + e.getMessage(), e); return false; } } public synchronized void save() { FileUtil.createParentDirs(myTargetsFile); try (DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myTargetsFile)))) { output.writeInt(VERSION); output.writeInt(myTargetIds.size() + myStaleTargetIds.size()); for (Map.Entry<BuildTarget<?>, Integer> entry : myTargetIds.entrySet()) { IOUtil.writeString(entry.getKey().getId(), output); output.writeInt(entry.getValue()); } for (Pair<String, Integer> pair : myStaleTargetIds) { IOUtil.writeString(pair.first, output); output.writeInt(pair.second); } output.writeLong(myAverageTargetBuildTimeMs); } catch (IOException e) { LOG.info("Cannot save " + myTargetType.getTypeId() + " targets data: " + e.getMessage(), e); } } public synchronized List<Pair<String, Integer>> getStaleTargetIds() { return new ArrayList<>(myStaleTargetIds); } public synchronized void removeStaleTarget(String targetId) { myStaleTargetIds.removeIf(pair -> pair.first.equals(targetId)); } public synchronized int getTargetId(BuildTarget<?> target) { if (!myTargetIds.containsKey(target)) { myTargetIds.put(target, myTargetsState.getFreeId()); } return myTargetIds.get(target); } public void setAverageTargetBuildTime(long timeInMs) { myAverageTargetBuildTimeMs = timeInMs; } /** * Returns average time required to rebuild a target of this type from scratch or {@code -1} if such information isn't available. */ public long getAverageTargetBuildTime() { return myAverageTargetBuildTimeMs; } public BuildTargetConfiguration getConfiguration(BuildTarget<?> target) { BuildTargetConfiguration configuration = myConfigurations.get(target); if (configuration == null) { configuration = new BuildTargetConfiguration(target, myTargetsState); final BuildTargetConfiguration existing = myConfigurations.putIfAbsent(target, configuration); if (existing != null) { configuration = existing; } } return configuration; } }
{ "content_hash": "79abc926c5207a086254333ff11a5a4e", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 131, "avg_line_length": 35.83458646616541, "alnum_prop": 0.7085606378514477, "repo_name": "msebire/intellij-community", "id": "8497805103bd855dd2e193d8403999b140209aaf", "size": "5366", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Oro\Bundle\FilterBundle\Tests\Unit\Provider; use Oro\Bundle\FilterBundle\Provider\DateModifierProvider; class DateModifierProviderTest extends \PHPUnit_Framework_TestCase { /** @var DateModifierProvider */ protected $dateModifierProvider; protected function setUp() { $this->dateModifierProvider = new DateModifierProvider(); } public function testDateParts() { $parts = $this->dateModifierProvider->getDateParts(); $this->assertNotEmpty($parts); $this->assertCount(9, $parts); } public function testDateVariables() { $vars = $this->dateModifierProvider->getDateVariables(); $this->assertNotEmpty($vars); $this->assertCount(8, $vars); } }
{ "content_hash": "56b962f6c577b4092c0bb8b947cb905a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 66, "avg_line_length": 25.366666666666667, "alnum_prop": 0.6727989487516426, "repo_name": "hugeval/platform", "id": "160023e93907e8789c50d833ca73f87145bee054", "size": "761", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/Oro/Bundle/FilterBundle/Tests/Unit/Provider/DateModifierProviderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "585517" }, { "name": "Cucumber", "bytes": "660" }, { "name": "HTML", "bytes": "1354850" }, { "name": "JavaScript", "bytes": "4630927" }, { "name": "PHP", "bytes": "19668529" } ], "symlink_target": "" }
package org.apache.felix.ipojo.manipulator; import org.apache.felix.ipojo.manipulator.util.Strings; import org.apache.felix.ipojo.metadata.Element; /** * Component Info. * Represent a component type to be manipulated or already manipulated. * @author <a href="mailto:felix-dev@incubator.apache.org">Felix Project Team</a> */ public class ManipulationUnit { private Element m_componentMetadata; private String m_resourcePath; private String m_className; /** * Constructor. * @param resourcePath class name * @param meta component type metadata */ public ManipulationUnit(String resourcePath, Element meta) { m_resourcePath = resourcePath; m_componentMetadata = meta; m_className = Strings.asClassName(resourcePath); } /** * @return Component Type metadata. */ public Element getComponentMetadata() { return m_componentMetadata; } /** * @return Resource path */ public String getResourcePath() { return m_resourcePath; } /** * @return Fully qualified class name */ public String getClassName() { return m_className; } }
{ "content_hash": "baa1a66be1943d55e318da4e0cf75be8", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 81, "avg_line_length": 22.49056603773585, "alnum_prop": 0.6585570469798657, "repo_name": "apache/felix-dev", "id": "c5558b6e8b862add165fd9ee73c3d61b4b57ee92", "size": "1999", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ipojo/manipulator/manipulator/src/main/java/org/apache/felix/ipojo/manipulator/ManipulationUnit.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53237" }, { "name": "Groovy", "bytes": "9231" }, { "name": "HTML", "bytes": "372812" }, { "name": "Java", "bytes": "28836360" }, { "name": "JavaScript", "bytes": "248796" }, { "name": "Scala", "bytes": "40378" }, { "name": "Shell", "bytes": "12628" }, { "name": "XSLT", "bytes": "151258" } ], "symlink_target": "" }
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts; import java.util.Collections; import java.util.List; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.geometry.Point; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.RunnableWithResult; import org.eclipse.gef.AccessibleEditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.requests.DirectEditRequest; import org.eclipse.gef.tools.DirectEditManager; import org.eclipse.gmf.runtime.common.ui.services.parser.IParser; import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserEditStatus; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions; import org.eclipse.gmf.runtime.diagram.ui.editparts.CompartmentEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.LabelDirectEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry; import org.eclipse.gmf.runtime.diagram.ui.label.ILabelDelegate; import org.eclipse.gmf.runtime.diagram.ui.label.WrappingLabelDelegate; import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants; import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; import org.eclipse.gmf.runtime.notation.FontStyle; import org.eclipse.gmf.runtime.notation.NotationPackage; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.gmf.tooling.runtime.directedit.TextDirectEditManager2; import org.eclipse.gmf.tooling.runtime.draw2d.labels.SimpleLabelDelegate; import org.eclipse.gmf.tooling.runtime.edit.policies.DefaultNodeLabelDragPolicy; import org.eclipse.gmf.tooling.runtime.edit.policies.labels.IRefreshableFeedbackEditPolicy; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.viewers.ICellEditorValidator; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.MediatorFigureSelectionListener; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.EsbTextSelectionEditPolicy; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbParserProvider; /** * @generated */ public class SpringMediatorDescriptionEditPart extends CompartmentEditPart implements ITextAwareEditPart { /** * @generated */ public static final int VISUAL_ID = 5174; /** * @generated */ private DirectEditManager manager; /** * @generated */ private IParser parser; /** * @generated */ private List<?> parserElements; /** * @generated */ private String defaultText; /** * @generated */ private ILabelDelegate labelDelegate; /** * @generated */ public SpringMediatorDescriptionEditPart(View view) { super(view); } /** * @generated */ protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new EsbTextSelectionEditPolicy()); installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new LabelDirectEditPolicy()); installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE, new DefaultNodeLabelDragPolicy()); } /** * @generated */ protected String getLabelTextHelper(IFigure figure) { if (figure instanceof WrappingLabel) { return ((WrappingLabel) figure).getText(); } else if (figure instanceof Label) { return ((Label) figure).getText(); } else { return getLabelDelegate().getText(); } } /** * @generated */ protected void setLabelTextHelper(IFigure figure, String text) { if (figure instanceof WrappingLabel) { ((WrappingLabel) figure).setText(text); } else if (figure instanceof Label) { ((Label) figure).setText(text); } else { getLabelDelegate().setText(text); } } /** * @generated */ protected Image getLabelIconHelper(IFigure figure) { if (figure instanceof WrappingLabel) { return ((WrappingLabel) figure).getIcon(); } else if (figure instanceof Label) { return ((Label) figure).getIcon(); } else { return getLabelDelegate().getIcon(0); } } /** * @generated */ protected void setLabelIconHelper(IFigure figure, Image icon) { if (figure instanceof WrappingLabel) { ((WrappingLabel) figure).setIcon(icon); return; } else if (figure instanceof Label) { ((Label) figure).setIcon(icon); return; } else { getLabelDelegate().setIcon(icon, 0); } } /** * @generated NOT */ public void setLabel(WrappingLabel figure) { figure.addMouseListener(new MediatorFigureSelectionListener(this .getParent())); unregisterVisuals(); setFigure(figure); defaultText = getLabelTextHelper(figure); registerVisuals(); refreshVisuals(); } /** * @generated */ @SuppressWarnings("rawtypes") protected List getModelChildren() { return Collections.EMPTY_LIST; } /** * @generated */ public IGraphicalEditPart getChildBySemanticHint(String semanticHint) { return null; } /** * @generated */ protected EObject getParserElement() { return resolveSemanticElement(); } /** * @generated */ protected Image getLabelIcon() { return null; } /** * @generated */ protected String getLabelText() { String text = null; EObject parserElement = getParserElement(); if (parserElement != null && getParser() != null) { text = getParser().getPrintString( new EObjectAdapter(parserElement), getParserOptions().intValue()); } if (text == null || text.length() == 0) { text = defaultText; } return text; } /** * @generated */ public void setLabelText(String text) { setLabelTextHelper(getFigure(), text); refreshSelectionFeedback(); } /** * @generated */ public String getEditText() { if (getParserElement() == null || getParser() == null) { return ""; //$NON-NLS-1$ } return getParser().getEditString( new EObjectAdapter(getParserElement()), getParserOptions().intValue()); } /** * @generated */ protected boolean isEditable() { return getParser() != null; } /** * @generated */ public ICellEditorValidator getEditTextValidator() { return new ICellEditorValidator() { public String isValid(final Object value) { if (value instanceof String) { final EObject element = getParserElement(); final IParser parser = getParser(); try { IParserEditStatus valid = (IParserEditStatus) getEditingDomain() .runExclusive( new RunnableWithResult.Impl<IParserEditStatus>() { public void run() { setResult(parser .isValidEditString( new EObjectAdapter( element), (String) value)); } }); return valid.getCode() == ParserEditStatus.EDITABLE ? null : valid.getMessage(); } catch (InterruptedException ie) { ie.printStackTrace(); } } // shouldn't get here return null; } }; } /** * @generated */ public IContentAssistProcessor getCompletionProcessor() { if (getParserElement() == null || getParser() == null) { return null; } return getParser().getCompletionProcessor( new EObjectAdapter(getParserElement())); } /** * @generated */ public ParserOptions getParserOptions() { return ParserOptions.NONE; } /** * @generated */ public IParser getParser() { if (parser == null) { parser = EsbParserProvider .getParser( EsbElementTypes.SpringMediator_3507, getParserElement(), EsbVisualIDRegistry .getType(org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SpringMediatorDescriptionEditPart.VISUAL_ID)); } return parser; } /** * @generated */ protected DirectEditManager getManager() { if (manager == null) { setManager(new TextDirectEditManager2(this, null, EsbEditPartFactory.getTextCellEditorLocator(this))); } return manager; } /** * @generated */ protected void setManager(DirectEditManager manager) { this.manager = manager; } /** * @generated */ protected void performDirectEdit() { getManager().show(); } /** * @generated */ protected void performDirectEdit(Point eventLocation) { if (getManager().getClass() == TextDirectEditManager2.class) { ((TextDirectEditManager2) getManager()).show(eventLocation .getSWTPoint()); } } /** * @generated */ private void performDirectEdit(char initialCharacter) { if (getManager() instanceof TextDirectEditManager) { ((TextDirectEditManager) getManager()).show(initialCharacter); } else // if (getManager() instanceof TextDirectEditManager2) { ((TextDirectEditManager2) getManager()).show(initialCharacter); } else // { performDirectEdit(); } } /** * @generated */ protected void performDirectEditRequest(Request request) { final Request theRequest = request; try { getEditingDomain().runExclusive(new Runnable() { public void run() { if (isActive() && isEditable()) { if (theRequest .getExtendedData() .get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR) instanceof Character) { Character initialChar = (Character) theRequest .getExtendedData() .get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR); performDirectEdit(initialChar.charValue()); } else if ((theRequest instanceof DirectEditRequest) && (getEditText().equals(getLabelText()))) { DirectEditRequest editRequest = (DirectEditRequest) theRequest; performDirectEdit(editRequest.getLocation()); } else { performDirectEdit(); } } } }); } catch (InterruptedException e) { e.printStackTrace(); } } /** * @generated */ protected void refreshVisuals() { super.refreshVisuals(); refreshLabel(); refreshFont(); refreshFontColor(); refreshUnderline(); refreshStrikeThrough(); } /** * @generated */ protected void refreshLabel() { setLabelTextHelper(getFigure(), getLabelText()); setLabelIconHelper(getFigure(), getLabelIcon()); refreshSelectionFeedback(); } /** * @generated */ protected void refreshUnderline() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null && getFigure() instanceof WrappingLabel) { ((WrappingLabel) getFigure()).setTextUnderline(style.isUnderline()); } } /** * @generated */ protected void refreshStrikeThrough() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null && getFigure() instanceof WrappingLabel) { ((WrappingLabel) getFigure()).setTextStrikeThrough(style .isStrikeThrough()); } } /** * @generated */ protected void refreshFont() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null) { FontData fontData = new FontData(style.getFontName(), style.getFontHeight(), (style.isBold() ? SWT.BOLD : SWT.NORMAL) | (style.isItalic() ? SWT.ITALIC : SWT.NORMAL)); setFont(fontData); } } /** * @generated */ private void refreshSelectionFeedback() { requestEditPolicyFeedbackRefresh(EditPolicy.PRIMARY_DRAG_ROLE); requestEditPolicyFeedbackRefresh(EditPolicy.SELECTION_FEEDBACK_ROLE); } /** * @generated */ private void requestEditPolicyFeedbackRefresh(String editPolicyKey) { Object editPolicy = getEditPolicy(editPolicyKey); if (editPolicy instanceof IRefreshableFeedbackEditPolicy) { ((IRefreshableFeedbackEditPolicy) editPolicy).refreshFeedback(); } } /** * @generated */ protected void setFontColor(Color color) { getFigure().setForegroundColor(color); } /** * @generated */ protected void addSemanticListeners() { if (getParser() instanceof ISemanticParser) { EObject element = resolveSemanticElement(); parserElements = ((ISemanticParser) getParser()) .getSemanticElementsBeingParsed(element); for (int i = 0; i < parserElements.size(); i++) { addListenerFilter( "SemanticModel" + i, this, (EObject) parserElements.get(i)); //$NON-NLS-1$ } } else { super.addSemanticListeners(); } } /** * @generated */ protected void removeSemanticListeners() { if (parserElements != null) { for (int i = 0; i < parserElements.size(); i++) { removeListenerFilter("SemanticModel" + i); //$NON-NLS-1$ } } else { super.removeSemanticListeners(); } } /** * @generated */ protected AccessibleEditPart getAccessibleEditPart() { if (accessibleEP == null) { accessibleEP = new AccessibleGraphicalEditPart() { public void getName(AccessibleEvent e) { e.result = getLabelTextHelper(getFigure()); } }; } return accessibleEP; } /** * @generated */ private View getFontStyleOwnerView() { return getPrimaryView(); } /** * @generated */ private ILabelDelegate getLabelDelegate() { if (labelDelegate == null) { IFigure label = getFigure(); if (label instanceof WrappingLabel) { labelDelegate = new WrappingLabelDelegate((WrappingLabel) label); } else { labelDelegate = new SimpleLabelDelegate((Label) label); } } return labelDelegate; } /** * @generated */ @Override public Object getAdapter(Class key) { if (ILabelDelegate.class.equals(key)) { return getLabelDelegate(); } return super.getAdapter(key); } /** * @generated */ protected void addNotationalListeners() { super.addNotationalListeners(); addListenerFilter("PrimaryView", this, getPrimaryView()); //$NON-NLS-1$ } /** * @generated */ protected void removeNotationalListeners() { super.removeNotationalListeners(); removeListenerFilter("PrimaryView"); //$NON-NLS-1$ } /** * @generated */ protected void handleNotificationEvent(Notification event) { Object feature = event.getFeature(); if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) { Integer c = (Integer) event.getNewValue(); setFontColor(DiagramColorRegistry.getInstance().getColor(c)); } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals( feature)) { refreshUnderline(); } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough() .equals(feature)) { refreshStrikeThrough(); } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals( feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals( feature) || NotationPackage.eINSTANCE.getFontStyle_Bold() .equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Italic().equals( feature)) { refreshFont(); } else { if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) { refreshLabel(); } if (getParser() instanceof ISemanticParser) { ISemanticParser modelParser = (ISemanticParser) getParser(); if (modelParser.areSemanticElementsAffected(null, event)) { removeSemanticListeners(); if (resolveSemanticElement() != null) { addSemanticListeners(); } refreshLabel(); } } } super.handleNotificationEvent(event); } /** * @generated */ protected IFigure createFigure() { // Parent should assign one using setLabel() method return null; } }
{ "content_hash": "bac155070a37c289bdc1ad12e01d7f88", "timestamp": "", "source": "github", "line_count": 630, "max_line_length": 124, "avg_line_length": 25.55873015873016, "alnum_prop": 0.7038877158117004, "repo_name": "rajeevanv89/developer-studio", "id": "e92fd897c837f12db78925b675b3c978df1bf4bb", "size": "16102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/SpringMediatorDescriptionEditPart.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "884" }, { "name": "CSS", "bytes": "62302" }, { "name": "GAP", "bytes": "14192" }, { "name": "Java", "bytes": "78811689" }, { "name": "JavaScript", "bytes": "171473" }, { "name": "PHP", "bytes": "4691550" }, { "name": "Shell", "bytes": "429" }, { "name": "XSLT", "bytes": "10672" } ], "symlink_target": "" }
package edu.cmu.lti.oaqa.ecd.example; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; public class ThirdPhaseAnnotatorA1 extends JCasAnnotator_ImplBase { private String pa; private String pb; private String pc; private String pd; private String foo; @Override public void initialize(UimaContext context) throws ResourceInitializationException { this.foo = (String) context.getConfigParameterValue("foo"); if (!foo.equals("bar")) { throw new ResourceInitializationException( new RuntimeException("Expected foo == bar")); } this.pa = (String) context.getConfigParameterValue("parameter-a"); if (pa == null) { throw new ResourceInitializationException( new RuntimeException("Expected parameter-a != null")); } this.pb = (String) context.getConfigParameterValue("parameter-b"); if (pb == null) { throw new ResourceInitializationException( new RuntimeException("Expected parameter-b != null")); } this.pc = (String) context.getConfigParameterValue("parameter-c"); if (pc == null) { throw new ResourceInitializationException( new RuntimeException("Expected parameter-c != null")); } this.pd = (String) context.getConfigParameterValue("parameter-d"); if (pd == null) { throw new ResourceInitializationException( new RuntimeException("Expected parameter-d != null")); } } @Override public void process(JCas jcas) throws AnalysisEngineProcessException { System.out.printf("process: %s(%s,%s,%s,%s,%s)\n", getClass().getSimpleName(), foo,pa,pb,pc,pd); } }
{ "content_hash": "79a0f75d46116806bae1ddb1e3e0c5dc", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 86, "avg_line_length": 36.43396226415094, "alnum_prop": 0.6763335059554635, "repo_name": "oaqa/uima-ecd", "id": "31f727cf2a1c850055dac7eac65e899bd8fee354", "size": "2564", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/edu/cmu/lti/oaqa/ecd/example/ThirdPhaseAnnotatorA1.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "200947" } ], "symlink_target": "" }
import os import sys import random from os import path from termcolor import colored from people import Staff, Fellow from rooms import Office, LivingSpace from database.schema import People, DataBaseConnection, Rooms, Unallocated sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) white_line = colored('-' * 60, 'white') class Dojo(object): def __init__(self): self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self.office_unallocated = [] self.living_unallocated = [] self.allocated = [] self.all_people = self.fellows + self.staff def get_room(self, rooms): """A function to generate a list of random rooms with space. :param rooms: :return: room_name """ # a room is only available if it's capacity is not exceeded available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity] # return False if all rooms are full if available_rooms: chosen_room = random.choice(available_rooms) return chosen_room.room_name return False # choose a room from the list of available rooms. def create_room(self, room_name, room_type): """Creates a room in the system, either office or living space. :param room_name: A string representing a room's name. :param room_type: A string representing a room's type (Office or Living space) """ if room_type is 'office': if room_name not in [room.room_name for room in self.offices]: room = Office(room_name=room_name, room_type=room_type) self.offices.append(room) self.all_rooms.append(room) print(white_line) print(colored('An office called' + ' ' + room_name + ' ' + 'has been successfully created!', 'cyan')) else: print(white_line) print(colored( 'An office with that name already exists!', 'red')) if room_type is 'livingspace': if room_name not in [room.room_name for room in self.livingrooms]: room = LivingSpace(room_name=room_name, room_type=room_type) # add object to list( has both room_name and room_type) self.livingrooms.append(room) self.all_rooms.append(room) print(white_line) print(colored('An room called' + ' ' + room_name + ' ' + 'has been successfully created!', 'cyan')) else: print(white_line) print(colored( 'A living room with that name already exists!', 'red')) def add_person(self, first_name, last_name, occupation, wants_accommodation=None): """Adds person to the system and allocates them office space and room space if they are a fellow and requested for accommodation. :param first_name: A string representing the person's first name. :param last_name: A string representing the person's second name. :param occupation: A string representing the persons's type (Fellow/Staff) :param wants_accommodation: An optional string representing a fellow's accommodation """ self.first_name = first_name self.last_name = last_name self.occupation = occupation self.wants_accommodation = wants_accommodation self.person_name = self.first_name + self.last_name if occupation == 'Fellow': if self.person_name not in [person.first_name + person.last_name for person in self.fellows]: person = Fellow( first_name, last_name, occupation, wants_accommodation) self.fellows.append(person) print(white_line) print(colored(first_name + ' ' + last_name + ' has been added successfully!', 'cyan')) # check if fellow wants accommodation, set to 'N' by default accommodation = person.wants_accommodation if accommodation is None or accommodation != 'Y': # if a fellow wants no accommodation grant just office work_room = self.get_room(self.offices) # if there is no available office space if work_room: for room in self.offices: if room.room_name == work_room: room.occupants.append(person) print(white_line) print(colored('A ' + person.occupation + ' ' + person.first_name + ' has been added to ' + work_room, 'cyan')) else: # Add person unallocated if no office space. self.office_unallocated.append(person) print(white_line) print(colored('Office space unavailable, ' 'added to office waiting list', 'red')) else: # Add person unallocated if no office space. work_room = self.get_room(self.offices) living_room = self.get_room(self.livingrooms) # if there is no available office space if work_room: for room in self.offices: if room.room_name == work_room: room.occupants.append(person) print(white_line) print(colored('A ' + person.occupation + ' ' + person.first_name + ' has been added to ' + work_room, 'cyan')) else: # Add person unallocated if no office space. self.office_unallocated.append(person) print(white_line) print(colored('Office space unavailable, ' 'added to office waiting list', 'red')) if living_room: for room in self.livingrooms: if room.room_name == living_room: room.occupants.append(person) print(white_line) print(colored('A ' + person.occupation + ' ' + person.first_name + ' has been added to ' + living_room, 'cyan')) else: # Add person unallocated if no office space. self.living_unallocated.append(person) print(white_line) print(colored('Living space unavailable, ' 'added to accommodation waiting list', 'red')) else: print(white_line) print(colored('A fellow with that name already exists', 'red')) if occupation == 'Staff': if self.person_name not in [person.first_name + person.last_name for person in self.staff]: person = Staff( first_name, last_name, occupation, wants_accommodation) self.staff.append(person) print(white_line) print(colored(first_name + ' ' + last_name + ' has been added successfully!', 'cyan')) accommodation = person.wants_accommodation if accommodation is None or accommodation != 'Y': work_room = self.get_room(self.offices) # if there is no available office space if work_room: for room in self.offices: if room.room_name == work_room: room.occupants.append(person) print(white_line) print(colored('A ' + person.occupation + ' ' + person.first_name + ' has been added to ' + work_room, 'cyan')) else: # Add person unallocated if no office space. self.office_unallocated.append(person) print(white_line) print(colored('Office space unavailable, ' 'added to office waiting list', 'red')) else: print(colored('Staff cannot get accommodation!', 'red')) # Add person unallocated if no office space. work_room = self.get_room(self.offices) # if there is no available office space if work_room: for room in self.offices: if room.room_name == work_room: room.occupants.append(person) print(white_line) print(colored('A ' + person.occupation + ' ' + person.first_name + ' has been added to ' + work_room, 'cyan')) return'Staff cannot get accommodation' else: # Add person unallocated if no office space. self.office_unallocated.append(person) print(white_line) print(colored('Office space unavailable, ' 'added to office waiting list', 'red')) else: print(white_line) print(colored('A member of staff with that name already exists', 'red')) def print_room(self, room_name): """Gets a room name as an argument and returns a status of the room's existence and occupants if room exists :param room_name: A string representing the name of the room. """ # check if the requested room is available in created rooms. data = "" if room_name not in [room.room_name for room in self.all_rooms]: print(white_line) print(colored('The room you entered is not in the system!', 'red')) return 'The room you entered is not in the system!' for room in self.all_rooms: if room.room_name == room_name: # data += ( # "{0} - {1}\n".format(room.room_name, room.room_type)) # data += white_line + '\n' print(room.room_name + '(' + room.room_type.title() + ')') print(white_line) print('Employee id' + ' ' + 'Employee Name') print(white_line) # check if room has occupants if room.occupants: for person in room.occupants: print(person.id + ' ' + person.first_name + ' ' + person.last_name) data += person.first_name + ' ' + person.last_name + '\n' else: print(colored('Room has currently no occupants!', 'red')) data += 'Room has currently no occupants!.' return data def print_allocation(self, filename): """Gets all the people in the dojo facility who have been awarded room and office allocations. """ if self.all_rooms: # writing to file write_to_file = '' for room in self.all_rooms: if room.occupants: print(colored(room.room_name + '(' + room.room_type.title() + ')', 'cyan')) write_to_file += room.room_name + '\n' print(white_line) print('Employee id' + ' ' + 'Employee Name') print(white_line) for person in room.occupants: person_name = person.first_name + ' ' + person.last_name write_to_file += person_name + '\n' print(person.id + ' ' + person.first_name + ' ' + person.last_name) # check if user has opted to print list if filename: file_name = filename + ".txt" file_output = open(file_name, 'w') file_output.write(write_to_file) file_output.close() return else: print(colored(room.room_name + '(' + room.room_type.title() + ')', 'cyan')) print(colored('This room has no occupants', 'red')) else: print(colored('There are no allocations in system', 'red')) def print_unallocated(self, filename): # collect all file info as a string write_to_file = '' if self.office_unallocated: print(white_line) print(colored('OFFICES WAITING LIST', 'cyan')) print(white_line) print('Employee id' + ' ' + 'Employee Name') print(white_line) for person in self.office_unallocated: if person: person_name = person.first_name + ' ' + person.last_name write_to_file += person_name + '\n' print(str(person.id) + ' ' + person.first_name + ' ' + person.last_name) # check if user has opted to print list if filename: file_name = filename + ".txt" file_output = open(file_name, 'w') file_output.write(write_to_file) file_output.close() if self.living_unallocated: print(white_line) print(colored('LIVING ROOMS WAITING LIST', 'cyan')) print(white_line) print('Employee id' + ' ' + 'Employee Name') print(white_line) for person in self.living_unallocated: person_name = person.first_name + ' ' + person.last_name write_to_file += person_name + '\n' print(str(person.id) + ' ' + person.first_name + ' ' + person.last_name) # check if user has opted to print list if filename: file_name = filename + ".txt" file_output = open(file_name, 'w') file_output.write(write_to_file) file_output.close() else: print(white_line) print(colored('Currently no pending allocations!', 'cyan')) def get_current_room(self, person_id, room_type): for room in self.all_rooms: if room.room_type == room_type: for occupant in room.occupants: if occupant.id == person_id: return room return 'Person does not have a room of type {}'.format(room_type) def unallocate_person(self, person_id, intended_room_type): """Removes a person from the room they are currently assigned to. :param intended_room_type: :param person_id: A string representing the person's id. :return: person: The person to be reallocated. """ for room in self.all_rooms: if room.room_type == intended_room_type: for occupant in room.occupants: if occupant.id == person_id: person = occupant room.occupants.remove(occupant) return person def get_room_type(self, room_name): """Gets the room_type of the room to which reallocation is intended :param room_name: The name of the room to reallocate to. :return: room_type: The name type of the room to reallocate """ for room in self.all_rooms: if room_name == room.room_name: if room.room_type == 'office': return room.room_type, self.office_unallocated else: return room.room_type, self.living_unallocated @staticmethod def check_current_room_object(current_room): """Catches the error in current room to prevent passing of a string to function call in reallocate_person :param current_room: A string representing the room currently occupied by a person :return: boolean: This depends on whether current room is string or object. """ try: if current_room.__dict__: return True except AttributeError: return False def reallocate_person(self, person_id, room_name): """Reallocates a person to a new room. :param person_id: A string representing a person's id. :param room_name: A string representing the name of the room to which reallocation is intended. """ self.all_people = self.staff + self.fellows if room_name in [room.room_name for room in self.all_rooms]: for person in self.all_people: if person_id == person.id: intended_room_type, unallocated =\ self.get_room_type(room_name) current_room = self.get_current_room(person_id, intended_room_type) if person not in unallocated: for room in self.all_rooms: if room_name == room.room_name: if room.room_type ==\ intended_room_type \ and len(room.occupants) \ < room.room_capacity: if self.check_current_room_object(current_room): if room_name != current_room.room_name: person = self.unallocate_person( person_id, intended_room_type) room.occupants.append(person) print(white_line) return colored( 'reallocation successful!,' 'new room: ' + room_name, 'cyan') else: return colored( 'Person already occupies that' ' room!', 'red') else: return colored( 'Reallocation for similar ' 'room_types only!', 'red') return colored('That room is fully occupied', 'red') else: return colored('Only persons with rooms can be ' 'reallocated!', 'red') return colored( 'There is no person in the system with such an id!', 'red') else: return colored('The room specified does not exist!', 'red') def load_people(self, file_name): """Loads people from a text file :param file_name: A string representing the name of the file from which the loading should take place """ try: with open(file_name, 'r') as list_file: people = list_file.readlines() for person in people: attributes = person.split() if attributes: first_name = attributes[0].title() last_name = attributes[1].title() occupation = attributes[2].title() if len(attributes) == 4: wants_accommodation = attributes[3] self.add_person(first_name, last_name, occupation, wants_accommodation) else: self.add_person(first_name, last_name, occupation) except IOError: print(colored('There exists no file with such a name!')) def save_state(self, db_name=None): """Persists all the data stored in the app to a SQLite database. :param db_name: The name of the database to create. """ if path.exists('default_amity_db.db'): os.remove('default_amity_db.db') if path.exists(str(db_name) + '.db'): os.remove(str(db_name) + '.db') if db_name is None: connection = DataBaseConnection() else: connection = DataBaseConnection(db_name) session = connection.Session() self.all_people = self.staff + self.fellows if self.all_people: print(colored('saving people to database.....', 'yellow')) for person in self.all_people: employee = People( person.id, person.first_name, person.last_name, person.occupation, person.wants_accommodation) session.add(employee) session.commit() else: print(colored('There are currently no people at the dojo!', 'red')) if self.all_rooms: print(colored('saving rooms to database....', 'yellow')) for room in self.all_rooms: room_occupants = ",".join([str(person.id) for person in room.occupants]) space = Rooms(room.room_name, room.room_type, room.room_capacity, room_occupants) session.add(space) session.commit() else: print(colored('There currently no rooms in the dojo!', 'red')) unallocated = self.office_unallocated + self.living_unallocated if unallocated: print(colored('saving unallocated to database....', 'yellow')) for person in self.office_unallocated: room_unallocated = 'Office' employee = Unallocated(person.id, person.first_name, person.last_name, person.occupation, room_unallocated) session.add(employee) session.commit() for person in self.living_unallocated: room_unallocated = 'Living space' employee = Unallocated(person.id, person.first_name, person.last_name, person.occupation, room_unallocated) session.add(employee) session.commit() else: print(colored('Currently there are no pending allocations!', 'cyan')) print('Data persisted to {} database successfully!'. format(connection.db_name)) def load_state(self, db_name): """ Loads data from a database into the application. :param db_name: The name of the database from which to load the data. """ # check if file is in root directory. # path_to_db = os.path.join('../', db_name + '.db') base_path = os.path.dirname(__file__) file_path = os.path.abspath(os.path.join(base_path, '..', db_name + '.db')) if not os.path.isfile(file_path): print(colored("Database does not exist.", 'red')) else: connection = DataBaseConnection(db_name) session = connection.Session() saved_people = session.query(People).all() saved_rooms = session.query(Rooms).all() saved_unallocated = session.query(Unallocated).all() if saved_people: for person in saved_people: data = {'id': person.person_id, 'first_name': person.first_name, 'last_name': person.last_name, 'occupation': person.occupation, 'wants_accommodation': person.wants_accommodation} if person.occupation == 'Staff': person = Staff(**data) self.staff.append(person) if person.occupation == 'Fellow': person = Fellow(**data) self.fellows.append(person) else: print(colored('No saved people in the database', 'red')) if saved_rooms: self.all_people = self.staff + self.fellows for room in saved_rooms: if room.room_type == 'office': if room.room_name \ not in [room.room_name for room in self.offices]: space = Office(room.room_name, room.room_type) occupants = [person_id for person_id in room.room_occupants.split(",") if person_id] self.all_rooms.append(space) if occupants: for occupant in occupants: person = self.get_person_object( occupant, self.all_people) space.occupants.append(person) if room.room_type == 'livingspace': if room.room_name \ not in [room.room_name for room in self.offices]: space = LivingSpace(room.room_name, room.room_type) occupants = [person_id for person_id in room.room_occupants.split(",") if person_id] self.all_rooms.append(space) if occupants: for occupant in occupants: person = self.get_person_object(occupant, self.all_people) space.occupants.append(person) print(colored('Rooms successfully loaded.', 'cyan')) else: print(colored('No saved rooms in the database.', 'red')) if saved_unallocated: for person in saved_unallocated: if person.room_unallocated == 'Office' and\ person not in self.office_unallocated: self.all_people = self.staff + self.fellows person_object = self.get_person_object( person.person_id, self.all_people) self.office_unallocated.append(person_object) if person.room_unallocated == 'Living space' and\ person not in self.living_unallocated: person_object = self.get_person_object( person.person_id, self.fellows) self.living_unallocated.append(person_object) print(colored('Unallocated people successfully loaded.', 'cyan')) else: print(colored( 'No saved unallocated people in the database.', 'red')) @staticmethod def get_person_object(person_id, person_location): """Gets the person object for the person to be loaded from database :param person_id: the id of the person to be loaded :param person_location: The list of people where the person exists. :return: person: The person to be loaded. """ for person in person_location: if person.id == person_id: return person def pre_load_state(self, db_name): """Cautions the user against loading state with current data in system""" self.all_people = self.fellows + self.staff self.all_rooms = self.livingrooms + self.offices if not (self.all_rooms or self.all_people): self.load_state(db_name) return'load successful' else: print(colored('This action will wipe all existing data', 'red')) res = raw_input('Would you like to continue[y/n]?: ') if res.lower() == 'y': self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self.office_unallocated = [] self.living_unallocated = [] self.allocated = [] self.all_people = self.fellows + self.staff self.load_state(db_name) else: print(colored('load state exited with no changes', 'cyan')) return 'load state exited with no changes'
{ "content_hash": "b816f6710d252bd37b4284fa37a21924", "timestamp": "", "source": "github", "line_count": 627, "max_line_length": 94, "avg_line_length": 48.75438596491228, "alnum_prop": 0.47374791455395987, "repo_name": "Alweezy/alvin-mutisya-dojo-project", "id": "9f2cf5a4c99bdea4ec561cf64ca5beeaf60e3543", "size": "30569", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "models/dojo.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "53777" } ], "symlink_target": "" }
Package.describe({ name: 'zweizeichen:accounts-eve', summary: 'Authentication for EVE Online\'s SSO service. Works like e.g. \'accounts-github\'.', version: '1.0.0', git: 'https://github.com/zweizeichen/accounts-eve.git' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use('accounts-base', ['client', 'server']); api.imply('accounts-base'); api.use('accounts-oauth', ['client', 'server']); api.use('oauth2', ['client', 'server']); api.use('oauth', ['client', 'server']); api.use('http', ['server']); api.use('templating', 'client'); api.use('underscore', 'server'); api.use('random', 'client'); api.use('service-configuration', ['client', 'server']); api.export('Eve'); api.addFiles('eve.js', ['client', 'server']); api.addFiles(['eve_client.js', 'eve_configure.html', 'eve_configure.js' , 'eve_login_button.css'], 'client'); api.addFiles('eve_server.js', 'server'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('zweizeichen:accounts-eve'); api.addFiles('zweizeichen:accounts-eve-tests.js'); });
{ "content_hash": "fde5bcc76493632e5336c6e42a50d901", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 96, "avg_line_length": 29.710526315789473, "alnum_prop": 0.6155890168290522, "repo_name": "zweizeichen/accounts-eve", "id": "b7ffa15019f651b08b3ed005dbcb8cb5f6bc34bc", "size": "1129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "package.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "6504" } ], "symlink_target": "" }
 namespace Anycmd.Xacml.Consts { public partial class Schema1 { /// <summary>指示者。The name of the element/attribute in the XSD schema.</summary> public class ActionAttributeDesignatorElement { /// <summary>指示者。The name of the element/attribute in the XSD schema.</summary> public const string ActionAttributeDesignator = "ActionAttributeDesignator"; } } }
{ "content_hash": "fc8a124ac37e5e7cf64abe532adaa7e4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 91, "avg_line_length": 32.53846153846154, "alnum_prop": 0.6595744680851063, "repo_name": "anycmd/anycmd", "id": "0bf9add792cf45b4ca7236f1a538028b045b14d5", "size": "441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Anycmd.Xacml/Consts/Consts.Schema1.ActionAttributeDesignatorElement.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "42024" }, { "name": "Batchfile", "bytes": "207" }, { "name": "C#", "bytes": "6965720" }, { "name": "CSS", "bytes": "279467" }, { "name": "HTML", "bytes": "385769" }, { "name": "Java", "bytes": "10698" }, { "name": "JavaScript", "bytes": "1311453" }, { "name": "PHP", "bytes": "92207" } ], "symlink_target": "" }
import express = require('express'); import path = require('path'); import {Routes} from "./routes/routes"; import { json, urlencoded } from "body-parser"; import * as http from "http"; var port = process.env.PORT || 3000; var app = express(); app.use(json()); app.use(urlencoded({ extended: true })); app.use('/app', express.static(path.resolve(__dirname, 'app'))); app.use('/libs', express.static(path.resolve(__dirname, 'libs'))); app.use('/rest', new Routes().getRouter()); // for system.js to work. Can be removed if bundling. app.use(express.static(path.resolve(__dirname, '.'))); app.use(express.static(path.resolve(__dirname, '../node_modules'))); var renderIndex = (req: express.Request, res: express.Response) => { res.sendFile(path.resolve(__dirname, 'index.html')); } app.get('/*', renderIndex); const server:http.Server = app.listen(port, function() { var host = server.address().address; var port = server.address().port; console.log('This express app is listening on port:' + port); }); //const server: http.Server = app.listen(3003); export { server };
{ "content_hash": "1ca153cd2827b68b9e6cf345f09ced30", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 68, "avg_line_length": 29.64864864864865, "alnum_prop": 0.6690975387420237, "repo_name": "amitrke/courtres2", "id": "b62ead5ebac0a15eebd35a2e37e45f4047e009a6", "size": "1097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/server.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2838" }, { "name": "HTML", "bytes": "1986" }, { "name": "JavaScript", "bytes": "1582" }, { "name": "TypeScript", "bytes": "14709" } ], "symlink_target": "" }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.04.20 at 03:09:04 PM EDT // package org.slc.sli.sample.entities; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * The specific type of special variation used in how an examination is presented, how it is administered, or how the test taker is allowed to respond. This generally refers to changes that do not substantially alter what the examination measures. The proper use of accommodations does not substantially change academic level or performance criteria. * * <p>Java class for SpecialAccommodationsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SpecialAccommodationsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="SpecialAccommodation" type="{http://ed-fi.org/0100}SpecialAccommodationItemType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SpecialAccommodationsType", propOrder = { "specialAccommodation" }) public class SpecialAccommodationsType { @XmlElement(name = "SpecialAccommodation") protected List<SpecialAccommodationItemType> specialAccommodation; /** * Gets the value of the specialAccommodation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the specialAccommodation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSpecialAccommodation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SpecialAccommodationItemType } * * */ public List<SpecialAccommodationItemType> getSpecialAccommodation() { if (specialAccommodation == null) { specialAccommodation = new ArrayList<SpecialAccommodationItemType>(); } return this.specialAccommodation; } }
{ "content_hash": "e525efd142c5c2dd3bbd5b9247678159", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 351, "avg_line_length": 35.04938271604938, "alnum_prop": 0.7020077492074674, "repo_name": "inbloom/secure-data-service", "id": "572dea24d4b802772731bbdf98e6b015851a3e7f", "size": "3456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/csv2xml/src/org/slc/sli/sample/entities/SpecialAccommodationsType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "9748" }, { "name": "CSS", "bytes": "112888" }, { "name": "Clojure", "bytes": "37861" }, { "name": "CoffeeScript", "bytes": "18305" }, { "name": "Groovy", "bytes": "26568" }, { "name": "Java", "bytes": "12115410" }, { "name": "JavaScript", "bytes": "390822" }, { "name": "Objective-C", "bytes": "490386" }, { "name": "Python", "bytes": "34255" }, { "name": "Ruby", "bytes": "2543748" }, { "name": "Shell", "bytes": "111267" }, { "name": "XSLT", "bytes": "144746" } ], "symlink_target": "" }
package mount import ( "path/filepath" "sync" "github.com/golang/glog" ) // FakeMounter implements mount.Interface for tests. type FakeMounter struct { MountPoints []MountPoint Log []FakeAction // Some tests run things in parallel, make sure the mounter does not produce // any golang's DATA RACE warnings. mutex sync.Mutex } var _ Interface = &FakeMounter{} // Values for FakeAction.Action const FakeActionMount = "mount" const FakeActionUnmount = "unmount" // FakeAction objects are logged every time a fake mount or unmount is called. type FakeAction struct { Action string // "mount" or "unmount" Target string // applies to both mount and unmount actions Source string // applies only to "mount" actions FSType string // applies only to "mount" actions } func (f *FakeMounter) ResetLog() { f.mutex.Lock() defer f.mutex.Unlock() f.Log = []FakeAction{} } func (f *FakeMounter) Mount(source string, target string, fstype string, options []string) error { f.mutex.Lock() defer f.mutex.Unlock() // find 'bind' option for _, option := range options { if option == "bind" { // This is a bind-mount. In order to mimic linux behaviour, we must // use the original device of the bind-mount as the real source. // E.g. when mounted /dev/sda like this: // $ mount /dev/sda /mnt/test // $ mount -o bind /mnt/test /mnt/bound // then /proc/mount contains: // /dev/sda /mnt/test // /dev/sda /mnt/bound // (and not /mnt/test /mnt/bound) // I.e. we must use /dev/sda as source instead of /mnt/test in the // bind mount. for _, mnt := range f.MountPoints { if source == mnt.Path { source = mnt.Device break } } break } } // If target is a symlink, get its absolute path absTarget, err := filepath.EvalSymlinks(target) if err != nil { absTarget = target } f.MountPoints = append(f.MountPoints, MountPoint{Device: source, Path: absTarget, Type: fstype}) glog.V(5).Infof("Fake mounter: mounted %s to %s", source, absTarget) f.Log = append(f.Log, FakeAction{Action: FakeActionMount, Target: absTarget, Source: source, FSType: fstype}) return nil } func (f *FakeMounter) Unmount(target string) error { f.mutex.Lock() defer f.mutex.Unlock() // If target is a symlink, get its absolute path absTarget, err := filepath.EvalSymlinks(target) if err != nil { absTarget = target } newMountpoints := []MountPoint{} for _, mp := range f.MountPoints { if mp.Path == absTarget { glog.V(5).Infof("Fake mounter: unmounted %s from %s", mp.Device, absTarget) // Don't copy it to newMountpoints continue } newMountpoints = append(newMountpoints, MountPoint{Device: mp.Device, Path: mp.Path, Type: mp.Type}) } f.MountPoints = newMountpoints f.Log = append(f.Log, FakeAction{Action: FakeActionUnmount, Target: absTarget}) return nil } func (f *FakeMounter) List() ([]MountPoint, error) { f.mutex.Lock() defer f.mutex.Unlock() return f.MountPoints, nil } func (f *FakeMounter) IsMountPointMatch(mp MountPoint, dir string) bool { return mp.Path == dir } func (f *FakeMounter) IsNotMountPoint(dir string) (bool, error) { return IsNotMountPoint(f, dir) } func (f *FakeMounter) IsLikelyNotMountPoint(file string) (bool, error) { f.mutex.Lock() defer f.mutex.Unlock() // If file is a symlink, get its absolute path absFile, err := filepath.EvalSymlinks(file) if err != nil { absFile = file } for _, mp := range f.MountPoints { if mp.Path == absFile { glog.V(5).Infof("isLikelyNotMountPoint for %s: mounted %s, false", file, mp.Path) return false, nil } } glog.V(5).Infof("isLikelyNotMountPoint for %s: true", file) return true, nil } func (f *FakeMounter) DeviceOpened(pathname string) (bool, error) { f.mutex.Lock() defer f.mutex.Unlock() for _, mp := range f.MountPoints { if mp.Device == pathname { return true, nil } } return false, nil } func (f *FakeMounter) PathIsDevice(pathname string) (bool, error) { return true, nil } func (f *FakeMounter) GetDeviceNameFromMount(mountPath, pluginDir string) (string, error) { return getDeviceNameFromMount(f, mountPath, pluginDir) } func (f *FakeMounter) MakeRShared(path string) error { return nil } func (f *FakeMounter) GetFileType(pathname string) (FileType, error) { return FileType("fake"), nil } func (f *FakeMounter) MakeDir(pathname string) error { return nil } func (f *FakeMounter) MakeFile(pathname string) error { return nil } func (f *FakeMounter) ExistsPath(pathname string) bool { return false }
{ "content_hash": "ac61880b6c8cb5f860a8c9fd79853adb", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 110, "avg_line_length": 25.335195530726256, "alnum_prop": 0.6912899669239251, "repo_name": "jcbsmpsn/kubernetes", "id": "d34510ae2a87e08d84810469bd212395b212b5c7", "size": "5104", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "pkg/util/mount/fake.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2525" }, { "name": "Go", "bytes": "43275106" }, { "name": "HTML", "bytes": "2912009" }, { "name": "Makefile", "bytes": "75116" }, { "name": "Nginx", "bytes": "595" }, { "name": "PowerShell", "bytes": "4261" }, { "name": "Protocol Buffer", "bytes": "564973" }, { "name": "Python", "bytes": "2385496" }, { "name": "Ruby", "bytes": "1591" }, { "name": "SaltStack", "bytes": "51807" }, { "name": "Shell", "bytes": "1671045" } ], "symlink_target": "" }
#include "UI/Common/StaticEx.h" #include "UI/Common/CommonCtrl.h" #include "WeatherBasedSimulationUI.h" namespace WBSF { class CGridInterpolParam; ///////////////////////////////////////////////////////////////////////////// // CMappingAdvancedDlg dialog class CMappingAdvancedDlg : public CDialog { // Construction public: CMappingAdvancedDlg(CWnd* pParentWnd); // standard constructor int m_method; std::unique_ptr<CGridInterpolParam> m_pParam; protected: // Dialog Data enum { IDD = IDD_MAP_GRID_INTERPOL }; CCFLEdit m_nbPointCtrl; CCFLEdit m_noDataCtrl; CCFLEdit m_maxDistanceCtrl; CCFLEdit m_XvalPointCtrl; CComboBox m_outputTypeCtrl; CCFLEdit m_GDALOptionsCtrl; CButton m_useElevationCtrl; CButton m_useExpositionCtrl; CButton m_useShoreCtrl; //Regression CComboBox m_regressOptCtrl; CCFLEdit m_R²Ctrl; //CComboBox m_regressionModelCtrl; //Kriging CComboBox m_variogramModelCtrl; CCFLEdit m_lagDistanceCtrl; CCFLEdit m_nbLagsCtrl; CComboBox m_detrendingCtrl; CComboBox m_externalDriftCtrl; CButton m_outputVariogramCtrl; CAutoEnableStatic m_regionalLimitCtrl; CCFLEdit m_regionalLimitSDCtrl; CButton m_regionalLimitToBoundCtrl; CAutoEnableStatic m_globalLimitCtrl; CCFLEdit m_globalLimitSDCtrl; CButton m_globalLimitToBoundCtrl; CAutoEnableStatic m_globalLimitMinMaxCtrl; CCFLEdit m_globalMinLimitCtrl; CCFLEdit m_globalMaxLimitCtrl; CButton m_globalMinMaxLimitToBoundCtrl; //IWD CComboBox m_IWDModelCtrl; CCFLComboBox m_powerCtrl; //TPS CCFLComboBox m_TPSMaxErrorCtrl; //Random Forest CComboBox m_RFTreeTypeCtrl; CStaticEx m_static1Ctrl; CStaticEx m_static2Ctrl; CStaticEx m_static3Ctrl; CStaticEx m_static4Ctrl; CStaticEx m_static5Ctrl; virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support void UpdateCtrl(); void GetFromInterface(); void SetToInterface(); // Generated message map functions DECLARE_MESSAGE_MAP() }; }
{ "content_hash": "274996856e47eaacc97ea01ae161780a", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 78, "avg_line_length": 22.135416666666668, "alnum_prop": 0.6978823529411765, "repo_name": "RNCan/WeatherBasedSimulationFramework", "id": "4e41e2a08f8d02808b21858d85a4d361b17cc8ef", "size": "2583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wbs/src/UI/MappingAdvancedDlg.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "25087" }, { "name": "C", "bytes": "304223" }, { "name": "C#", "bytes": "16020" }, { "name": "C++", "bytes": "15327220" }, { "name": "HTML", "bytes": "29355" }, { "name": "Python", "bytes": "2061" } ], "symlink_target": "" }
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'schema' require 'rspec'
{ "content_hash": "7cfc48c2732dfef1919842a4d386af0a", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 66, "avg_line_length": 35.5, "alnum_prop": 0.676056338028169, "repo_name": "kirel/schema", "id": "c5ad20ee037e798c32b500eb2382b7c5e1e66dae", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "8524" } ], "symlink_target": "" }
namespace ppx { namespace string_util { void TrimLeft(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } void TrimRight(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); } std::string TrimCopy(const std::string& s) { std::string sc = s; TrimLeft(sc); TrimRight(sc); return sc; } } // namespace string_util } // namespace ppx
{ "content_hash": "40891f704f48210e30757301986d5b61", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 78, "avg_line_length": 20.571428571428573, "alnum_prop": 0.5381944444444444, "repo_name": "google/bigwheels", "id": "e1da5f6145c02df343ed77da9409b8db9b8afe7d", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/ppx/string_util.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "220559" }, { "name": "C++", "bytes": "3219220" }, { "name": "CMake", "bytes": "93847" }, { "name": "HLSL", "bytes": "153896" }, { "name": "Python", "bytes": "23019" } ], "symlink_target": "" }
package org.apache.camel.component.atomix.client; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import io.atomix.resource.Resource; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.atomix.AtomixAsyncMessageProcessor; import org.apache.camel.spi.InvokeOnHeader; import org.apache.camel.support.DefaultAsyncProducer; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT; import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_NAME; import static org.apache.camel.support.ObjectHelper.invokeMethodSafe; public abstract class AbstractAtomixClientProducer<E extends AbstractAtomixClientEndpoint, R extends Resource> extends DefaultAsyncProducer { private static final Logger LOG = LoggerFactory.getLogger(AbstractAtomixClientProducer.class); private final Map<String, AtomixAsyncMessageProcessor> processors; private ConcurrentMap<String, R> resources; protected AbstractAtomixClientProducer(E endpoint) { super(endpoint); this.processors = new HashMap<>(); this.resources = new ConcurrentHashMap<>(); } @Override protected void doInit() throws Exception { for (final Method method : getClass().getDeclaredMethods()) { InvokeOnHeader[] annotations = method.getAnnotationsByType(InvokeOnHeader.class); if (annotations != null && annotations.length > 0) { for (InvokeOnHeader annotation : annotations) { bind(annotation, method); } } } super.doInit(); } @Override public boolean process(Exchange exchange, AsyncCallback callback) { final Message message = exchange.getIn(); final String key = getProcessorKey(message); AtomixAsyncMessageProcessor processor = this.processors.get(key); if (processor != null) { try { return processor.process(message, callback); } catch (Exception e) { throw new RuntimeCamelException(e); } } else { throw new RuntimeCamelException("No handler for action " + key); } } // ********************************** // // ********************************** @SuppressWarnings("unchecked") protected E getAtomixEndpoint() { return (E) super.getEndpoint(); } protected void processResult(Message message, AsyncCallback callback, Object result) { if (result != null && !(result instanceof Void)) { message.setHeader(RESOURCE_ACTION_HAS_RESULT, true); String resultHeader = getAtomixEndpoint().getConfiguration().getResultHeader(); if (resultHeader != null) { message.setHeader(resultHeader, result); } else { message.setBody(result); } } else { message.setHeader(RESOURCE_ACTION_HAS_RESULT, false); } callback.done(false); } protected R getResource(Message message) { String resourceName = getResourceName(message); ObjectHelper.notNull(resourceName, RESOURCE_NAME); return resources.computeIfAbsent(resourceName, name -> createResource(name)); } protected abstract String getProcessorKey(Message message); protected abstract String getResourceName(Message message); protected abstract R createResource(String name); // ************************************ // Binding helpers // ************************************ private void bind(InvokeOnHeader annotation, final Method method) { if (method.getParameterCount() == 2) { if (!Message.class.isAssignableFrom(method.getParameterTypes()[0])) { throw new IllegalArgumentException("First argument should be of type Message"); } if (!AsyncCallback.class.isAssignableFrom(method.getParameterTypes()[1])) { throw new IllegalArgumentException("Second argument should be of type AsyncCallback"); } if (LOG.isDebugEnabled()) { LOG.debug("bind key={}, class={}, method={}", annotation.value(), this.getClass(), method.getName()); } this.processors.put(annotation.value(), (m, c) -> (boolean) invokeMethodSafe(method, this, m, c)); } else { throw new IllegalArgumentException( "Illegal number of parameters for method: " + method.getName() + ", required: 2, found: " + method.getParameterCount()); } } }
{ "content_hash": "9ab7a3fb7b03d35e44ddd5a59f3da4f3", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 110, "avg_line_length": 36.55072463768116, "alnum_prop": 0.6362014274385408, "repo_name": "mcollovati/camel", "id": "f11ada9bf09857b91a248f057523399a1a876930", "size": "5846", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientProducer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "14479" }, { "name": "HTML", "bytes": "915679" }, { "name": "Java", "bytes": "84048197" }, { "name": "JavaScript", "bytes": "100326" }, { "name": "Makefile", "bytes": "513" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Shell", "bytes": "17240" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "275257" } ], "symlink_target": "" }
import React from 'react' import PropTypes from 'prop-types' import { graphql } from 'gatsby' import Layout from '../components/Layout' import Features from '../components/Features' import Testimonials from '../components/Testimonials' import Pricing from '../components/Pricing' export const ProductPageTemplate = ({ image, title, heading, description, intro, main, testimonials, fullImage, pricing, }) => ( <section className="section section--gradient"> <div className="container"> <div className="section"> <div className="columns"> <div className="column is-10 is-offset-1"> <div className="content"> <div className="full-width-image-container margin-top-0" style={{ backgroundImage: `url(${image})` }} > <h2 className="has-text-weight-bold is-size-1" style={{ boxShadow: '0.5rem 0 0 #f40, -0.5rem 0 0 #f40', backgroundColor: '#f40', color: 'white', padding: '1rem', }} > {title} </h2> </div> <div className="columns"> <div className="column is-7"> <h3 className="has-text-weight-semibold is-size-2"> {heading} </h3> <p>{description}</p> </div> </div> <Features gridItems={intro.blurbs} /> <div className="columns"> <div className="column is-7"> <h3 className="has-text-weight-semibold is-size-3"> {main.heading} </h3> <p>{main.description}</p> </div> </div> <div className="tile is-ancestor"> <div className="tile is-vertical"> <div className="tile"> <div className="tile is-parent is-vertical"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image1.image} alt={main.image1.alt} /> </article> </div> <div className="tile is-parent"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image2.image} alt={main.image2.alt} /> </article> </div> </div> <div className="tile is-parent"> <article className="tile is-child"> <img style={{ borderRadius: '5px' }} src={main.image3.image} alt={main.image3.alt} /> </article> </div> </div> </div> <Testimonials testimonials={testimonials} /> <div className="full-width-image-container" style={{ backgroundImage: `url(${fullImage})` }} /> <h2 className="has-text-weight-semibold is-size-2"> {pricing.heading} </h2> <p className="is-size-5">{pricing.description}</p> <Pricing data={pricing.plans} /> </div> </div> </div> </div> </div> </section> ) ProductPageTemplate.propTypes = { image: PropTypes.string, title: PropTypes.string, heading: PropTypes.string, description: PropTypes.string, intro: PropTypes.shape({ blurbs: PropTypes.array, }), main: PropTypes.shape({ heading: PropTypes.string, description: PropTypes.string, image1: PropTypes.object, image2: PropTypes.object, image3: PropTypes.object, }), testimonials: PropTypes.array, fullImage: PropTypes.string, pricing: PropTypes.shape({ heading: PropTypes.string, description: PropTypes.string, plans: PropTypes.array, }), } const ProductPage = ({ data }) => { const { frontmatter } = data.markdownRemark return ( <Layout> <ProductPageTemplate image={frontmatter.image} title={frontmatter.title} heading={frontmatter.heading} description={frontmatter.description} intro={frontmatter.intro} main={frontmatter.main} testimonials={frontmatter.testimonials} fullImage={frontmatter.full_image} pricing={frontmatter.pricing} /> </Layout> ) } ProductPage.propTypes = { data: PropTypes.shape({ markdownRemark: PropTypes.shape({ frontmatter: PropTypes.object, }), }), } export default ProductPage export const productPageQuery = graphql` query ProductPage($id: String!) { markdownRemark(id: { eq: $id }) { frontmatter { title image heading description intro { blurbs { image text } heading description } main { heading description image1 { alt image } image2 { alt image } image3 { alt image } } testimonials { author quote } full_image pricing { heading description plans { description items plan price } } } } } `
{ "content_hash": "de888e18b6e54642c2f82807d5fba0e8", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 69, "avg_line_length": 27.672897196261683, "alnum_prop": 0.46335697399527187, "repo_name": "sfoubert/cdsbf75", "id": "547ac1e02e884a41b3a461e2192fe7547bee677a", "size": "5922", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/templates/product-page.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "750" }, { "name": "JavaScript", "bytes": "28217" } ], "symlink_target": "" }
package org.optaplanner.examples.cloudbalancing.optional.move; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.optaplanner.core.impl.heuristic.move.AbstractMove; import org.optaplanner.core.impl.heuristic.move.Move; import org.optaplanner.core.impl.score.director.ScoreDirector; import org.optaplanner.examples.cloudbalancing.domain.CloudBalance; import org.optaplanner.examples.cloudbalancing.domain.CloudComputer; import org.optaplanner.examples.cloudbalancing.domain.CloudProcess; public class CloudProcessSwapMove extends AbstractMove<CloudBalance> { private CloudProcess leftCloudProcess; private CloudProcess rightCloudProcess; public CloudProcessSwapMove(CloudProcess leftCloudProcess, CloudProcess rightCloudProcess) { this.leftCloudProcess = leftCloudProcess; this.rightCloudProcess = rightCloudProcess; } @Override public boolean isMoveDoable(ScoreDirector<CloudBalance> scoreDirector) { return !Objects.equals(leftCloudProcess.getComputer(), rightCloudProcess.getComputer()); } @Override public CloudProcessSwapMove createUndoMove(ScoreDirector<CloudBalance> scoreDirector) { return new CloudProcessSwapMove(rightCloudProcess, leftCloudProcess); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<CloudBalance> scoreDirector) { CloudComputer oldLeftCloudComputer = leftCloudProcess.getComputer(); CloudComputer oldRightCloudComputer = rightCloudProcess.getComputer(); scoreDirector.beforeVariableChanged(leftCloudProcess, "computer"); leftCloudProcess.setComputer(oldRightCloudComputer); scoreDirector.afterVariableChanged(leftCloudProcess, "computer"); scoreDirector.beforeVariableChanged(rightCloudProcess, "computer"); rightCloudProcess.setComputer(oldLeftCloudComputer); scoreDirector.afterVariableChanged(rightCloudProcess, "computer"); } @Override public Collection<? extends Object> getPlanningEntities() { return Arrays.asList(leftCloudProcess, rightCloudProcess); } @Override public Collection<? extends Object> getPlanningValues() { return Arrays.asList(leftCloudProcess.getComputer(), rightCloudProcess.getComputer()); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof CloudProcessSwapMove) { CloudProcessSwapMove other = (CloudProcessSwapMove) o; return new EqualsBuilder() .append(leftCloudProcess, other.leftCloudProcess) .append(rightCloudProcess, other.rightCloudProcess) .isEquals(); } else { return false; } } @Override public int hashCode() { return new HashCodeBuilder() .append(leftCloudProcess) .append(rightCloudProcess) .toHashCode(); } @Override public String toString() { return leftCloudProcess + " {" + leftCloudProcess.getComputer() + "} <-> " + rightCloudProcess + " {" + rightCloudProcess.getComputer() + "}"; } }
{ "content_hash": "4cb20923ba14c0c6c080bb551a0fee5d", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 96, "avg_line_length": 37.49438202247191, "alnum_prop": 0.7168115073419239, "repo_name": "oskopek/optaplanner", "id": "4a7c65e322ad114605d182531850df8162a53a95", "size": "3957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/optional/move/CloudProcessSwapMove.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2602" }, { "name": "CSS", "bytes": "13781" }, { "name": "FreeMarker", "bytes": "114386" }, { "name": "HTML", "bytes": "678" }, { "name": "Java", "bytes": "6969940" }, { "name": "JavaScript", "bytes": "215434" }, { "name": "Shell", "bytes": "1548" } ], "symlink_target": "" }
Delo.PartsLayer = function(config) { this._initPartsLayer(config); }; Delo.PartsLayer.prototype = { _initPartsLayer : function(config) { this.partMap = {}; config.id = 'parts_layer'; // call super constructor Kinetic.Layer.call(this, config); /* set event handlers */ var document = this.getAttr('document'); var mode = this.getAttr('mode'); document.bind('add', this._add, this); document.bind('remove', this._remove, this); document.bind('reset', this._reset, this); this._reset(); // TODO stage나 model이 destroy 될 때 이벤트핸들러들을 모두 해제시켜주어야 한다. }, register: function(modelType, editpartClass) { this.partMap[modelType] = editpartClass; }, findByModel : function(models) { if(!models) { return null; } if(!models instanceof Array) { models = [models]; } var nodes = this.getChildren().toArray(); var selnodes = []; for(var i = 0;i < models.length;i++) { var model = models[i]; for(var j = 0;j < nodes.length;j++) { if(nodes[j].getAttr('model') === model) { selnodes.push(nodes[j]); } } } return selnodes; }, _reset : function() { // 뷰를 클리어하기 전에 리소스들을 해제할 수 있는 기회를 제공해야 한다. removed 이벤트 fire this.removeChildren(); this.draw(); }, _add : function(m) { var editPartClass = this.partMap[m.constructor.partType]; var node = new editPartClass({ model: m, mode : this.getAttr('mode') }); this.add(node); this.draw(); }, _remove : function(m) { this.draw(); } }; Kinetic.Util.extend(Delo.PartsLayer, Kinetic.Layer);
{ "content_hash": "14fafedaa869eaef15a7417805a7a7f9", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 61, "avg_line_length": 20.128205128205128, "alnum_prop": 0.6152866242038216, "repo_name": "heartyoh/infogra", "id": "966d32b2df7f1139f2b9c5bcd1747de313e89b90", "size": "1680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/infogra/view/layer/PartsLayer.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "429" }, { "name": "JavaScript", "bytes": "302077" }, { "name": "Makefile", "bytes": "243" }, { "name": "Ruby", "bytes": "1540" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Inventory Tel-U</title> <!-- Bootstrap --> <link href="<?= base_url(); ?>assets/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="<?= base_url(); ?>assets/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <!-- NProgress --> <link href="<?= base_url(); ?>assets/vendors/nprogress/nprogress.css" rel="stylesheet"> <!-- iCheck --> <link href="<?= base_url(); ?>assets/vendors/iCheck/skins/flat/green.css" rel="stylesheet"> <!-- Datatables --> <link href="<?= base_url(); ?>assets/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"> <link href="<?= base_url(); ?>assets/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet"> <link href="<?= base_url(); ?>assets/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet"> <link href="<?= base_url(); ?>assets/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet"> <link href="<?= base_url(); ?>assets/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet"> <!-- Custom Theme Style --> <link href="<?= base_url(); ?>assets/build/css/custom.min.css" rel="stylesheet"> </head> <body class="nav-md"> <div class="container body"> <div class="main_container"> <div class="col-md-3 left_col"> <div class="left_col scroll-view"> <div class="navbar nav_title" style="border: 0;"> <span>Inventory Tel-U</span></a> </div> <div class="clearfix"></div> <!-- menu profile quick info --> <div class="profile"> <div class="profile_pic"> <img src="<?= base_url(); ?>assets/images/img.jpg" alt="..." class="img-circle profile_img"> </div> <div class="profile_info"> <span>Welcome,</span> <h2><?php echo $namaUser; ?></h2> </div> </div> <!-- /menu profile quick info --> <br /> <!-- sidebar menu --> <div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section"> <h3>Inventory</h3> <ul class="nav side-menu"> <li><a><i class="fa fa-square"></i> Barang <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="<?php echo base_url();?>Barang/fakultas">Lihat Barang</a></li> <li><a href="<?php echo base_url();?>Barang/editFakultas">Ubah Barang</a></li> <li><a href="<?php echo base_url();?>Barang/hapusFakultas">Hapus Barang</a></li> </ul> </li> <li><a><i class="fa fa-bookmark"></i> Ruangan <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="<?php echo base_url();?>Ruangan/fakultas">Lihat Ruangan</a></li> </ul> </li> <li><a><i class="fa fa-building"></i> Gedung <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="<?php echo base_url();?>Gedung/fakultas">Lihat Gedung</a></li> </ul> </li> <li><a><i class="fa fa-edit"></i> Permintaan <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="<?php echo base_url();?>Permintaan/fakultas">Ajukan Permintaan</a></li> </ul> </li> <li><a><i class="fa fa-archive"></i> Status <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="<?php echo base_url();?>Kondisi/barangFakultas">Kondisi Barang</a></li> <li><a href="<?php echo base_url();?>Kondisi/ruanganFakultas">Kondisi Ruangan</a></li> </ul> </li> <!-- <li><a><i class="fa fa-table"></i> Pelaporan <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="pelaporan.html">Pelaporan</a></li> </ul> </li> <li><a><i class="fa fa-truck"></i> Mutasi <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="mutasi.html">Mutasi</a></li> </ul> </li>--> </ul> </div> </div> <!-- /sidebar menu --> <!-- /menu footer buttons --> <!-- /menu footer buttons --> </div> </div> <!-- top navigation --> <div class="top_nav"> <div class="nav_menu"> <nav> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="<?= base_url(); ?>assets/images/img.jpg" alt=""><?php echo $namaUser; ?> <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="<?php echo site_url('barang/logout'); ?>"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> </ul> </nav> </div> </div> <!-- /top navigation --> <!-- page content --> <div class="right_col" role="main"> <div class=""> <div class="page-title"> <div class="title_left"> <h3></h3> </div> <div class="title_right"> </div> </div> <div class="clearfix"></div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Hapus Barang</small></h2> <div class="clearfix"></div> </div> <div class="x_content"> <p class="text-muted font-13 m-b-30"> </p> <table id="datatable-checkbox" class="table table-striped table-bordered bulk_action"> <thead> <tr> <th>Id Barang</th> <th>Nama Barang</th> <th>Ruangan Barang</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($datane as $value): ?> <tr> <td><?php echo $value['idBarang']; ?></td> <td><?php echo $value['namaBarang']; ?></td> <td><?php echo $value['namaRuangan']; ?></td> <td><a href="<?php echo base_url().'Barang/doHapus/'.$value['idBarang'];?>">Hapus</a></td> </tr> <?php endforeach ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <!-- /page content --> <!-- footer content --> <footer> <div class="pull-right"> Inventory by <a href="http://steamcommunity.com/profiles/76561198103686428">FEaR</a> </div> <div class="clearfix"></div> </footer> <!-- /footer content --> </div> </div> <!-- jQuery --> <script src="<?= base_url(); ?>assets/vendors/jquery/dist/jquery.min.js"></script> <!-- Bootstrap --> <script src="<?= base_url(); ?>assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script> <!-- FastClick --> <script src="<?= base_url(); ?>assets/vendors/fastclick/lib/fastclick.js"></script> <!-- NProgress --> <script src="<?= base_url(); ?>assets/vendors/nprogress/nprogress.js"></script> <!-- iCheck --> <script src="<?= base_url(); ?>assets/vendors/iCheck/icheck.min.js"></script> <!-- Datatables --> <script src="<?= base_url(); ?>assets/vendors/datatables.net/js/jquery.dataTables.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-buttons/js/buttons.flash.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-buttons/js/buttons.html5.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-buttons/js/buttons.print.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script> <script src="<?= base_url(); ?>assets/vendors/datatables.net-scroller/js/datatables.scroller.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/jszip/dist/jszip.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/pdfmake/build/pdfmake.min.js"></script> <script src="<?= base_url(); ?>assets/vendors/pdfmake/build/vfs_fonts.js"></script> <!-- Custom Theme Scripts --> <script src="<?= base_url(); ?>assets/build/js/custom.min.js"></script> <!-- Datatables --> <script> $(document).ready(function() { var handleDataTableButtons = function() { if ($("#datatable-buttons").length) { $("#datatable-buttons").DataTable({ dom: "Bfrtip", buttons: [ { extend: "copy", className: "btn-sm" }, { extend: "csv", className: "btn-sm" }, { extend: "excel", className: "btn-sm" }, { extend: "pdfHtml5", className: "btn-sm" }, { extend: "print", className: "btn-sm" }, ], responsive: true }); } }; TableManageButtons = function() { "use strict"; return { init: function() { handleDataTableButtons(); } }; }(); $('#datatable').dataTable(); $('#datatable-keytable').DataTable({ keys: true }); $('#datatable-responsive').DataTable(); $('#datatable-scroller').DataTable({ ajax: "js/datatables/json/scroller-demo.json", deferRender: true, scrollY: 380, scrollCollapse: true, scroller: true }); $('#datatable-fixed-header').DataTable({ fixedHeader: true }); var $datatable = $('#datatable-checkbox'); $datatable.dataTable({ 'order': [[ 1, 'asc' ]], 'columnDefs': [ { orderable: false, targets: [0] } ] }); $datatable.on('draw.dt', function() { $('input').iCheck({ checkboxClass: 'icheckbox_flat-green' }); }); TableManageButtons.init(); }); </script> <!-- /Datatables --> </body> </html>
{ "content_hash": "291144824c9c87928f81a29f72d6890f", "timestamp": "", "source": "github", "line_count": 320, "max_line_length": 133, "avg_line_length": 40.596875, "alnum_prop": 0.47425140481872063, "repo_name": "mizangh/inventory", "id": "ff4211b61fa08fb9f717dedc1c5dea64712bbe5d", "size": "12991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/fakultas/barang-hapus.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "364" }, { "name": "CSS", "bytes": "97244" }, { "name": "HTML", "bytes": "8413296" }, { "name": "JavaScript", "bytes": "100032" }, { "name": "PHP", "bytes": "2184351" } ], "symlink_target": "" }
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Z.EntityFramework.Plus; namespace Z.Test.EntityFramework.Plus { public partial class QueryIncludeFilter_Where { [TestMethod] public void Many_ThenQuery_Enumerator() { TestContext.DeleteAll(x => x.Association_Multi_OneToMany_Right1s); TestContext.DeleteAll(x => x.Association_Multi_OneToMany_Right2s); TestContext.DeleteAll(x => x.Association_Multi_OneToMany_Lefts); using (var ctx = new TestContext()) { { var left = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Lefts, 1).First(); left.Right1s = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Right1s, 5); left.Right2s = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Right2s, 5); } { var left = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Lefts, 1).First(); left.ColumnInt = 5; left.Right1s = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Right1s, 5); left.Right2s = TestContext.Insert(ctx, x => x.Association_Multi_OneToMany_Right2s, 5); } ctx.SaveChanges(); } using (var ctx = new TestContext()) { var list = ctx.Association_Multi_OneToMany_Lefts .IncludeFilter(left => left.Right1s.Where(y => y.ColumnInt > 2)) .IncludeFilter(left => left.Right2s.Where(y => y.ColumnInt > 2)) .Where(x => x.ColumnInt < 5) .OrderBy(x => x.ID) .ToList(); // TEST: context Assert.AreEqual(5, ctx.ChangeTracker.Entries().Count()); // TEST: left Assert.AreEqual(1, list.Count); var item = list[0]; // TEST: right1 Assert.AreEqual(2, item.Right1s.Count); if (item.Right1s[0].ColumnInt == 3) { Assert.AreEqual(3, item.Right1s[0].ColumnInt); Assert.AreEqual(4, item.Right1s[1].ColumnInt); } else { Assert.AreEqual(4, item.Right1s[0].ColumnInt); Assert.AreEqual(3, item.Right1s[1].ColumnInt); } // TEST: right2 Assert.AreEqual(2, item.Right2s.Count); if (item.Right2s[0].ColumnInt == 3) { Assert.AreEqual(3, item.Right2s[0].ColumnInt); Assert.AreEqual(4, item.Right2s[1].ColumnInt); } else { Assert.AreEqual(4, item.Right2s[0].ColumnInt); Assert.AreEqual(3, item.Right2s[1].ColumnInt); } } } } }
{ "content_hash": "802a3f7e2c8dac8f932855c341a46d36", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 191, "avg_line_length": 41.96511627906977, "alnum_prop": 0.5394846217788861, "repo_name": "zzzprojects/EntityFramework-Plus", "id": "0455be0c6b48a8a3ed7b08f6b01b8e4e5262e354", "size": "3612", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/Z.Test.EntityFramework.Plus.EF6/QueryIncludeFilter/Where/Many_ThenQuery_Enumerator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "7438029" } ], "symlink_target": "" }
def add_native_methods(clazz): def sin__double__(a0): raise NotImplementedError() def cos__double__(a0): raise NotImplementedError() def tan__double__(a0): raise NotImplementedError() def asin__double__(a0): raise NotImplementedError() def acos__double__(a0): raise NotImplementedError() def atan__double__(a0): raise NotImplementedError() def exp__double__(a0): raise NotImplementedError() def log__double__(a0): raise NotImplementedError() def log10__double__(a0): raise NotImplementedError() def sqrt__double__(a0): raise NotImplementedError() def cbrt__double__(a0): raise NotImplementedError() def IEEEremainder__double__double__(a0, a1): raise NotImplementedError() def atan2__double__double__(a0, a1): raise NotImplementedError() def pow__double__double__(a0, a1): raise NotImplementedError() def sinh__double__(a0): raise NotImplementedError() def cosh__double__(a0): raise NotImplementedError() def tanh__double__(a0): raise NotImplementedError() def hypot__double__double__(a0, a1): raise NotImplementedError() def expm1__double__(a0): raise NotImplementedError() def log1p__double__(a0): raise NotImplementedError() clazz.sin__double__ = staticmethod(sin__double__) clazz.cos__double__ = staticmethod(cos__double__) clazz.tan__double__ = staticmethod(tan__double__) clazz.asin__double__ = staticmethod(asin__double__) clazz.acos__double__ = staticmethod(acos__double__) clazz.atan__double__ = staticmethod(atan__double__) clazz.exp__double__ = staticmethod(exp__double__) clazz.log__double__ = staticmethod(log__double__) clazz.log10__double__ = staticmethod(log10__double__) clazz.sqrt__double__ = staticmethod(sqrt__double__) clazz.cbrt__double__ = staticmethod(cbrt__double__) clazz.IEEEremainder__double__double__ = staticmethod(IEEEremainder__double__double__) clazz.atan2__double__double__ = staticmethod(atan2__double__double__) clazz.pow__double__double__ = staticmethod(pow__double__double__) clazz.sinh__double__ = staticmethod(sinh__double__) clazz.cosh__double__ = staticmethod(cosh__double__) clazz.tanh__double__ = staticmethod(tanh__double__) clazz.hypot__double__double__ = staticmethod(hypot__double__double__) clazz.expm1__double__ = staticmethod(expm1__double__) clazz.log1p__double__ = staticmethod(log1p__double__)
{ "content_hash": "8e354451b559a0aaebfdb49dd928fc9f", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 89, "avg_line_length": 31.5609756097561, "alnum_prop": 0.6367851622874807, "repo_name": "laffra/pava", "id": "d7073997d1871a68e38d0ee04f2a37d907505e2b", "size": "2588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pava/implementation/natives/java/lang/StrictMath.py", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "144" }, { "name": "Python", "bytes": "369288" } ], "symlink_target": "" }
package org.apache.spark.executor import java.lang.Long.{MAX_VALUE => LONG_MAX_VALUE} import java.util.concurrent.{ConcurrentHashMap, TimeUnit} import java.util.concurrent.atomic.{AtomicLong, AtomicLongArray} import scala.collection.mutable.HashMap import org.apache.spark.internal.Logging import org.apache.spark.memory.MemoryManager import org.apache.spark.metrics.ExecutorMetricType import org.apache.spark.util.{ThreadUtils, Utils} /** * A class that polls executor metrics, and tracks their peaks per task and per stage. * Each executor keeps an instance of this class. * The poll method polls the executor metrics, and is either run in its own thread or * called by the executor's heartbeater thread, depending on configuration. * The class keeps two ConcurrentHashMaps that are accessed (via its methods) by the * executor's task runner threads concurrently with the polling thread. One thread may * update one of these maps while another reads it, so the reading thread may not get * the latest metrics, but this is ok. * We track executor metric peaks per stage, as well as per task. The per-stage peaks * are sent in executor heartbeats. That way, we get incremental updates of the metrics * as the tasks are running, and if the executor dies we still have some metrics. The * per-task peaks are sent in the task result at task end. These are useful for short * tasks. If there are no heartbeats during the task, we still get the metrics polled * for the task. * * @param memoryManager the memory manager used by the executor. * @param pollingInterval the polling interval in milliseconds. */ private[spark] class ExecutorMetricsPoller( memoryManager: MemoryManager, pollingInterval: Long) extends Logging { type StageKey = (Int, Int) // Task Count and Metric Peaks private case class TCMP(count: AtomicLong, peaks: AtomicLongArray) // Map of (stageId, stageAttemptId) to (count of running tasks, executor metric peaks) private val stageTCMP = new ConcurrentHashMap[StageKey, TCMP] // Map of taskId to executor metric peaks private val taskMetricPeaks = new ConcurrentHashMap[Long, AtomicLongArray] private val poller = if (pollingInterval > 0) { Some(ThreadUtils.newDaemonSingleThreadScheduledExecutor("executor-metrics-poller")) } else { None } /** * Function to poll executor metrics. * On start, if pollingInterval is positive, this is scheduled to run at that interval. * Otherwise, this is called by the reportHeartBeat function defined in Executor and passed * to its Heartbeater. */ def poll(): Unit = { // Note: Task runner threads may update stageTCMP or read from taskMetricPeaks concurrently // with this function via calls to methods of this class. // get the latest values for the metrics val latestMetrics = ExecutorMetrics.getCurrentMetrics(memoryManager) def updatePeaks(metrics: AtomicLongArray): Unit = { (0 until metrics.length).foreach { i => metrics.getAndAccumulate(i, latestMetrics(i), math.max) } } // for each active stage, update the peaks stageTCMP.forEachValue(LONG_MAX_VALUE, v => updatePeaks(v.peaks)) // for each running task, update the peaks taskMetricPeaks.forEachValue(LONG_MAX_VALUE, updatePeaks) } /** Starts the polling thread. */ def start(): Unit = { poller.foreach { exec => val pollingTask: Runnable = () => Utils.logUncaughtExceptions(poll()) exec.scheduleAtFixedRate(pollingTask, 0L, pollingInterval, TimeUnit.MILLISECONDS) } } /** * Called by TaskRunner#run. */ def onTaskStart(taskId: Long, stageId: Int, stageAttemptId: Int): Unit = { // Put an entry in taskMetricPeaks for the task. taskMetricPeaks.put(taskId, new AtomicLongArray(ExecutorMetricType.numMetrics)) // Put a new entry in stageTCMP for the stage if there isn't one already. // Increment the task count. val countAndPeaks = stageTCMP.computeIfAbsent((stageId, stageAttemptId), _ => TCMP(new AtomicLong(0), new AtomicLongArray(ExecutorMetricType.numMetrics))) val stageCount = countAndPeaks.count.incrementAndGet() logDebug(s"stageTCMP: ($stageId, $stageAttemptId) -> $stageCount") } /** * Called by TaskRunner#run. It should only be called if onTaskStart has been called with * the same arguments. */ def onTaskCompletion(taskId: Long, stageId: Int, stageAttemptId: Int): Unit = { // Decrement the task count. // Remove the entry from stageTCMP if the task count reaches zero. def decrementCount(stage: StageKey, countAndPeaks: TCMP): TCMP = { val countValue = countAndPeaks.count.decrementAndGet() if (countValue == 0L) { logDebug(s"removing (${stage._1}, ${stage._2}) from stageTCMP") null } else { logDebug(s"stageTCMP: (${stage._1}, ${stage._2}) -> " + countValue) countAndPeaks } } stageTCMP.computeIfPresent((stageId, stageAttemptId), decrementCount) // Remove the entry from taskMetricPeaks for the task. taskMetricPeaks.remove(taskId) } /** * Called by TaskRunner#run. */ def getTaskMetricPeaks(taskId: Long): Array[Long] = { // If this is called with an invalid taskId or a valid taskId but the task was killed and // onTaskStart was therefore not called, then we return an array of zeros. val currentPeaks = taskMetricPeaks.get(taskId) // may be null val metricPeaks = new Array[Long](ExecutorMetricType.numMetrics) // initialized to zeros if (currentPeaks != null) { ExecutorMetricType.metricToOffset.foreach { case (_, i) => metricPeaks(i) = currentPeaks.get(i) } } metricPeaks } /** * Called by the reportHeartBeat function defined in Executor and passed to its Heartbeater. * It resets the metric peaks in stageTCMP before returning the executor updates. * Thus, the executor updates contains the per-stage metric peaks since the last heartbeat * (the last time this method was called). */ def getExecutorUpdates(): HashMap[StageKey, ExecutorMetrics] = { val executorUpdates = new HashMap[StageKey, ExecutorMetrics] def getUpdateAndResetPeaks(k: StageKey, v: TCMP): TCMP = { executorUpdates.put(k, new ExecutorMetrics(v.peaks)) TCMP(v.count, new AtomicLongArray(ExecutorMetricType.numMetrics)) } stageTCMP.replaceAll(getUpdateAndResetPeaks) executorUpdates } /** Stops the polling thread. */ def stop(): Unit = { poller.foreach { exec => exec.shutdown() exec.awaitTermination(10, TimeUnit.SECONDS) } } }
{ "content_hash": "402c215ea378456bd9a59818ec91b4cf", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 95, "avg_line_length": 38.51162790697674, "alnum_prop": 0.7169384057971014, "repo_name": "kiszk/spark", "id": "805b0f729b122a0a2d6476896e123138d7a7f7ff", "size": "7424", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "core/src/main/scala/org/apache/spark/executor/ExecutorMetricsPoller.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "46871" }, { "name": "Batchfile", "bytes": "31352" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "26599" }, { "name": "Dockerfile", "bytes": "8863" }, { "name": "HTML", "bytes": "70407" }, { "name": "HiveQL", "bytes": "1823701" }, { "name": "Java", "bytes": "4054268" }, { "name": "JavaScript", "bytes": "201603" }, { "name": "Makefile", "bytes": "9397" }, { "name": "PLpgSQL", "bytes": "257276" }, { "name": "PowerShell", "bytes": "3867" }, { "name": "Python", "bytes": "2976348" }, { "name": "R", "bytes": "1186688" }, { "name": "Roff", "bytes": "15633" }, { "name": "SQLPL", "bytes": "9325" }, { "name": "Scala", "bytes": "30321675" }, { "name": "Shell", "bytes": "201878" }, { "name": "TSQL", "bytes": "438358" }, { "name": "Thrift", "bytes": "67610" }, { "name": "q", "bytes": "146878" } ], "symlink_target": "" }
""" Convolution layer tests """ import itertools as itt import numpy as np from neon import NervanaObject from neon.layers.layer import Convolution from neon.initializers.initializer import Uniform from tests.utils import allclose_with_out def pytest_generate_tests(metafunc): np.random.seed(1) if metafunc.config.option.all: bsz_rng = [32, 64] else: bsz_rng = [128] if 'zeros_convargs' in metafunc.fixturenames: fargs = [] if metafunc.config.option.all: fs_rng = [2, 3, 5, 7] nofm_rng = [16, 32] else: fs_rng = [2, 5] nofm_rng = [16] fargs = itt.product(fs_rng, nofm_rng, bsz_rng) metafunc.parametrize('zeros_convargs', fargs) if 'ones_convargs' in metafunc.fixturenames: fargs = [] if metafunc.config.option.all: bsz_rng = [64] indim_rng = [16, 32] nifm_rng = [1, 2, 3] fs_rng = [2, 3] stride_rng = [1, 2] nofm_rng = [16, 32, 64] pad_rng = [0, 1, 2] fargs1 = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, pad_rng) fs_rng = [5] stride_rng = [1, 5] fargs2 = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, pad_rng) fargs = itt.chain(fargs1, fargs2) else: bsz_rng = [64] indim_rng = [32] nifm_rng = [3] fs_rng = [2, 5] nofm_rng = [16] stride_rng = [1, 2] pad_rng = [0, 1] fargs = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, pad_rng) metafunc.parametrize('ones_convargs', fargs) if 'rand_convargs' in metafunc.fixturenames: fargs = [] eps = np.finfo(np.float32).eps if metafunc.config.option.all: indim_rng = [16, 32] nifm_rng = [1, 3] fs_rng = [2, 3] nofm_rng = [16] rng_max_rng = [eps, eps * 10, 1.0, 100] wrng = [[0.0, 1.0], [-1.0, 0.0], [-1.0, 1.0]] stride_rng = [1, 2, 3] pad_rng = [0, 1, 2] fargs1 = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, rng_max_rng, wrng, pad_rng) fs_rng = [5] stride_rng = [1, 5] fargs2 = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, rng_max_rng, wrng, pad_rng) fargs = itt.chain(fargs1, fargs2) else: indim_rng = [16] nifm_rng = [1, 3] fs_rng = [2, 5] nofm_rng = [16] rng_max_rng = [2.0] stride_rng = [1, 2] wrng = [[-1.0, 1.0]] pad_rng = [0, 1] fargs = itt.product(indim_rng, nifm_rng, fs_rng, nofm_rng, bsz_rng, stride_rng, rng_max_rng, wrng, pad_rng) metafunc.parametrize('rand_convargs', fargs) def test_conv_zeros(backend_default, zeros_convargs): fshape, nofm, batch_size = zeros_convargs NervanaObject.be.bsz = batch_size # basic sanity check with 0 weights random inputs init_unif = Uniform(low=0.0, high=0.0) inshape = (3, 32, 32) insize = np.prod(inshape) neon_layer = Convolution(fshape=(fshape, fshape, nofm), strides=1, padding=0, init=init_unif) inp = neon_layer.be.array(np.random.random((insize, batch_size))) inp.lshape = inshape neon_layer.configure(inshape) neon_layer.prev_layer = True neon_layer.allocate() neon_layer.set_deltas([neon_layer.be.iobuf(inshape)]) out = neon_layer.fprop(inp).get() assert np.min(out) == 0.0 and np.max(out) == 0.0 err = np.zeros(out.shape) deltas = neon_layer.bprop(neon_layer.be.array(err)).get() assert np.min(deltas) == 0.0 and np.max(deltas) == 0.0 dw = neon_layer.dW.get() assert np.min(dw) == 0.0 and np.max(dw) == 0.0 return def test_conv_ones(backend_default, ones_convargs): dtypeu = np.float32 indim, nifm, fshape, nofm, batch_size, stride, pad = ones_convargs NervanaObject.be.bsz = batch_size # weights set to one init_unif = Uniform(low=1.0, high=1.0) inshape = (nifm, indim, indim) insize = np.prod(inshape) neon_layer = Convolution(fshape=(fshape, fshape, nofm), strides=stride, padding=pad, init=init_unif) inp = neon_layer.be.array(np.ones((insize, batch_size))) inp.lshape = inshape neon_layer.configure(inshape) neon_layer.prev_layer = True neon_layer.allocate() neon_layer.set_deltas([neon_layer.be.iobuf(inshape)]) # run fprop out = neon_layer.fprop(inp).get() # generate the reference layer ref_layer = ConvLayerRef(1, batch_size, identity, inshape[0], inshape[1:3], (fshape, fshape), nofm, stride, dtypeu, padding=pad) # init weights to ones ref_layer.weights = np.ones(neon_layer.W.shape).T.astype(dtypeu) ref_layer.fprop(inp.get().T) out_exp = ref_layer.y.copy() assert np.allclose(out_exp.T, out, atol=0.0, rtol=0.0) # generate err array err = np.ones(out.shape).astype(np.float32) # run bprop neon_layer.bprop(neon_layer.be.array(err)) dw = neon_layer.dW.get() # run bprop ref_layer.bprop(err.T.astype(dtypeu), 1.0) # expected output for updates is uniform matrix with # all elements == ofmsize*batch_size updates_exp = ref_layer.updates.T # check dw from neon layer assert np.allclose(dw, updates_exp, atol=0.0, rtol=0.0) # the deltas are more complicated since the matricies are not # uniform, going to use the reference code directly here # no tolerance here should be exact dd = np.abs(ref_layer.berror_nopad.T - neon_layer.deltas.get()) assert np.max(dd) == 0.0 return def test_conv_rand(backend_default, rand_convargs): indim, nifm, fshape, nofm, batch_size, stride, rng_max, w_rng, pad = rand_convargs NervanaObject.be.bsz = batch_size inp_rng = [0.0, rng_max] dtypeu = np.float32 init_unif = Uniform(low=w_rng[0], high=w_rng[1]) inshape = (nifm, indim, indim) insize = np.prod(inshape) # generate neon conv layer neon_layer = Convolution(fshape=(fshape, fshape, nofm), strides=stride, padding=pad, init=init_unif) # generate the reference layer ref_layer = ConvLayerRef(1, batch_size, identity, inshape[0], inshape[1:3], (fshape, fshape), nofm, stride, dtypeu, padding=pad) # setup input in range inp_rng inpa = np.random.random((insize, batch_size)) inpa *= inp_rng[1] - inp_rng[0] inpa += inp_rng[0] inpa = inpa.astype(dtypeu) inp = neon_layer.be.array(inpa) inp.lshape = inshape # run fprop on neon neon_layer.configure(inshape) neon_layer.prev_layer = True neon_layer.allocate() neon_layer.set_deltas([neon_layer.be.iobuf(inshape)]) neon_out = neon_layer.fprop(inp).get() # pull neon weights into ref layer weights ref_layer.weights = neon_layer.W.get().T ref_layer.fprop(inpa.T) ref_out = np.copy(ref_layer.y) # estimate the numerical precision by # permuting order of ops in ref layer # fprop calculation ref_layer.fprop(inpa.T, permute=True) ref_out_perm = ref_layer.y atol = 4*np.max(np.abs(ref_out - ref_out_perm)) # compare ref and neon layer fprop outputs # using the empirically determined atol assert allclose_with_out(ref_out.T, neon_out, atol=atol, rtol=1.e-4) # generate random deltas array erra = np.random.random(neon_out.shape) erra *= (inp_rng[1] - inp_rng[0]) erra += inp_rng[0] erra = erra.astype(dtypeu) err = neon_layer.be.array(erra) # run neon bprop neon_deltas = neon_layer.bprop(err).get() neon_dW = neon_layer.dW.get() # run ref code bprop ref_layer.bprop(erra.T, 1.0) ref_deltas = np.copy(ref_layer.berror_nopad.T) ref_dW = np.copy(ref_layer.updates) # estimate precision using permutation # of operation order on ref layer code ref_layer.bprop(erra.T, 1.0, permute=True) ref_deltas_perm = ref_layer.berror_nopad.T ref_dW_perm = ref_layer.updates atol = 4*np.max(np.abs(ref_deltas - ref_deltas_perm)) assert allclose_with_out(ref_deltas, neon_deltas, atol=atol, rtol=1.e-4) atol = 4*np.max(np.abs(ref_dW - ref_dW_perm)) assert allclose_with_out(ref_dW.T, neon_dW, atol=atol, rtol=1.e-4) return """ Conv check code adapted from ref-des cnn8 """ def identity(x): return x def identity_prime(x): return np.ones(x.shape) def get_prime(func): if func == identity: return identity_prime class ConvLayerRef(object): def __init__(self, pos, mbs, g, nifm, ifmshape_nopad, fshape, nofm, strides, dtypeu, padding=0): assert g == identity self.ifmheight, self.ifmwidth = ifmshape_nopad self.ifmshape_nopad = ifmshape_nopad self.padding = padding self.ifmshape = (self.ifmheight + 2*padding, self.ifmwidth + 2*padding) self.fshape = fshape self.stride = strides self.fheight, self.fwidth = fshape self.ofmheight = (self.ifmshape[0] - self.fheight) / strides + 1 self.ofmwidth = (self.ifmshape[1] - self.fwidth) / strides + 1 ofmshape = (self.ofmheight, self.ofmwidth) self.ifmsize = self.ifmshape[0]*self.ifmshape[1] self.ifmsize_nopad = self.ifmshape_nopad[0]*self.ifmshape_nopad[1] self.ofmsize = self.ofmheight * self.ofmwidth self.nout = self.ofmsize * nofm self.nifm = nifm self.nofm = nofm self.fsize = nifm * self.fheight * self.fwidth self.weights = np.zeros((nofm, self.fsize), dtype=dtypeu) self.g = g self.gprime = get_prime(g) self.z = np.zeros((mbs, self.nout), dtype=dtypeu) self.y = np.zeros((mbs, self.nout), dtype=dtypeu) ofmstarts = np.array(range(0, (self.ofmsize * nofm), self.ofmsize)) self.ofmlocs = np.zeros((self.ofmsize, nofm), dtype='i32') for dst in range(self.ofmsize): self.ofmlocs[dst, :] = ofmstarts + dst # Figure out the connections with the previous layer. # This is a list of lists. self.links = [] # sfsize = self.fheight * self.fwidth # not used self.makelinks(nifm, self.ifmsize, self.ifmshape, ofmshape, fshape, strides) self.updates = np.zeros(self.weights.shape, dtype=dtypeu) self.updateshards = np.zeros((self.fheight * self.fwidth, nofm, self.fsize), dtype=dtypeu) self.updatebuf = np.zeros((nofm, self.fsize), dtype=dtypeu).copy() self.pos = pos if self.pos > 0: self.bpropbuf = np.zeros((mbs, self.fsize), dtype=dtypeu) self.berror = np.zeros((mbs, self.ifmsize*nifm), dtype=dtypeu) self.berrorshards = np.zeros((self.fheight * self.fwidth, mbs, self.ifmsize * nifm), dtype=dtypeu) def makelinks(self, nifm, ifmsize, ifmshape, ofmshape, fshape, strides): # Figure out local connections to the previous layer. # This function works for any number of dimensions. ndims = len(ifmshape) dimsizes = np.empty(ndims, dtype='int32') for dim in range(ndims): dimsizes[dim] = np.prod(ifmshape[dim:]) links = [] for ofmdim in np.ndindex(ofmshape): # This variable tracks the top left corner of # the receptive field. src = ofmdim[-1] for dim in range(-1, -ndims, -1): src += dimsizes[dim] * ofmdim[dim - 1] src *= strides indlist = list(range(src, src + fshape[-1])) for dim in range(-1, -ndims, -1): indarray = np.array(indlist) for dimind in range(1, fshape[dim - 1]): indlist.extend(list(indarray + dimind * dimsizes[dim])) indarray = np.array(indlist) for ifm in range(1, nifm): indlist.extend(list(indarray + ifm * ifmsize)) links.append(indlist) self.links = np.array(links, dtype='int32') def fprop(self, inputs_nopad, permute=False): # add padding if self.padding == 0: inputs = inputs_nopad.astype(np.float32).copy() else: shp = inputs_nopad.shape shp = [shp[0], self.nifm] shp.extend(self.ifmshape_nopad) in_rs = inputs_nopad.reshape(shp) pad = self.padding inputs = np.zeros((shp[0], self.nifm, self.ifmshape[0], self.ifmshape[1])) inputs[:, :, pad:-pad, pad:-pad] = in_rs inputs = inputs.reshape((shp[0], -1)).astype(np.float32).copy() self.inputs = inputs for dst in range(self.ofmsize): # Compute the weighted average of the receptive field # and store the result within the destination feature map. # Do this for all filters in one shot. rflinks = self.links[dst] A = inputs[:, rflinks] B = self.weights.T if permute: inds = np.random.permutation(A.shape[1]) self.y[:, self.ofmlocs[dst]] = np.dot(A[:, inds], B[inds, :]) else: self.y[:, self.ofmlocs[dst]] = np.dot(A, B) def bprop_naive(self, error, permute=False): for dst in range(self.ofmsize): rflinks = self.links[dst] A = error[:, self.ofmlocs[dst]] B = self.weights if permute: inds = np.random.permutation(A.shape[1]) np.dot(A[:, inds], B[inds, :], self.bpropbuf) else: np.dot(A, B, self.bpropbuf) self.berror[:, rflinks] += self.bpropbuf def bprop(self, error, epsilon, permute=False): inputs = self.inputs if self.pos > 0: # Propagate the errors backwards. self.berror.fill(0.0) self.bprop_naive(error, permute=permute) bshp = [self.berror.shape[0], self.nifm, self.ifmshape[0], self.ifmshape[1]] pad = self.padding # clip the padding out for neon comparison if pad > 0: self.berror_nopad = self.berror.reshape(bshp)[:, :, pad:-pad, pad:-pad] self.berror_nopad = self.berror_nopad.reshape((bshp[0], -1)).copy() else: self.berror_nopad = self.berror.copy() self.updates.fill(0.0) for dst in range(self.ofmsize): # Accumulate weight updates, going over all # corresponding cells in the output feature maps. rflinks = self.links[dst] deltaslice = error[:, self.ofmlocs[dst]] A = deltaslice.T B = inputs[:, rflinks] if permute: inds = np.random.permutation(A.shape[1]) np.dot(A[:, inds], B[inds, :], out=self.updatebuf) else: np.dot(A, B, out=self.updatebuf) self.updates += self.updatebuf # Update the weights. np.multiply(self.updates, epsilon, out=self.updates) # skip updating weights, just return the dW and deltas # np.subtract(self.weights, self.updates, out=self.weights)
{ "content_hash": "e8185e7542629e8482245684809f05a4", "timestamp": "", "source": "github", "line_count": 442, "max_line_length": 86, "avg_line_length": 36.463800904977376, "alnum_prop": 0.5561829124526897, "repo_name": "coufon/neon-distributed", "id": "599b10b5e9132760783cd3bf3cfe3fa16b350940", "size": "16858", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/test_conv_layer.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6534" }, { "name": "C++", "bytes": "67757" }, { "name": "CSS", "bytes": "927996" }, { "name": "Cap'n Proto", "bytes": "448" }, { "name": "Cuda", "bytes": "14937" }, { "name": "Makefile", "bytes": "11145" }, { "name": "Python", "bytes": "1625654" } ], "symlink_target": "" }
package com.opengamma.financial.security; import com.opengamma.financial.security.future.AgricultureFutureSecurity; import com.opengamma.financial.security.future.BondFutureSecurity; import com.opengamma.financial.security.future.DeliverableSwapFutureSecurity; import com.opengamma.financial.security.future.EnergyFutureSecurity; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.financial.security.future.FederalFundsFutureSecurity; import com.opengamma.financial.security.future.IndexFutureSecurity; import com.opengamma.financial.security.future.InterestRateFutureSecurity; import com.opengamma.financial.security.future.MetalFutureSecurity; import com.opengamma.financial.security.future.StockFutureSecurity; /** * @param <T> The return type of the visitor */ public interface FutureSecurityVisitor<T> { T visitAgricultureFutureSecurity(AgricultureFutureSecurity security); T visitBondFutureSecurity(BondFutureSecurity security); T visitEnergyFutureSecurity(EnergyFutureSecurity security); T visitEquityFutureSecurity(EquityFutureSecurity security); T visitEquityIndexDividendFutureSecurity(EquityIndexDividendFutureSecurity security); T visitFXFutureSecurity(FXFutureSecurity security); T visitIndexFutureSecurity(IndexFutureSecurity security); T visitInterestRateFutureSecurity(InterestRateFutureSecurity security); T visitMetalFutureSecurity(MetalFutureSecurity security); T visitStockFutureSecurity(StockFutureSecurity security); T visitDeliverableSwapFutureSecurity(DeliverableSwapFutureSecurity security); T visitFederalFundsFutureSecurity(FederalFundsFutureSecurity security); }
{ "content_hash": "8a3d50ec53e02b77954ee37206c7cd5c", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 87, "avg_line_length": 39.58695652173913, "alnum_prop": 0.8643602416254805, "repo_name": "ChinaQuants/OG-Platform", "id": "81fac851e70fbc7f8fc62123a47ea12f2e160ccd", "size": "1958", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "projects/OG-FinancialTypes/src/main/java/com/opengamma/financial/security/FutureSecurityVisitor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4064" }, { "name": "CSS", "bytes": "212432" }, { "name": "FreeMarker", "bytes": "306032" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "284313" }, { "name": "Java", "bytes": "81106788" }, { "name": "JavaScript", "bytes": "1528695" }, { "name": "PLSQL", "bytes": "105" }, { "name": "PLpgSQL", "bytes": "13175" }, { "name": "Protocol Buffer", "bytes": "53119" }, { "name": "SQLPL", "bytes": "1004" }, { "name": "Shell", "bytes": "10958" } ], "symlink_target": "" }
<?php /** * The contents of this file was generated using the WSDLs as provided by eBay. * * DO NOT EDIT THIS FILE! */ namespace DTS\eBaySDK\MerchantData\Types; /** * * @property string[] $eBayPictureURL * @property string $ExternalPictureURL */ class PictureURLsType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = [ 'eBayPictureURL' => [ 'type' => 'string', 'repeatable' => true, 'attribute' => false, 'elementName' => 'eBayPictureURL' ], 'ExternalPictureURL' => [ 'type' => 'string', 'repeatable' => false, 'attribute' => false, 'elementName' => 'ExternalPictureURL' ] ]; /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = []) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"'; } $this->setValues(__CLASS__, $childValues); } }
{ "content_hash": "4354b34a078c40b37eb7142c49679cbe", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 116, "avg_line_length": 28.574074074074073, "alnum_prop": 0.5748541801685029, "repo_name": "chain24/ebayprocess-lumen", "id": "c25b0b488f210eec7e5634cfe5b995c226a14f56", "size": "1543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/dts/ebay-sdk-php/src/MerchantData/Types/PictureURLsType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "PHP", "bytes": "302973" } ], "symlink_target": "" }
package eu.modaclouds.sla.mediator.model.constraints; public enum TargetClass { NONE(Names.NONE), METHOD(Names.METHOD), INTERNAL_COMPONENT(Names.INTERNAL_COMPONENT), VM(Names.VM); private static class Names { static String NONE = ""; static String METHOD = "Method"; static String INTERNAL_COMPONENT = "InternalComponent"; static String VM = "VM"; } String repr; private TargetClass(String repr) { this.repr = repr; } public static TargetClass fromString(String str) { if (Names.METHOD.equals(str)) { return METHOD; } if (Names.INTERNAL_COMPONENT.equals(str)) { return INTERNAL_COMPONENT; } if (Names.VM.equals(str)) { return VM; } return NONE; } }
{ "content_hash": "ce41fd22b348f58676998608dcd4b8bc", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 63, "avg_line_length": 23.945945945945947, "alnum_prop": 0.5507900677200903, "repo_name": "modaclouds/modaclouds-sla-mediator", "id": "f89ed8a25ecd69c0a8d114b19774018d9cc6154d", "size": "1555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/eu/modaclouds/sla/mediator/model/constraints/TargetClass.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "216459" }, { "name": "Shell", "bytes": "5814" } ], "symlink_target": "" }
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/bytestream.h" #include "unicode/utypes.h" #include "unicode/locid.h" #include "unicode/putil.h" #include "unicode/uchar.h" #include "unicode/uloc.h" #include "unicode/ures.h" #include "unicode/uscript.h" #include "bytesinkutil.h" #include "charstr.h" #include "cmemory.h" #include "cstring.h" #include "ulocimp.h" #include "ustr_imp.h" /** * These are the canonical strings for unknown languages, scripts and regions. **/ static const char* const unknownLanguage = "und"; static const char* const unknownScript = "Zzzz"; static const char* const unknownRegion = "ZZ"; /** * This function looks for the localeID in the likelySubtags resource. * * @param localeID The tag to find. * @param buffer A buffer to hold the matching entry * @param bufferLength The length of the output buffer * @return A pointer to "buffer" if found, or a null pointer if not. */ static const char* U_CALLCONV findLikelySubtags(const char* localeID, char* buffer, int32_t bufferLength, UErrorCode* err) { const char* result = NULL; if (!U_FAILURE(*err)) { int32_t resLen = 0; const UChar* s = NULL; UErrorCode tmpErr = U_ZERO_ERROR; icu::LocalUResourceBundlePointer subtags(ures_openDirect(NULL, "likelySubtags", &tmpErr)); if (U_SUCCESS(tmpErr)) { icu::CharString und; if (localeID != NULL) { if (*localeID == '\0') { localeID = unknownLanguage; } else if (*localeID == '_') { und.append(unknownLanguage, *err); und.append(localeID, *err); if (U_FAILURE(*err)) { return NULL; } localeID = und.data(); } } s = ures_getStringByKey(subtags.getAlias(), localeID, &resLen, &tmpErr); if (U_FAILURE(tmpErr)) { /* * If a resource is missing, it's not really an error, it's * just that we don't have any data for that particular locale ID. */ if (tmpErr != U_MISSING_RESOURCE_ERROR) { *err = tmpErr; } } else if (resLen >= bufferLength) { /* The buffer should never overflow. */ *err = U_INTERNAL_PROGRAM_ERROR; } else { u_UCharsToChars(s, buffer, resLen + 1); if (resLen >= 3 && uprv_strnicmp(buffer, unknownLanguage, 3) == 0 && (resLen == 3 || buffer[3] == '_')) { uprv_memmove(buffer, buffer + 3, resLen - 3 + 1); } result = buffer; } } else { *err = tmpErr; } } return result; } /** * Append a tag to a buffer, adding the separator if necessary. The buffer * must be large enough to contain the resulting tag plus any separator * necessary. The tag must not be a zero-length string. * * @param tag The tag to add. * @param tagLength The length of the tag. * @param buffer The output buffer. * @param bufferLength The length of the output buffer. This is an input/ouput parameter. **/ static void U_CALLCONV appendTag( const char* tag, int32_t tagLength, char* buffer, int32_t* bufferLength, UBool withSeparator) { if (withSeparator) { buffer[*bufferLength] = '_'; ++(*bufferLength); } uprv_memmove( &buffer[*bufferLength], tag, tagLength); *bufferLength += tagLength; } /** * Create a tag string from the supplied parameters. The lang, script and region * parameters may be NULL pointers. If they are, their corresponding length parameters * must be less than or equal to 0. * * If any of the language, script or region parameters are empty, and the alternateTags * parameter is not NULL, it will be parsed for potential language, script and region tags * to be used when constructing the new tag. If the alternateTags parameter is NULL, or * it contains no language tag, the default tag for the unknown language is used. * * If the length of the new string exceeds the capacity of the output buffer, * the function copies as many bytes to the output buffer as it can, and returns * the error U_BUFFER_OVERFLOW_ERROR. * * If an illegal argument is provided, the function returns the error * U_ILLEGAL_ARGUMENT_ERROR. * * Note that this function can return the warning U_STRING_NOT_TERMINATED_WARNING if * the tag string fits in the output buffer, but the null terminator doesn't. * * @param lang The language tag to use. * @param langLength The length of the language tag. * @param script The script tag to use. * @param scriptLength The length of the script tag. * @param region The region tag to use. * @param regionLength The length of the region tag. * @param trailing Any trailing data to append to the new tag. * @param trailingLength The length of the trailing data. * @param alternateTags A string containing any alternate tags. * @param sink The output sink receiving the tag string. * @param err A pointer to a UErrorCode for error reporting. **/ static void U_CALLCONV createTagStringWithAlternates( const char* lang, int32_t langLength, const char* script, int32_t scriptLength, const char* region, int32_t regionLength, const char* trailing, int32_t trailingLength, const char* alternateTags, icu::ByteSink& sink, UErrorCode* err) { if (U_FAILURE(*err)) { goto error; } else if (langLength >= ULOC_LANG_CAPACITY || scriptLength >= ULOC_SCRIPT_CAPACITY || regionLength >= ULOC_COUNTRY_CAPACITY) { goto error; } else { /** * ULOC_FULLNAME_CAPACITY will provide enough capacity * that we can build a string that contains the language, * script and region code without worrying about overrunning * the user-supplied buffer. **/ char tagBuffer[ULOC_FULLNAME_CAPACITY]; int32_t tagLength = 0; UBool regionAppended = FALSE; if (langLength > 0) { appendTag( lang, langLength, tagBuffer, &tagLength, /*withSeparator=*/FALSE); } else if (alternateTags == NULL) { /* * Use the empty string for an unknown language, if * we found no language. */ } else { /* * Parse the alternateTags string for the language. */ char alternateLang[ULOC_LANG_CAPACITY]; int32_t alternateLangLength = sizeof(alternateLang); alternateLangLength = uloc_getLanguage( alternateTags, alternateLang, alternateLangLength, err); if(U_FAILURE(*err) || alternateLangLength >= ULOC_LANG_CAPACITY) { goto error; } else if (alternateLangLength == 0) { /* * Use the empty string for an unknown language, if * we found no language. */ } else { appendTag( alternateLang, alternateLangLength, tagBuffer, &tagLength, /*withSeparator=*/FALSE); } } if (scriptLength > 0) { appendTag( script, scriptLength, tagBuffer, &tagLength, /*withSeparator=*/TRUE); } else if (alternateTags != NULL) { /* * Parse the alternateTags string for the script. */ char alternateScript[ULOC_SCRIPT_CAPACITY]; const int32_t alternateScriptLength = uloc_getScript( alternateTags, alternateScript, sizeof(alternateScript), err); if (U_FAILURE(*err) || alternateScriptLength >= ULOC_SCRIPT_CAPACITY) { goto error; } else if (alternateScriptLength > 0) { appendTag( alternateScript, alternateScriptLength, tagBuffer, &tagLength, /*withSeparator=*/TRUE); } } if (regionLength > 0) { appendTag( region, regionLength, tagBuffer, &tagLength, /*withSeparator=*/TRUE); regionAppended = TRUE; } else if (alternateTags != NULL) { /* * Parse the alternateTags string for the region. */ char alternateRegion[ULOC_COUNTRY_CAPACITY]; const int32_t alternateRegionLength = uloc_getCountry( alternateTags, alternateRegion, sizeof(alternateRegion), err); if (U_FAILURE(*err) || alternateRegionLength >= ULOC_COUNTRY_CAPACITY) { goto error; } else if (alternateRegionLength > 0) { appendTag( alternateRegion, alternateRegionLength, tagBuffer, &tagLength, /*withSeparator=*/TRUE); regionAppended = TRUE; } } /** * Copy the partial tag from our internal buffer to the supplied * target. **/ sink.Append(tagBuffer, tagLength); if (trailingLength > 0) { if (*trailing != '@') { sink.Append("_", 1); if (!regionAppended) { /* extra separator is required */ sink.Append("_", 1); } } /* * Copy the trailing data into the supplied buffer. */ sink.Append(trailing, trailingLength); } return; } error: /** * An overflow indicates the locale ID passed in * is ill-formed. If we got here, and there was * no previous error, it's an implicit overflow. **/ if (*err == U_BUFFER_OVERFLOW_ERROR || U_SUCCESS(*err)) { *err = U_ILLEGAL_ARGUMENT_ERROR; } } /** * Create a tag string from the supplied parameters. The lang, script and region * parameters may be NULL pointers. If they are, their corresponding length parameters * must be less than or equal to 0. If the lang parameter is an empty string, the * default value for an unknown language is written to the output buffer. * * If the length of the new string exceeds the capacity of the output buffer, * the function copies as many bytes to the output buffer as it can, and returns * the error U_BUFFER_OVERFLOW_ERROR. * * If an illegal argument is provided, the function returns the error * U_ILLEGAL_ARGUMENT_ERROR. * * @param lang The language tag to use. * @param langLength The length of the language tag. * @param script The script tag to use. * @param scriptLength The length of the script tag. * @param region The region tag to use. * @param regionLength The length of the region tag. * @param trailing Any trailing data to append to the new tag. * @param trailingLength The length of the trailing data. * @param sink The output sink receiving the tag string. * @param err A pointer to a UErrorCode for error reporting. **/ static void U_CALLCONV createTagString( const char* lang, int32_t langLength, const char* script, int32_t scriptLength, const char* region, int32_t regionLength, const char* trailing, int32_t trailingLength, icu::ByteSink& sink, UErrorCode* err) { createTagStringWithAlternates( lang, langLength, script, scriptLength, region, regionLength, trailing, trailingLength, NULL, sink, err); } /** * Parse the language, script, and region subtags from a tag string, and copy the * results into the corresponding output parameters. The buffers are null-terminated, * unless overflow occurs. * * The langLength, scriptLength, and regionLength parameters are input/output * parameters, and must contain the capacity of their corresponding buffers on * input. On output, they will contain the actual length of the buffers, not * including the null terminator. * * If the length of any of the output subtags exceeds the capacity of the corresponding * buffer, the function copies as many bytes to the output buffer as it can, and returns * the error U_BUFFER_OVERFLOW_ERROR. It will not parse any more subtags once overflow * occurs. * * If an illegal argument is provided, the function returns the error * U_ILLEGAL_ARGUMENT_ERROR. * * @param localeID The locale ID to parse. * @param lang The language tag buffer. * @param langLength The length of the language tag. * @param script The script tag buffer. * @param scriptLength The length of the script tag. * @param region The region tag buffer. * @param regionLength The length of the region tag. * @param err A pointer to a UErrorCode for error reporting. * @return The number of chars of the localeID parameter consumed. **/ static int32_t U_CALLCONV parseTagString( const char* localeID, char* lang, int32_t* langLength, char* script, int32_t* scriptLength, char* region, int32_t* regionLength, UErrorCode* err) { const char* position = localeID; int32_t subtagLength = 0; if(U_FAILURE(*err) || localeID == NULL || lang == NULL || langLength == NULL || script == NULL || scriptLength == NULL || region == NULL || regionLength == NULL) { goto error; } subtagLength = ulocimp_getLanguage(position, lang, *langLength, &position); u_terminateChars(lang, *langLength, subtagLength, err); /* * Note that we explicit consider U_STRING_NOT_TERMINATED_WARNING * to be an error, because it indicates the user-supplied tag is * not well-formed. */ if(U_FAILURE(*err)) { goto error; } *langLength = subtagLength; /* * If no language was present, use the empty string instead. * Otherwise, move past any separator. */ if (_isIDSeparator(*position)) { ++position; } subtagLength = ulocimp_getScript(position, script, *scriptLength, &position); u_terminateChars(script, *scriptLength, subtagLength, err); if(U_FAILURE(*err)) { goto error; } *scriptLength = subtagLength; if (*scriptLength > 0) { if (uprv_strnicmp(script, unknownScript, *scriptLength) == 0) { /** * If the script part is the "unknown" script, then don't return it. **/ *scriptLength = 0; } /* * Move past any separator. */ if (_isIDSeparator(*position)) { ++position; } } subtagLength = ulocimp_getCountry(position, region, *regionLength, &position); u_terminateChars(region, *regionLength, subtagLength, err); if(U_FAILURE(*err)) { goto error; } *regionLength = subtagLength; if (*regionLength > 0) { if (uprv_strnicmp(region, unknownRegion, *regionLength) == 0) { /** * If the region part is the "unknown" region, then don't return it. **/ *regionLength = 0; } } else if (*position != 0 && *position != '@') { /* back up over consumed trailing separator */ --position; } exit: return (int32_t)(position - localeID); error: /** * If we get here, we have no explicit error, it's the result of an * illegal argument. **/ if (!U_FAILURE(*err)) { *err = U_ILLEGAL_ARGUMENT_ERROR; } goto exit; } static UBool U_CALLCONV createLikelySubtagsString( const char* lang, int32_t langLength, const char* script, int32_t scriptLength, const char* region, int32_t regionLength, const char* variants, int32_t variantsLength, icu::ByteSink& sink, UErrorCode* err) { /** * ULOC_FULLNAME_CAPACITY will provide enough capacity * that we can build a string that contains the language, * script and region code without worrying about overrunning * the user-supplied buffer. **/ char likelySubtagsBuffer[ULOC_FULLNAME_CAPACITY]; if(U_FAILURE(*err)) { goto error; } /** * Try the language with the script and region first. **/ if (scriptLength > 0 && regionLength > 0) { const char* likelySubtags = NULL; icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createTagString( lang, langLength, script, scriptLength, region, regionLength, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } likelySubtags = findLikelySubtags( tagBuffer.data(), likelySubtagsBuffer, sizeof(likelySubtagsBuffer), err); if(U_FAILURE(*err)) { goto error; } if (likelySubtags != NULL) { /* Always use the language tag from the maximal string, since it may be more specific than the one provided. */ createTagStringWithAlternates( NULL, 0, NULL, 0, NULL, 0, variants, variantsLength, likelySubtags, sink, err); return TRUE; } } /** * Try the language with just the script. **/ if (scriptLength > 0) { const char* likelySubtags = NULL; icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createTagString( lang, langLength, script, scriptLength, NULL, 0, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } likelySubtags = findLikelySubtags( tagBuffer.data(), likelySubtagsBuffer, sizeof(likelySubtagsBuffer), err); if(U_FAILURE(*err)) { goto error; } if (likelySubtags != NULL) { /* Always use the language tag from the maximal string, since it may be more specific than the one provided. */ createTagStringWithAlternates( NULL, 0, NULL, 0, region, regionLength, variants, variantsLength, likelySubtags, sink, err); return TRUE; } } /** * Try the language with just the region. **/ if (regionLength > 0) { const char* likelySubtags = NULL; icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createTagString( lang, langLength, NULL, 0, region, regionLength, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } likelySubtags = findLikelySubtags( tagBuffer.data(), likelySubtagsBuffer, sizeof(likelySubtagsBuffer), err); if(U_FAILURE(*err)) { goto error; } if (likelySubtags != NULL) { /* Always use the language tag from the maximal string, since it may be more specific than the one provided. */ createTagStringWithAlternates( NULL, 0, script, scriptLength, NULL, 0, variants, variantsLength, likelySubtags, sink, err); return TRUE; } } /** * Finally, try just the language. **/ { const char* likelySubtags = NULL; icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createTagString( lang, langLength, NULL, 0, NULL, 0, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } likelySubtags = findLikelySubtags( tagBuffer.data(), likelySubtagsBuffer, sizeof(likelySubtagsBuffer), err); if(U_FAILURE(*err)) { goto error; } if (likelySubtags != NULL) { /* Always use the language tag from the maximal string, since it may be more specific than the one provided. */ createTagStringWithAlternates( NULL, 0, script, scriptLength, region, regionLength, variants, variantsLength, likelySubtags, sink, err); return TRUE; } } return FALSE; error: if (!U_FAILURE(*err)) { *err = U_ILLEGAL_ARGUMENT_ERROR; } return FALSE; } #define CHECK_TRAILING_VARIANT_SIZE(trailing, trailingLength) \ { int32_t count = 0; \ int32_t i; \ for (i = 0; i < trailingLength; i++) { \ if (trailing[i] == '-' || trailing[i] == '_') { \ count = 0; \ if (count > 8) { \ goto error; \ } \ } else if (trailing[i] == '@') { \ break; \ } else if (count > 8) { \ goto error; \ } else { \ count++; \ } \ } \ } static void _uloc_addLikelySubtags(const char* localeID, icu::ByteSink& sink, UErrorCode* err) { char lang[ULOC_LANG_CAPACITY]; int32_t langLength = sizeof(lang); char script[ULOC_SCRIPT_CAPACITY]; int32_t scriptLength = sizeof(script); char region[ULOC_COUNTRY_CAPACITY]; int32_t regionLength = sizeof(region); const char* trailing = ""; int32_t trailingLength = 0; int32_t trailingIndex = 0; UBool success = FALSE; if(U_FAILURE(*err)) { goto error; } if (localeID == NULL) { goto error; } trailingIndex = parseTagString( localeID, lang, &langLength, script, &scriptLength, region, &regionLength, err); if(U_FAILURE(*err)) { /* Overflow indicates an illegal argument error */ if (*err == U_BUFFER_OVERFLOW_ERROR) { *err = U_ILLEGAL_ARGUMENT_ERROR; } goto error; } /* Find the length of the trailing portion. */ while (_isIDSeparator(localeID[trailingIndex])) { trailingIndex++; } trailing = &localeID[trailingIndex]; trailingLength = (int32_t)uprv_strlen(trailing); CHECK_TRAILING_VARIANT_SIZE(trailing, trailingLength); success = createLikelySubtagsString( lang, langLength, script, scriptLength, region, regionLength, trailing, trailingLength, sink, err); if (!success) { const int32_t localIDLength = (int32_t)uprv_strlen(localeID); /* * If we get here, we need to return localeID. */ sink.Append(localeID, localIDLength); } return; error: if (!U_FAILURE(*err)) { *err = U_ILLEGAL_ARGUMENT_ERROR; } } static void _uloc_minimizeSubtags(const char* localeID, icu::ByteSink& sink, UErrorCode* err) { icu::CharString maximizedTagBuffer; char lang[ULOC_LANG_CAPACITY]; int32_t langLength = sizeof(lang); char script[ULOC_SCRIPT_CAPACITY]; int32_t scriptLength = sizeof(script); char region[ULOC_COUNTRY_CAPACITY]; int32_t regionLength = sizeof(region); const char* trailing = ""; int32_t trailingLength = 0; int32_t trailingIndex = 0; if(U_FAILURE(*err)) { goto error; } else if (localeID == NULL) { goto error; } trailingIndex = parseTagString( localeID, lang, &langLength, script, &scriptLength, region, &regionLength, err); if(U_FAILURE(*err)) { /* Overflow indicates an illegal argument error */ if (*err == U_BUFFER_OVERFLOW_ERROR) { *err = U_ILLEGAL_ARGUMENT_ERROR; } goto error; } /* Find the spot where the variants or the keywords begin, if any. */ while (_isIDSeparator(localeID[trailingIndex])) { trailingIndex++; } trailing = &localeID[trailingIndex]; trailingLength = (int32_t)uprv_strlen(trailing); CHECK_TRAILING_VARIANT_SIZE(trailing, trailingLength); { icu::CharString base; { icu::CharStringByteSink sink(&base); createTagString( lang, langLength, script, scriptLength, region, regionLength, NULL, 0, sink, err); } /** * First, we need to first get the maximization * from AddLikelySubtags. **/ { icu::CharStringByteSink sink(&maximizedTagBuffer); ulocimp_addLikelySubtags(base.data(), sink, err); } } if(U_FAILURE(*err)) { goto error; } /** * Start first with just the language. **/ { icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createLikelySubtagsString( lang, langLength, NULL, 0, NULL, 0, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } else if (!tagBuffer.isEmpty() && uprv_strnicmp( maximizedTagBuffer.data(), tagBuffer.data(), tagBuffer.length()) == 0) { createTagString( lang, langLength, NULL, 0, NULL, 0, trailing, trailingLength, sink, err); return; } } /** * Next, try the language and region. **/ if (regionLength > 0) { icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createLikelySubtagsString( lang, langLength, NULL, 0, region, regionLength, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } else if (uprv_strnicmp( maximizedTagBuffer.data(), tagBuffer.data(), tagBuffer.length()) == 0) { createTagString( lang, langLength, NULL, 0, region, regionLength, trailing, trailingLength, sink, err); return; } } /** * Finally, try the language and script. This is our last chance, * since trying with all three subtags would only yield the * maximal version that we already have. **/ if (scriptLength > 0 && regionLength > 0) { icu::CharString tagBuffer; { icu::CharStringByteSink sink(&tagBuffer); createLikelySubtagsString( lang, langLength, script, scriptLength, NULL, 0, NULL, 0, sink, err); } if(U_FAILURE(*err)) { goto error; } else if (uprv_strnicmp( maximizedTagBuffer.data(), tagBuffer.data(), tagBuffer.length()) == 0) { createTagString( lang, langLength, script, scriptLength, NULL, 0, trailing, trailingLength, sink, err); return; } } { /** * If we got here, return the locale ID parameter. **/ const int32_t localeIDLength = (int32_t)uprv_strlen(localeID); sink.Append(localeID, localeIDLength); return; } error: if (!U_FAILURE(*err)) { *err = U_ILLEGAL_ARGUMENT_ERROR; } } static UBool do_canonicalize(const char* localeID, char* buffer, int32_t bufferCapacity, UErrorCode* err) { uloc_canonicalize( localeID, buffer, bufferCapacity, err); if (*err == U_STRING_NOT_TERMINATED_WARNING || *err == U_BUFFER_OVERFLOW_ERROR) { *err = U_ILLEGAL_ARGUMENT_ERROR; return FALSE; } else if (U_FAILURE(*err)) { return FALSE; } else { return TRUE; } } U_CAPI int32_t U_EXPORT2 uloc_addLikelySubtags(const char* localeID, char* maximizedLocaleID, int32_t maximizedLocaleIDCapacity, UErrorCode* status) { if (U_FAILURE(*status)) { return 0; } icu::CheckedArrayByteSink sink( maximizedLocaleID, maximizedLocaleIDCapacity); ulocimp_addLikelySubtags(localeID, sink, status); int32_t reslen = sink.NumberOfBytesAppended(); if (U_FAILURE(*status)) { return sink.Overflowed() ? reslen : -1; } if (sink.Overflowed()) { *status = U_BUFFER_OVERFLOW_ERROR; } else { u_terminateChars( maximizedLocaleID, maximizedLocaleIDCapacity, reslen, status); } return reslen; } U_CAPI void U_EXPORT2 ulocimp_addLikelySubtags(const char* localeID, icu::ByteSink& sink, UErrorCode* status) { char localeBuffer[ULOC_FULLNAME_CAPACITY]; if (do_canonicalize(localeID, localeBuffer, sizeof localeBuffer, status)) { _uloc_addLikelySubtags(localeBuffer, sink, status); } } U_CAPI int32_t U_EXPORT2 uloc_minimizeSubtags(const char* localeID, char* minimizedLocaleID, int32_t minimizedLocaleIDCapacity, UErrorCode* status) { if (U_FAILURE(*status)) { return 0; } icu::CheckedArrayByteSink sink( minimizedLocaleID, minimizedLocaleIDCapacity); ulocimp_minimizeSubtags(localeID, sink, status); int32_t reslen = sink.NumberOfBytesAppended(); if (U_FAILURE(*status)) { return sink.Overflowed() ? reslen : -1; } if (sink.Overflowed()) { *status = U_BUFFER_OVERFLOW_ERROR; } else { u_terminateChars( minimizedLocaleID, minimizedLocaleIDCapacity, reslen, status); } return reslen; } U_CAPI void U_EXPORT2 ulocimp_minimizeSubtags(const char* localeID, icu::ByteSink& sink, UErrorCode* status) { char localeBuffer[ULOC_FULLNAME_CAPACITY]; if (do_canonicalize(localeID, localeBuffer, sizeof localeBuffer, status)) { _uloc_minimizeSubtags(localeBuffer, sink, status); } } // Pairs of (language subtag, + or -) for finding out fast if common languages // are LTR (minus) or RTL (plus). static const char LANG_DIR_STRING[] = "root-en-es-pt-zh-ja-ko-de-fr-it-ar+he+fa+ru-nl-pl-th-tr-"; // Implemented here because this calls ulocimp_addLikelySubtags(). U_CAPI UBool U_EXPORT2 uloc_isRightToLeft(const char *locale) { UErrorCode errorCode = U_ZERO_ERROR; char script[8]; int32_t scriptLength = uloc_getScript(locale, script, UPRV_LENGTHOF(script), &errorCode); if (U_FAILURE(errorCode) || errorCode == U_STRING_NOT_TERMINATED_WARNING || scriptLength == 0) { // Fastpath: We know the likely scripts and their writing direction // for some common languages. errorCode = U_ZERO_ERROR; char lang[8]; int32_t langLength = uloc_getLanguage(locale, lang, UPRV_LENGTHOF(lang), &errorCode); if (U_FAILURE(errorCode) || errorCode == U_STRING_NOT_TERMINATED_WARNING) { return FALSE; } if (langLength > 0) { const char* langPtr = uprv_strstr(LANG_DIR_STRING, lang); if (langPtr != NULL) { switch (langPtr[langLength]) { case '-': return FALSE; case '+': return TRUE; default: break; // partial match of a longer code } } } // Otherwise, find the likely script. errorCode = U_ZERO_ERROR; icu::CharString likely; { icu::CharStringByteSink sink(&likely); ulocimp_addLikelySubtags(locale, sink, &errorCode); } if (U_FAILURE(errorCode) || errorCode == U_STRING_NOT_TERMINATED_WARNING) { return FALSE; } scriptLength = uloc_getScript(likely.data(), script, UPRV_LENGTHOF(script), &errorCode); if (U_FAILURE(errorCode) || errorCode == U_STRING_NOT_TERMINATED_WARNING || scriptLength == 0) { return FALSE; } } UScriptCode scriptCode = (UScriptCode)u_getPropertyValueEnum(UCHAR_SCRIPT, script); return uscript_isRightToLeft(scriptCode); } U_NAMESPACE_BEGIN UBool Locale::isRightToLeft() const { return uloc_isRightToLeft(getBaseName()); } U_NAMESPACE_END // The following must at least allow for rg key value (6) plus terminator (1). #define ULOC_RG_BUFLEN 8 U_CAPI int32_t U_EXPORT2 ulocimp_getRegionForSupplementalData(const char *localeID, UBool inferRegion, char *region, int32_t regionCapacity, UErrorCode* status) { if (U_FAILURE(*status)) { return 0; } char rgBuf[ULOC_RG_BUFLEN]; UErrorCode rgStatus = U_ZERO_ERROR; // First check for rg keyword value int32_t rgLen = uloc_getKeywordValue(localeID, "rg", rgBuf, ULOC_RG_BUFLEN, &rgStatus); if (U_FAILURE(rgStatus) || rgLen != 6) { rgLen = 0; } else { // rgBuf guaranteed to be zero terminated here, with text len 6 char *rgPtr = rgBuf; for (; *rgPtr!= 0; rgPtr++) { *rgPtr = uprv_toupper(*rgPtr); } rgLen = (uprv_strcmp(rgBuf+2, "ZZZZ") == 0)? 2: 0; } if (rgLen == 0) { // No valid rg keyword value, try for unicode_region_subtag rgLen = uloc_getCountry(localeID, rgBuf, ULOC_RG_BUFLEN, status); if (U_FAILURE(*status)) { rgLen = 0; } else if (rgLen == 0 && inferRegion) { // no unicode_region_subtag but inferRegion TRUE, try likely subtags rgStatus = U_ZERO_ERROR; icu::CharString locBuf; { icu::CharStringByteSink sink(&locBuf); ulocimp_addLikelySubtags(localeID, sink, &rgStatus); } if (U_SUCCESS(rgStatus)) { rgLen = uloc_getCountry(locBuf.data(), rgBuf, ULOC_RG_BUFLEN, status); if (U_FAILURE(*status)) { rgLen = 0; } } } } rgBuf[rgLen] = 0; uprv_strncpy(region, rgBuf, regionCapacity); return u_terminateChars(region, regionCapacity, rgLen, status); }
{ "content_hash": "0018340f72c6afe0d7758596ce7c2d5a", "timestamp": "", "source": "github", "line_count": 1341, "max_line_length": 98, "avg_line_length": 28.653989560029828, "alnum_prop": 0.5148210800260247, "repo_name": "graetzer/arangodb", "id": "843cd8f391b50a5931bb380e6bbb048a4e78f9d3", "size": "39032", "binary": false, "copies": "5", "ref": "refs/heads/devel", "path": "3rdParty/V8/v7.9.317/third_party/icu/source/common/loclikely.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "391227" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "63025" }, { "name": "C", "bytes": "7952921" }, { "name": "C#", "bytes": "96431" }, { "name": "C++", "bytes": "274543069" }, { "name": "CMake", "bytes": "646773" }, { "name": "CSS", "bytes": "1054160" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "259402" }, { "name": "Emacs Lisp", "bytes": "14637" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groovy", "bytes": "131" }, { "name": "HTML", "bytes": "2215528" }, { "name": "Java", "bytes": "922156" }, { "name": "JavaScript", "bytes": "53300241" }, { "name": "LLVM", "bytes": "24129" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "17899" }, { "name": "M4", "bytes": "575204" }, { "name": "Makefile", "bytes": "492694" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "28404" }, { "name": "Objective-C", "bytes": "18435" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "107274" }, { "name": "Pascal", "bytes": "150599" }, { "name": "Perl", "bytes": "564374" }, { "name": "Perl6", "bytes": "9918" }, { "name": "Python", "bytes": "4527647" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "1007604" }, { "name": "Ruby", "bytes": "929950" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "424800" }, { "name": "Swift", "bytes": "116" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XSLT", "bytes": "551977" }, { "name": "Yacc", "bytes": "53072" } ], "symlink_target": "" }
package slack // Group contains all the information for a group type Group struct { GroupConversation IsGroup bool `json:"is_group"` }
{ "content_hash": "b82f5d233f86754e98d8af0d69b222b4", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 49, "avg_line_length": 19.714285714285715, "alnum_prop": 0.7608695652173914, "repo_name": "jirwin/quadlek", "id": "b77f909dbd6ff9a5fd7897ea6cbe17dbbb52286a", "size": "138", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "vendor/github.com/slack-go/slack/groups.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "107102" }, { "name": "Makefile", "bytes": "64" }, { "name": "Starlark", "bytes": "282" } ], "symlink_target": "" }
package ch.uzh.ifi.pdeboer.pplib.examples.optimizationSimulation import ch.uzh.ifi.pdeboer.pplib.hcomp.HCompPortalAdapter import ch.uzh.ifi.pdeboer.pplib.process.entities._ import ch.uzh.ifi.pdeboer.pplib.process.recombination._ import ch.uzh.ifi.pdeboer.pplib.process.stdlib.{ContestWithStatisticalReductionProcess, ContestWithBeatByKVotingProcess, FixPatchProcess} /** * Created by pdeboer on 12/05/15. */ case class MCOptimizationResult(text: String, costInCents: Int) extends Comparable[MCOptimizationResult] with ResultWithCostfunction { override def compareTo(o: MCOptimizationResult): Int = costFunctionResult.compareTo(o.costFunctionResult) override def costFunctionResult: Double = MCOptimizeConstants.answerDistance(text.toInt) + costInCents.toDouble } class MCOptimizationDeepStructure extends SimpleDeepStructure[String, MCOptimizationResult] { override def run(data: String, blueprint: RecombinedProcessBlueprint): MCOptimizationResult = { val options: List[IndexedPatch] = IndexedPatch.from(data, ",") type inputType = List[Patch] type outputType = Patch //create an instance of the recombined process that's currently evaluated val generatedShorteningProcess = blueprint.createProcess[inputType, outputType](forcedParams = Map(FixPatchProcess.ALL_DATA.key -> options)) //run this process and get resulting, shortened text val result: Patch = generatedShorteningProcess.process(options) //return the result MCOptimizationResult(result.value, generatedShorteningProcess match { case x: HCompPortalAccess => x.portal.cost case _ => throw new IllegalArgumentException("this only works for hcomp portals"); 0 }) } val HCOMP_PORTAL_TO_USE: HCompPortalAdapter = new MCOptimizationMockPortal() override def defineSimpleRecombinationSearchSpace: RecombinationSearchSpaceDefinition[_ <: ProcessStub[_, _]] = RecombinationSearchSpaceDefinition[DecideProcess[_ <: List[Patch], _ <: Patch]]( RecombinationHints.create(Map( RecombinationHints.DEFAULT_HINTS -> { new AddedParameterRecombinationHint[Int](DefaultParameters.MAX_ITERATIONS, 20 to 30) :: new AddedParameterRecombinationHint[Int](DefaultParameters.WORKER_COUNT, 1 to 10) :: new AddedParameterRecombinationHint[Int](ContestWithBeatByKVotingProcess.K, 1 to 10) :: new AddedParameterRecombinationHint[Double](ContestWithStatisticalReductionProcess.CONFIDENCE_PARAMETER, (1 to 8).map(i => 0.6 + (i.toDouble * .05))) :: RecombinationHints.hcompPlatform(List(HCOMP_PORTAL_TO_USE)) ::: RecombinationHints.instructions(List( new InstructionData(actionName = "select the element you like most", detailedDescription = "yeah, that one"))) }) ) ) }
{ "content_hash": "c8ef07b1b042af64851c8fa0389012d1", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 158, "avg_line_length": 51.0377358490566, "alnum_prop": 0.7837338262476895, "repo_name": "uzh/PPLib", "id": "e2287a5336298737639d659cfc1985ac9e00c7fb", "size": "2705", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/ch/uzh/ifi/pdeboer/pplib/examples/optimizationSimulation/MCOptimizationDeepStructure.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "880" }, { "name": "Scala", "bytes": "448955" } ], "symlink_target": "" }
/* Layout helpers ----------------------------------*/ .ui-helper-hidden { display: none; } .ui-helper-hidden-accessible { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } .ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; border-collapse: collapse; } .ui-helper-clearfix:after { clear: both; } .ui-helper-clearfix { min-height: 0; /* support: IE7 */ } .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); /* support: IE8 */ } .ui-front { z-index: 100; } /* Interaction Cues ----------------------------------*/ .ui-state-disabled { cursor: default !important; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } /* Misc visuals ----------------------------------*/ /* Overlays */ .ui-widget-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } .ui-tooltip { padding: 8px; position: absolute; z-index: 9999; max-width: 300px; -webkit-box-shadow: 0 0 5px #aaa; box-shadow: 0 0 5px #aaa; } body .ui-tooltip { border-width: 2px; } /* Component containers ----------------------------------*/ .ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 1.1em; } .ui-widget .ui-widget { font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; } .ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url("/assets/ui-bg_flat_75_ffffff_40x100.png") 50% 50% repeat-x; color: #222222; } .ui-widget-content a { color: #222222; } .ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url("/assets/ui-bg_highlight-soft_75_cccccc_1x100.png") 50% 50% repeat-x; color: #222222; font-weight: bold; } .ui-widget-header a { color: #222222; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3; background: #e6e6e6 url("/assets/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x; font-weight: normal; color: #555555; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999; background: #dadada url("/assets/ui-bg_glass_75_dadada_1x400.png") 50% 50% repeat-x; font-weight: normal; color: #212121; } .ui-state-hover a, .ui-state-hover a:hover, .ui-state-hover a:link, .ui-state-hover a:visited, .ui-state-focus a, .ui-state-focus a:hover, .ui-state-focus a:link, .ui-state-focus a:visited { color: #212121; text-decoration: none; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa; background: #ffffff url("/assets/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x; font-weight: normal; color: #212121; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121; text-decoration: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #fcefa1; background: #fbf9ee url("/assets/ui-bg_glass_55_fbf9ee_1x400.png") 50% 50% repeat-x; color: #363636; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { color: #363636; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #cd0a0a; background: #fef1ec url("/assets/ui-bg_glass_95_fef1ec_1x400.png") 50% 50% repeat-x; color: #cd0a0a; } .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; } .ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; } .ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); /* support: IE8 */ font-weight: normal; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); /* support: IE8 */ background-image: none; } .ui-state-disabled .ui-icon { filter:Alpha(Opacity=35); /* support: IE8 - See #6059 */ } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { width: 16px; height: 16px; } .ui-icon, .ui-widget-content .ui-icon { background-image: url("/assets/ui-icons_222222_256x240.png"); } .ui-widget-header .ui-icon { background-image: url("/assets/ui-icons_222222_256x240.png"); } .ui-state-default .ui-icon { background-image: url("/assets/ui-icons_888888_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { background-image: url("/assets/ui-icons_454545_256x240.png"); } .ui-state-active .ui-icon { background-image: url("/assets/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { background-image: url("/assets/ui-icons_2e83ff_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url("/assets/ui-icons_cd0a0a_256x240.png"); } /* positioning */ .ui-icon-blank { background-position: 16px 16px; } .ui-icon-carat-1-n { background-position: 0 0; } .ui-icon-carat-1-ne { background-position: -16px 0; } .ui-icon-carat-1-e { background-position: -32px 0; } .ui-icon-carat-1-se { background-position: -48px 0; } .ui-icon-carat-1-s { background-position: -64px 0; } .ui-icon-carat-1-sw { background-position: -80px 0; } .ui-icon-carat-1-w { background-position: -96px 0; } .ui-icon-carat-1-nw { background-position: -112px 0; } .ui-icon-carat-2-n-s { background-position: -128px 0; } .ui-icon-carat-2-e-w { background-position: -144px 0; } .ui-icon-triangle-1-n { background-position: 0 -16px; } .ui-icon-triangle-1-ne { background-position: -16px -16px; } .ui-icon-triangle-1-e { background-position: -32px -16px; } .ui-icon-triangle-1-se { background-position: -48px -16px; } .ui-icon-triangle-1-s { background-position: -64px -16px; } .ui-icon-triangle-1-sw { background-position: -80px -16px; } .ui-icon-triangle-1-w { background-position: -96px -16px; } .ui-icon-triangle-1-nw { background-position: -112px -16px; } .ui-icon-triangle-2-n-s { background-position: -128px -16px; } .ui-icon-triangle-2-e-w { background-position: -144px -16px; } .ui-icon-arrow-1-n { background-position: 0 -32px; } .ui-icon-arrow-1-ne { background-position: -16px -32px; } .ui-icon-arrow-1-e { background-position: -32px -32px; } .ui-icon-arrow-1-se { background-position: -48px -32px; } .ui-icon-arrow-1-s { background-position: -64px -32px; } .ui-icon-arrow-1-sw { background-position: -80px -32px; } .ui-icon-arrow-1-w { background-position: -96px -32px; } .ui-icon-arrow-1-nw { background-position: -112px -32px; } .ui-icon-arrow-2-n-s { background-position: -128px -32px; } .ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } .ui-icon-arrow-2-e-w { background-position: -160px -32px; } .ui-icon-arrow-2-se-nw { background-position: -176px -32px; } .ui-icon-arrowstop-1-n { background-position: -192px -32px; } .ui-icon-arrowstop-1-e { background-position: -208px -32px; } .ui-icon-arrowstop-1-s { background-position: -224px -32px; } .ui-icon-arrowstop-1-w { background-position: -240px -32px; } .ui-icon-arrowthick-1-n { background-position: 0 -48px; } .ui-icon-arrowthick-1-ne { background-position: -16px -48px; } .ui-icon-arrowthick-1-e { background-position: -32px -48px; } .ui-icon-arrowthick-1-se { background-position: -48px -48px; } .ui-icon-arrowthick-1-s { background-position: -64px -48px; } .ui-icon-arrowthick-1-sw { background-position: -80px -48px; } .ui-icon-arrowthick-1-w { background-position: -96px -48px; } .ui-icon-arrowthick-1-nw { background-position: -112px -48px; } .ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } .ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } .ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } .ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } .ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } .ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } .ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } .ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } .ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } .ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } .ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } .ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } .ui-icon-arrowreturn-1-w { background-position: -64px -64px; } .ui-icon-arrowreturn-1-n { background-position: -80px -64px; } .ui-icon-arrowreturn-1-e { background-position: -96px -64px; } .ui-icon-arrowreturn-1-s { background-position: -112px -64px; } .ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } .ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } .ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } .ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } .ui-icon-arrow-4 { background-position: 0 -80px; } .ui-icon-arrow-4-diag { background-position: -16px -80px; } .ui-icon-extlink { background-position: -32px -80px; } .ui-icon-newwin { background-position: -48px -80px; } .ui-icon-refresh { background-position: -64px -80px; } .ui-icon-shuffle { background-position: -80px -80px; } .ui-icon-transfer-e-w { background-position: -96px -80px; } .ui-icon-transferthick-e-w { background-position: -112px -80px; } .ui-icon-folder-collapsed { background-position: 0 -96px; } .ui-icon-folder-open { background-position: -16px -96px; } .ui-icon-document { background-position: -32px -96px; } .ui-icon-document-b { background-position: -48px -96px; } .ui-icon-note { background-position: -64px -96px; } .ui-icon-mail-closed { background-position: -80px -96px; } .ui-icon-mail-open { background-position: -96px -96px; } .ui-icon-suitcase { background-position: -112px -96px; } .ui-icon-comment { background-position: -128px -96px; } .ui-icon-person { background-position: -144px -96px; } .ui-icon-print { background-position: -160px -96px; } .ui-icon-trash { background-position: -176px -96px; } .ui-icon-locked { background-position: -192px -96px; } .ui-icon-unlocked { background-position: -208px -96px; } .ui-icon-bookmark { background-position: -224px -96px; } .ui-icon-tag { background-position: -240px -96px; } .ui-icon-home { background-position: 0 -112px; } .ui-icon-flag { background-position: -16px -112px; } .ui-icon-calendar { background-position: -32px -112px; } .ui-icon-cart { background-position: -48px -112px; } .ui-icon-pencil { background-position: -64px -112px; } .ui-icon-clock { background-position: -80px -112px; } .ui-icon-disk { background-position: -96px -112px; } .ui-icon-calculator { background-position: -112px -112px; } .ui-icon-zoomin { background-position: -128px -112px; } .ui-icon-zoomout { background-position: -144px -112px; } .ui-icon-search { background-position: -160px -112px; } .ui-icon-wrench { background-position: -176px -112px; } .ui-icon-gear { background-position: -192px -112px; } .ui-icon-heart { background-position: -208px -112px; } .ui-icon-star { background-position: -224px -112px; } .ui-icon-link { background-position: -240px -112px; } .ui-icon-cancel { background-position: 0 -128px; } .ui-icon-plus { background-position: -16px -128px; } .ui-icon-plusthick { background-position: -32px -128px; } .ui-icon-minus { background-position: -48px -128px; } .ui-icon-minusthick { background-position: -64px -128px; } .ui-icon-close { background-position: -80px -128px; } .ui-icon-closethick { background-position: -96px -128px; } .ui-icon-key { background-position: -112px -128px; } .ui-icon-lightbulb { background-position: -128px -128px; } .ui-icon-scissors { background-position: -144px -128px; } .ui-icon-clipboard { background-position: -160px -128px; } .ui-icon-copy { background-position: -176px -128px; } .ui-icon-contact { background-position: -192px -128px; } .ui-icon-image { background-position: -208px -128px; } .ui-icon-video { background-position: -224px -128px; } .ui-icon-script { background-position: -240px -128px; } .ui-icon-alert { background-position: 0 -144px; } .ui-icon-info { background-position: -16px -144px; } .ui-icon-notice { background-position: -32px -144px; } .ui-icon-help { background-position: -48px -144px; } .ui-icon-check { background-position: -64px -144px; } .ui-icon-bullet { background-position: -80px -144px; } .ui-icon-radio-on { background-position: -96px -144px; } .ui-icon-radio-off { background-position: -112px -144px; } .ui-icon-pin-w { background-position: -128px -144px; } .ui-icon-pin-s { background-position: -144px -144px; } .ui-icon-play { background-position: 0 -160px; } .ui-icon-pause { background-position: -16px -160px; } .ui-icon-seek-next { background-position: -32px -160px; } .ui-icon-seek-prev { background-position: -48px -160px; } .ui-icon-seek-end { background-position: -64px -160px; } .ui-icon-seek-start { background-position: -80px -160px; } /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ .ui-icon-seek-first { background-position: -80px -160px; } .ui-icon-stop { background-position: -96px -160px; } .ui-icon-eject { background-position: -112px -160px; } .ui-icon-volume-off { background-position: -128px -160px; } .ui-icon-volume-on { background-position: -144px -160px; } .ui-icon-power { background-position: 0 -176px; } .ui-icon-signal-diag { background-position: -16px -176px; } .ui-icon-signal { background-position: -32px -176px; } .ui-icon-battery-0 { background-position: -48px -176px; } .ui-icon-battery-1 { background-position: -64px -176px; } .ui-icon-battery-2 { background-position: -80px -176px; } .ui-icon-battery-3 { background-position: -96px -176px; } .ui-icon-circle-plus { background-position: 0 -192px; } .ui-icon-circle-minus { background-position: -16px -192px; } .ui-icon-circle-close { background-position: -32px -192px; } .ui-icon-circle-triangle-e { background-position: -48px -192px; } .ui-icon-circle-triangle-s { background-position: -64px -192px; } .ui-icon-circle-triangle-w { background-position: -80px -192px; } .ui-icon-circle-triangle-n { background-position: -96px -192px; } .ui-icon-circle-arrow-e { background-position: -112px -192px; } .ui-icon-circle-arrow-s { background-position: -128px -192px; } .ui-icon-circle-arrow-w { background-position: -144px -192px; } .ui-icon-circle-arrow-n { background-position: -160px -192px; } .ui-icon-circle-zoomin { background-position: -176px -192px; } .ui-icon-circle-zoomout { background-position: -192px -192px; } .ui-icon-circle-check { background-position: -208px -192px; } .ui-icon-circlesmall-plus { background-position: 0 -208px; } .ui-icon-circlesmall-minus { background-position: -16px -208px; } .ui-icon-circlesmall-close { background-position: -32px -208px; } .ui-icon-squaresmall-plus { background-position: -48px -208px; } .ui-icon-squaresmall-minus { background-position: -64px -208px; } .ui-icon-squaresmall-close { background-position: -80px -208px; } .ui-icon-grip-dotted-vertical { background-position: 0 -224px; } .ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } .ui-icon-grip-solid-vertical { background-position: -32px -224px; } .ui-icon-grip-solid-horizontal { background-position: -48px -224px; } .ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } .ui-icon-grip-diagonal-se { background-position: -80px -224px; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { border-top-left-radius: 4px; } .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { border-top-right-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { border-bottom-left-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { border-bottom-right-radius: 4px; } /* Overlays */ .ui-widget-overlay { background: #aaaaaa url("/assets/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .3; filter: Alpha(Opacity=30); /* support: IE8 */ } .ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url("/assets/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .3; filter: Alpha(Opacity=30); /* support: IE8 */ border-radius: 8px; }
{ "content_hash": "d1585fc0072e168bd6b8a98176caac2a", "timestamp": "", "source": "github", "line_count": 492, "max_line_length": 94, "avg_line_length": 34.8760162601626, "alnum_prop": 0.6896672300250597, "repo_name": "cvetter34/entership-engine", "id": "1ba6c2b437bc232f5265e72c843a9ea09d870d31", "size": "18677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/assets/stylesheets/jquery-ui.css", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "11977" }, { "name": "CoffeeScript", "bytes": "4477" }, { "name": "JavaScript", "bytes": "200051" }, { "name": "Ruby", "bytes": "34754" } ], "symlink_target": "" }
package org.springframework.osgi.service.importer.support; import org.springframework.core.enums.StaticLabeledEnum; import org.springframework.core.enums.StaticLabeledEnumResolver; /** * Enum-like class containing the OSGi service importer thread context class loader (TCCL) management options. * * @author Costin Leau * @deprecated As of Spring DM 2.0, replaced by {@link ImportContextClassLoaderEnum} */ public class ImportContextClassLoader extends StaticLabeledEnum { private static final long serialVersionUID = -7054525261814306077L; /** * The TCCL will not be managed upon service invocation. */ public static final ImportContextClassLoader UNMANAGED = new ImportContextClassLoader(0, "UNMANAGED"); /** * The TCCL will be set to that of the service provider upon service invocation. */ public static final ImportContextClassLoader SERVICE_PROVIDER = new ImportContextClassLoader(1, "SERVICE_PROVIDER"); /** * The TCCL will be set to that of the client upon service invocation. */ public static final ImportContextClassLoader CLIENT = new ImportContextClassLoader(2, "CLIENT"); /** * Constructs a new <code>ImportContextClassLoader</code> instance. * * @param code * @param label */ private ImportContextClassLoader(int code, String label) { super(code, label); } ImportContextClassLoaderEnum getImportContextClassLoaderEnum() { return ImportContextClassLoaderEnum.valueOf(getLabel()); } static ImportContextClassLoader getImportContextClassLoader(ImportContextClassLoaderEnum enm) { return (ImportContextClassLoader) StaticLabeledEnumResolver.instance().getLabeledEnumByLabel( ImportContextClassLoader.class, enm.name()); } }
{ "content_hash": "dcd6661f609318b1f9930cfaebcfda22", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 117, "avg_line_length": 34.27450980392157, "alnum_prop": 0.7597254004576659, "repo_name": "kurtharriger/spring-osgi", "id": "92e5ff4189c4b67cc66c1888a846bdcaeff98195", "size": "2385", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/src/main/java/org/springframework/osgi/service/importer/support/ImportContextClassLoader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3099097" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) 2009-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>org.wso2.carbon.registry</groupId> <artifactId>carbon-registry</artifactId> <version>4.5.3-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>webdav-feature</artifactId> <packaging>pom</packaging> <name>WSO2 Carbon - Registry Webdav Module</name> <url>http://wso2.org</url> <modules> <module>org.wso2.carbon.registry.webdav.feature</module> </modules> </project>
{ "content_hash": "c1940e03adb3ce3faf040bd20f2c0ba5", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 201, "avg_line_length": 37.39473684210526, "alnum_prop": 0.6917663617171006, "repo_name": "thushara35/carbon-registry", "id": "d60b03c2cf84a972b1ac70e2013637dc7b65aae2", "size": "1421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/webdav/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "62597" }, { "name": "CSS", "bytes": "62539" }, { "name": "HTML", "bytes": "46318" }, { "name": "Java", "bytes": "5679968" }, { "name": "JavaScript", "bytes": "334293" }, { "name": "PLSQL", "bytes": "186568" }, { "name": "Shell", "bytes": "70140" }, { "name": "XSLT", "bytes": "78182" } ], "symlink_target": "" }
package org.assertj.core.api.path; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.nio.file.Path; import org.assertj.core.api.PathAssert; import org.assertj.core.api.PathAssertBaseTest; class PathAssert_hasParent_Test extends PathAssertBaseTest { private final Path expected = mock(Path.class); @Override protected PathAssert invoke_api_method() { return assertions.hasParent(expected); } @Override protected void verify_internal_effects() { verify(paths).assertHasParent(getInfo(assertions), getActual(assertions), expected); } }
{ "content_hash": "348baa54ecddfab52f51feacbdd593e5", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 88, "avg_line_length": 24.28, "alnum_prop": 0.771004942339374, "repo_name": "assertj/assertj-core", "id": "255514a5e9c8175349397312789d5f85f1bd3289", "size": "1213", "binary": false, "copies": "2", "ref": "refs/heads/assertj-jpms-it", "path": "assertj-core/src/test/java/org/assertj/core/api/path/PathAssert_hasParent_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17632910" }, { "name": "Shell", "bytes": "39247" } ], "symlink_target": "" }
using Castle.Core; using Castle.MicroKernel; namespace Rhino.Testing.AutoMocking { class NonPropertyResolvingComponentActivator : AutoMockingComponentActivator { public NonPropertyResolvingComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction) { } protected override void SetUpProperties(object instance, CreationContext context) { // Do nothing - we're not resolving properties } } }
{ "content_hash": "8fe451b76eff0c5187d9a9128dcd920c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 170, "avg_line_length": 34.388888888888886, "alnum_prop": 0.7027463651050081, "repo_name": "codechip/rhino-tools", "id": "111ec56c04feb14b7198699bc0b981b1431e7d1e", "size": "619", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testing/Rhino.Testing/AutoMocking/NonPropertyResolvingComponentActivator.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "12300" }, { "name": "Boo", "bytes": "206891" }, { "name": "C#", "bytes": "2051009" }, { "name": "JavaScript", "bytes": "555055" }, { "name": "Visual Basic", "bytes": "26367" } ], "symlink_target": "" }
.. _new-labware: ######## Labware ######## When writing a protocol, you must inform the Protocol API about the labware you will be placing on the OT-2's deck. When you load labware, you specify the name of the labware (e.g. ``'corning_96_wellplate_360ul_flat'``), and the slot on the OT-2's deck in which it will be placed (e.g. ``'2'``). The first place to look for the names of labware should always be the `Opentrons Labware Library <https://labware.opentrons.com>`_, where Opentrons maintains a database of labware, their names in the API, what they look like, manufacturer part numbers, and more. In this example, we’ll use ``'corning_96_wellplate_360ul_flat'`` (`an ANSI standard 96-well plate <https://labware.opentrons.com/corning_96_wellplate_360ul_flat>`_) and ``'opentrons_96_tiprack_300ul'`` (`the Opentrons standard 300 µL tiprack <https://labware.opentrons.com/opentrons_96_tiprack_300ul>`_). In the example given in the :ref:`overview-section-v2` section, we loaded labware like this: .. code-block:: python plate = protocol.load_labware('corning_96_wellplate_360ul_flat', '2') tiprack = protocol.load_labware('opentrons_96_tiprack_300ul', '1') which informed the protocol context that the deck contains a 300 µL tiprack in slot 1 and a 96 well plate in slot 2. A third optional argument can be used to give the labware a nickname to be displayed in the Opentrons App. .. code-block:: python plate = protocol.load_labware('corning_96_wellplate_360ul_flat', location='2', label='any-name-you-want') Labware is loaded into a protocol using :py:meth:`.ProtocolContext.load_labware`, which returns :py:class:`opentrons.protocol_api.labware.Labware` object. *************** Finding Labware *************** Default Labware ^^^^^^^^^^^^^^^ The OT-2 has a set of labware well-supported by Opentrons defined internally. This set of labware is always available to protocols. This labware can be found on the `Opentrons Labware Library <https://labware.opentrons.com>`_. You can copy the load names that should be passed to ``protocol.load_labware`` statements to get the correct definitions. .. _v2-custom-labware: Custom Labware ^^^^^^^^^^^^^^ If you have a piece of labware that is not in the Labware Library, you can create your own definition using the `Opentrons Labware Creator <https://labware.opentrons.com/create/>`_. Before using the Labware Creator, you should read the introduction article `here <https://support.opentrons.com/en/articles/3136504-creating-custom-labware-definitions>`__. Once you have created your labware and saved it as a ``.json`` file, you can add it to the Opentrons App by clicking "More" and then "Labware". Once you have added your labware to the Opentrons App, it will be available to all Python Protocol API version 2 protocols uploaded to your robot through that Opentrons App. If other people will be using this custom labware definition, they must also add it to their Opentrons App. You can find a support article about this custom labware process `here <https://support.opentrons.com/en/articles/3136506-using-labware-in-your-protocols>`__. .. _new-well-access: ************************** Accessing Wells in Labware ************************** Well Ordering ^^^^^^^^^^^^^ When writing a protocol, you will need to select which wells to transfer liquids to and from. Rows of wells (see image below) on a labware are typically labeled with capital letters starting with ``'A'``; for instance, an 8x12 96 well plate will have rows ``'A'`` through ``'H'``. Columns of wells (see image below) on a labware are typically labeled with numerical indices starting with ``'1'``; for instance, an 8x12 96 well plate will have columns ``'1'`` through ``'12'``. For all well accessing functions, the starting well will always be at the top left corner of the labware. The ending well will be in the bottom right, see the diagram below for further explanation. .. image:: ../img/well_iteration/Well_Iteration.png .. code-block:: python :substitutions: ''' Examples in this section expect the following ''' metadata = {'apiLevel': '|apiLevel|'} def run(protocol): plate = protocol.load_labware('corning_24_wellplate_3.4ml_flat', slot='1') .. versionadded:: 2.0 Accessor Methods ^^^^^^^^^^^^^^^^ There are many different ways to access wells inside labware. Different methods are useful in different contexts. The table below lists out the methods available to access wells and their differences. +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | Method Name | Returns | +=====================================+===================================================================================================================+ | :py:meth:`.Labware.wells` | List of all wells, i.e. ``[labware:A1, labware:B1, labware:C1...]`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | :py:meth:`.Labware.rows` | List of a list ordered by row, i.e ``[[labware:A1, labware:A2...], [labware:B1, labware:B2..]]`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | :py:meth:`.Labware.columns` | List of a list ordered by column, i.e. ``[[labware:A1, labware:B1..], [labware:A2, labware:B2..]]`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | :py:meth:`.Labware.wells_by_name` | Dictionary with well names as keys, i.e. ``{'A1': labware:A1, 'B1': labware:B1}`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | :py:meth:`.Labware.rows_by_name` | Dictionary with row names as keys, i.e. ``{'A': [labware:A1, labware:A2..], 'B': [labware:B1, labware:B2]}`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ | :py:meth:`.Labware.columns_by_name` | Dictionary with column names as keys, i.e. ``{'1': [labware:A1, labware:B1..], '2': [labware:A2, labware:B2..]}`` | +-------------------------------------+-------------------------------------------------------------------------------------------------------------------+ Accessing Individual Wells ^^^^^^^^^^^^^^^^^^^^^^^^^^ Dictionary Access ----------------- Once a labware is loaded into your protocol, you can easily access the many wells within it by using dictionary indexing. If a well does not exist in this labware, you will receive a ``KeyError``. This is equivalent to using the return value of :py:meth:`.Labware.wells_by_name`: .. code-block:: python a1 = plate['A1'] d6 = plate.wells_by_name()['D6'] .. versionadded:: 2.0 List Access From ``wells`` -------------------------- Wells can be referenced by their name, as demonstrated above. However, they can also be referenced with zero-indexing, with the first well in a labware being at position 0. .. code-block:: python plate.wells()[0] # well A1 plate.wells()[23] # well D6 .. tip:: You may find well names (e.g. ``"B3"``) to be easier to reason with, especially with irregular labware (e.g. ``opentrons_10_tuberack_falcon_4x50ml_6x15ml_conical`` (`Labware Library <https://labware.opentrons.com/opentrons_10_tuberack_falcon_4x50ml_6x15ml_conical>`_). Whichever well access method you use, your protocol will be most maintainable if you use only one access method consistently. .. versionadded:: 2.0 Accessing Groups of Wells ^^^^^^^^^^^^^^^^^^^^^^^^^ When describing a liquid transfer, you can point to groups of wells for the liquid's source and/or destination. Or, you can get a group of wells and loop (or iterate) through them. You can access a specific row or column of wells by using the :py:meth:`.Labware.rows_by_name` and :py:meth:`.Labware.columns_by_name` methods on a labware. These methods both return a dictionary with the row or column name as the keys: .. code-block:: python row_dict = plate.rows_by_name()['A'] row_list = plate.rows()[0] # equivalent to the line above column_dict = plate.columns_by_name()['1'] column_list = plate.columns()[0] # equivalent to the line above print('Column "1" has', len(column_dict), 'wells') print('Row "A" has', len(row_dict), 'wells') will print out... .. code-block:: python Column "1" has 4 wells Row "A" has 6 wells Since these methods return either lists or dictionaries, you can iterate through them as you would regular Python data structures. For example, to access the individual wells of row ``'A'`` in a well plate, you can do: .. code-block:: python for well in plate.rows()[0]: print(well) or, .. code-block:: python for well_obj in plate.rows_by_name()['A'].values(): print(well_obj) and it will return the individual well objects in row A. .. versionadded:: 2.0 .. _v2-location-within-wells: ******************************** Specifying Position Within Wells ******************************** The functions listed above (in the :ref:`new-well-access` section) return objects (or lists, lists of lists, dictionaries, or dictionaries of lists of objects) representing wells. These are :py:class:`opentrons.protocol_api.labware.Well` objects. :py:class:`.Well` objects have some useful methods on them, which allow you to more closely specify the location to which the OT-2 should move *inside* a given well. Each of these methods returns an object called a :py:class:`opentrons.types.Location`, which encapsulates a position in deck coordinates (see :ref:`protocol-api-deck-coords`) and a well with which it is associated. This lets you further manipulate the positions returned by these methods. All :py:class:`.InstrumentContext` methods that involve positions accept these :py:class:`.Location` objects. Position Modifiers ^^^^^^^^^^^^^^^^^^ Top --- The method :py:meth:`.Well.top` returns a position at the top center of the well. This is a good position to use for :ref:`new-blow-out` or any other operation where you don't want to be contacting the liquid. In addition, :py:meth:`.Well.top` takes an optional argument ``z``, which is a distance in mm to move relative to the top vertically (positive numbers move up, and negative numbers move down): .. code-block:: python plate['A1'].top() # This is the top center of the well plate['A1'].top(z=1) # This is 1mm above the top center of the well plate['A1'].top(z=-1) # This is 1mm below the top center of the well .. versionadded:: 2.0 Bottom ------ The method :py:meth:`.Well.bottom` returns a position at the bottom center of the well. This is a good position to start when considering where to aspirate, or any other operation where you want to be contacting the liquid. In addition, :py:meth:`.Well.bottom` takes an optional argument ``z``, which is a distance in mm to move relative to the bottom vertically (positive numbers move up, and negative numbers move down): .. code-block:: python plate['A1'].bottom() # This is the bottom center of the well plate['A1'].bottom(z=1) # This is 1mm above the bottom center of the well plate['A1'].bottom(z=-1) # This is 1mm below the bottom center of the well. # this may be dangerous! .. warning:: Negative ``z`` arguments to :py:meth:`.Well.bottom` may cause the tip to collide with the bottom of the well. The OT-2 has no sensors to detect this, and if it happens, the pipette that collided will be too high in z until the next time it picks up a tip. .. note:: If you are using this to change the position at which the robot does :ref:`new-aspirate` or :ref:`new-dispense` throughout the protocol, consider setting the default aspirate or dispense offset with :py:obj:`.InstrumentContext.well_bottom_clearance` (see :ref:`new-default-op-positions`). .. versionadded:: 2.0 Center ------ The method :py:meth:`.Well.center` returns a position centered in the well both vertically and horizontally. This can be a good place to start for precise control of positions within the well for unusual or custom labware. .. code-block:: python plate['A1'].center() # This is the vertical and horizontal center of the well .. versionadded:: 2.0 Manipulating Positions ^^^^^^^^^^^^^^^^^^^^^^ The objects returned by the position modifier functions are all instances of :py:class:`opentrons.types.Location`, which are `named tuples <https://docs.python.org/3/library/collections.html#collections.namedtuple>`_ representing the combination of a point in space (another named tuple) and a reference to the associated :py:class:`.Well` (or :py:class:`.Labware`, or slot name, depending on context). To adjust the position within a well, you can use :py:meth:`.Location.move`. Pass it a :py:class:`opentrons.types.Point` representing a 3-dimensional offset. It will return a new location, representing the original location with that offset applied. For example: .. code-block:: python :substitutions: from opentrons import types metadata = {'apiLevel': '|apiLevel|'} def run(protocol): plate = protocol.load_labware( 'corning_24_wellplate_3.4ml_flat', slot='1') # Get the center of well A1. center_location = plate['A1'].center() # Get a location 1 mm right, 1 mm back, and 1 mm up from the center of well A1. adjusted_location = center_location.move(types.Point(x=1, y=1, z=1)) # Move to 1 mm right, 1 mm back, and 1 mm up from the center of well A1. pipette.move_to(adjusted_location) .. versionadded:: 2.0
{ "content_hash": "632d6b41604c45689173adf81230de3c", "timestamp": "", "source": "github", "line_count": 327, "max_line_length": 747, "avg_line_length": 43.77064220183486, "alnum_prop": 0.6236288688604765, "repo_name": "Opentrons/labware", "id": "e77ef763fd44bf2b1bf2703949239a13be3dcf2c", "size": "14317", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "api/docs/v2/new_labware.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "102985" } ], "symlink_target": "" }
package com.intellij.openapi.fileTypes.impl; import com.intellij.ide.highlighter.ArchiveFileType; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.highlighter.WorkspaceFileType; import com.intellij.ide.highlighter.custom.SyntaxTable; import com.intellij.ide.plugins.IdeaPluginDescriptorImpl; import com.intellij.ide.plugins.PluginDescriptorTestKt; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.DefaultLogger; import com.intellij.openapi.diagnostic.FrequentEventDetector; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.DefaultPluginDescriptor; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.*; import com.intellij.openapi.fileTypes.ex.DetectedByContentFileType; import com.intellij.openapi.fileTypes.ex.FakeFileType; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.fileTypes.impl.ConflictingFileTypeMappingTracker.ResolveConflictResult; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.ByteSequence; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.PersistentFSConstants; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl; import com.intellij.openapi.vfs.newvfs.impl.CachedFileType; import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile; import com.intellij.psi.PsiBinaryFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiPlainTextFile; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.testFramework.ExtensionTestUtil; import com.intellij.testFramework.HeavyPlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.PatternUtil; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.intellij.lang.annotations.Language; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assume; import javax.swing.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import java.util.stream.Collectors; public class FileTypesTest extends HeavyPlatformTestCase { private static final Logger LOG = Logger.getInstance(FileTypesTest.class); private List<ResolveConflictResult> myConflicts; private FileTypeManagerImpl myFileTypeManager; private Element myGlobalStateBefore; @Override protected void setUp() throws Exception { super.setUp(); // we test against myFileTypeManager instance only, standard FileTypeManager.getInstance() must not be changed in any way myFileTypeManager = new FileTypeManagerImpl(); myFileTypeManager.listenAsyncVfsEvents(); myFileTypeManager.initializeComponent(); myFileTypeManager.getRegisteredFileTypes(); myFileTypeManager.reDetectAsync(true); Assume.assumeTrue( "This test must be run under community classpath because otherwise everything would break thanks to weird HelmYamlLanguage" + " which is created on each HelmYamlFileType registration which happens a lot in these tests", PlatformTestUtil.isUnderCommunityClassPath()); myConflicts = new ArrayList<>(); myFileTypeManager.setConflictResultConsumer(myConflicts::add); myGlobalStateBefore = ((FileTypeManagerImpl)FileTypeManagerEx.getInstanceEx()).getState(); } @Override protected void tearDown() throws Exception { try { myFileTypeManager.setConflictResultConsumer(null); myConflicts = null; assertFileTypeIsUnregistered(new MyCustomImageFileType()); assertFileTypeIsUnregistered(new MyCustomImageFileType2()); assertFileTypeIsUnregistered(new MyTestFileType()); assertFileTypeIsUnregistered(new MyHaskellFileType()); assertEmpty(myFileTypeManager.getRemovedMappingTracker().getRemovedMappings()); myFileTypeManager.reDetectAsync(false); assertNull(myFileTypeManager.findFileTypeByName("x." + MyTestFileType.EXTENSION)); assertNull(myFileTypeManager.getExtensionMap().findByExtension(MyTestFileType.EXTENSION)); Disposer.dispose(myFileTypeManager); Element globalStateAfter = ((FileTypeManagerImpl)FileTypeManagerEx.getInstanceEx()).getState(); assertEquals(JDOMUtil.writeElement(myGlobalStateBefore), JDOMUtil.writeElement(globalStateAfter)); } catch (Throwable e) { addSuppressedException(e); } finally { myFileTypeManager = null; myGlobalStateBefore = null; super.tearDown(); } } public void testMaskExclude() { String pattern1 = "a*b.c?d"; String pattern2 = "xxx"; WriteAction.run(() -> myFileTypeManager.setIgnoredFilesList(pattern1 + ";" + pattern2)); checkIgnored("ab.cxd"); checkIgnored("axb.cxd"); checkIgnored("xxx"); checkNotIgnored("ax.cxx"); checkNotIgnored("ab.cd"); checkNotIgnored("ab.c__d"); checkNotIgnored(pattern2 + 'x'); checkNotIgnored("xx"); assertTrue(myFileTypeManager.isIgnoredFilesListEqualToCurrent(pattern2 + ";" + pattern1)); assertFalse(myFileTypeManager.isIgnoredFilesListEqualToCurrent(pattern2 + ";" + "ab.c*d")); } public void testMaskToPattern() { for (char i = 0; i < 256; i++) { if (i == '?' || i == '*') continue; String str = "x" + i + "y"; assertTrue("char: " + i + "(" + (int)i + ")", PatternUtil.fromMask(str).matcher(str).matches()); } String allSymbols = "+.\\*/^?$[]()"; assertTrue(PatternUtil.fromMask(allSymbols).matcher(allSymbols).matches()); Pattern pattern = PatternUtil.fromMask("?\\?/*"); assertTrue(pattern.matcher("a\\b/xyz").matches()); assertFalse(pattern.matcher("x/a\\b").matches()); } public void testAddNewExtension() { FileType XML = StdFileTypes.XML; FileTypeAssocTable<FileType> associations = new FileTypeAssocTable<>(); associations.addAssociation(FileTypeManager.parseFromString("*.java"), ArchiveFileType.INSTANCE); associations.addAssociation(FileTypeManager.parseFromString("*.xyz"), XML); associations.addAssociation(FileTypeManager.parseFromString("SomeSpecial*.java"), XML); // patterns should have precedence over extensions assertEquals(XML, associations.findAssociatedFileType("sample.xyz")); assertEquals(XML, associations.findAssociatedFileType("SomeSpecialFile.java")); checkNotAssociated(XML, "java", associations); checkNotAssociated(XML, "iws", associations); } public void testIgnoreOrder() { WriteAction.run(() -> myFileTypeManager.setIgnoredFilesList("a;b")); assertEquals("a;b", myFileTypeManager.getIgnoredFilesList()); WriteAction.run(() -> myFileTypeManager.setIgnoredFilesList("b;a")); assertEquals("b;a", myFileTypeManager.getIgnoredFilesList()); } public void testIgnoredFiles() throws IOException { VirtualFile file = getVirtualFile(createTempFile(".svn", "")); assertTrue(myFileTypeManager.isFileIgnored(file)); assertFalse(myFileTypeManager.isFileIgnored(createTempVirtualFile("x.txt", null, "", StandardCharsets.UTF_8))); } public void testEmptyFileWithoutExtension() throws IOException { VirtualFile foo = getVirtualFile(createTempFile("foo", "")); WriteAction.run(() -> myFileTypeManager.associatePattern(DetectedByContentFileType.INSTANCE, "foo")); FileType type = myFileTypeManager.getFileTypeByFile(foo); // foo.getFileType() will call FileTypeRegistry.getInstance() which we try to avoid assertFalse(type.getName(), type.isBinary()); } private static void checkNotAssociated(@NotNull FileType fileType, @NotNull String extension, @NotNull FileTypeAssocTable<FileType> associations) { assertFalse(ArrayUtil.contains(extension, associations.getAssociatedExtensions(fileType))); } private void checkNotIgnored(String fileName) { assertFalse(myFileTypeManager.isFileIgnored(fileName)); } private void checkIgnored(String fileName) { assertTrue(myFileTypeManager.isFileIgnored(fileName)); } public void testAutoDetected() throws IOException { File dir = createTempDirectory(); File file = FileUtil.createTempFile(dir, "x", "xxx_xx_xx", true); FileUtil.writeToFile(file, "xxx xxx xxx xxx"); VirtualFile virtualFile = getVirtualFile(file); assertNotNull(virtualFile); PsiFile psi = getPsiManager().findFile(virtualFile); assertTrue(String.valueOf(psi), psi instanceof PsiPlainTextFile); assertEquals(FileTypes.PLAIN_TEXT, getFileType(virtualFile)); } public void testAutoDetectedWhenDocumentWasCreated() throws IOException { File dir = createTempDirectory(); File file = FileUtil.createTempFile(dir, "x", "xxx_xx_xx", true); FileUtil.writeToFile(file, "xxx xxx xxx xxx"); VirtualFile virtualFile = getVirtualFile(file); Document document = FileDocumentManager.getInstance().getDocument(virtualFile); assertNotNull(document); assertEquals(FileTypes.PLAIN_TEXT, getFileType(virtualFile)); } public void testAutoDetectionShouldNotBeOverEager() throws IOException { File dir = createTempDirectory(); File file = FileUtil.createTempFile(dir, "x", "xxx_xx_xx", true); FileUtil.writeToFile(file, "xxx xxx xxx xxx"); VirtualFile virtualFile = getVirtualFile(file); FileType fileType = getFileType(virtualFile); assertEquals(myFileTypeManager.getRemovedMappingTracker().getRemovedMappings().toString(), PlainTextFileType.INSTANCE, fileType); } public void testAutoDetectEmptyFile() throws IOException { File dir = createTempDirectory(); File file = FileUtil.createTempFile(dir, "x", "xxx_xx_xx", true); VirtualFile virtualFile = getVirtualFile(file); assertEquals(FileTypes.UNKNOWN, getFileType(virtualFile)); PsiFile psi = getPsiManager().findFile(virtualFile); assertTrue(psi instanceof PsiBinaryFile); assertEquals(FileTypes.UNKNOWN, getFileType(virtualFile)); setBinaryContent(virtualFile, "x_x_x_x".getBytes(StandardCharsets.UTF_8)); assertEquals(FileTypes.PLAIN_TEXT, getFileType(virtualFile)); PsiFile after = getPsiManager().findFile(virtualFile); assertNotSame(psi, after); assertFalse(psi.isValid()); assertTrue(after.isValid()); assertTrue(after instanceof PsiPlainTextFile); } public void testAutoDetectTextFileFromContents() throws IOException { File dir = createTempDirectory(); VirtualFile vDir = getVirtualFile(dir); VirtualFile vFile = createChildData(vDir, "test.x_x_x_x"); setFileText(vFile, "text"); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); assertEquals(PlainTextFileType.INSTANCE, getFileType(vFile)); // type is autodetected during indexing PsiFile psiFile = PsiManagerEx.getInstanceEx(getProject()).getFileManager().findFile(vFile); // autodetect text file if needed assertNotNull(psiFile); assertEquals(PlainTextFileType.INSTANCE, psiFile.getFileType()); } public void testAutoDetectTextFileEvenOutsideTheProject() throws IOException { File d = createTempDirectory(); File f = new File(d, "xx.asf_das_dfa"); FileUtil.writeToFile(f, "asd_asd_asd_faf_dsa"); VirtualFile vFile = getVirtualFile(f); assertEquals(PlainTextFileType.INSTANCE, getFileType(vFile)); } public void test7BitBinaryIsNotText() throws IOException { File d = createTempDirectory(); byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'x', 'a', 'b'}; assertEquals(CharsetToolkit.GuessedEncoding.BINARY, new CharsetToolkit(bytes, Charset.defaultCharset(), false).guessFromContent(bytes.length)); File f = new File(d, "xx.asf_das_dfa"); FileUtil.writeToFile(f, bytes); VirtualFile vFile = getVirtualFile(f); assertEquals(UnknownFileType.INSTANCE, getFileType(vFile)); } public void test7BitIsText() throws IOException { File d = createTempDirectory(); byte[] bytes = {9, 10, 13, 'x', 'a', 'b'}; assertEquals(CharsetToolkit.GuessedEncoding.SEVEN_BIT, new CharsetToolkit(bytes, Charset.defaultCharset(), false).guessFromContent(bytes.length)); File f = new File(d, "xx.asf_das_dfa"); FileUtil.writeToFile(f, bytes); VirtualFile vFile = getVirtualFile(f); assertEquals(PlainTextFileType.INSTANCE, getFileType(vFile)); } public void testReDetectOnContentChange() throws IOException { FileType fileType = myFileTypeManager.getFileTypeByFileName("x" + ModuleFileType.DOT_DEFAULT_EXTENSION); assertTrue(fileType.toString(), fileType instanceof ModuleFileType); fileType = myFileTypeManager.getFileTypeByFileName("x" + ProjectFileType.DOT_DEFAULT_EXTENSION); assertTrue(fileType.toString(), fileType instanceof ProjectFileType); FileType module = myFileTypeManager.findFileTypeByName("IDEA_MODULE"); assertNotNull(module); assertFalse(module.equals(PlainTextFileType.INSTANCE)); FileType project = myFileTypeManager.findFileTypeByName("IDEA_PROJECT"); assertNotNull(project); assertFalse(project.equals(PlainTextFileType.INSTANCE)); Set<VirtualFile> detectorCalled = ContainerUtil.newConcurrentSet(); FileTypeRegistry.FileTypeDetector detector = new FileTypeRegistry.FileTypeDetector() { @Override public @Nullable FileType detect(@NotNull VirtualFile file, @NotNull ByteSequence firstBytes, @Nullable CharSequence firstCharsIfText) { detectorCalled.add(file); String text = firstCharsIfText != null ? firstCharsIfText.toString() : null; FileType result = text != null && text.startsWith("TYPE:") ? myFileTypeManager.findFileTypeByName(StringUtil.trimStart(text, "TYPE:")) : null; log("T: my detector run for "+file.getName()+"; result: "+(result == null ? null : result.getName())+" (text="+text+")"); return result; } @Override public int getDesiredContentPrefixLength() { return 48; } }; runWithDetector(detector, () -> { log("T: ------ akj_dhf_ksd_jgf"); File f = createTempFile("xx.asf_das_dfs", "akj_dhf_ksd_jgf"); VirtualFile vFile = getVirtualFile(f); ensureReDetected(vFile, detectorCalled); assertTrue(getFileType(vFile).toString(), getFileType(vFile) instanceof PlainTextFileType); log("T: ------ TYPE:IDEA_MODULE"); setFileText(vFile, "TYPE:IDEA_MODULE"); ensureReDetected(vFile, detectorCalled); assertTrue(getFileType(vFile).toString(), getFileType(vFile) instanceof ModuleFileType); log("T: ------ TYPE:IDEA_PROJECT"); setFileText(vFile, "TYPE:IDEA_PROJECT"); ensureReDetected(vFile, detectorCalled); assertTrue(getFileType(vFile).toString(), getFileType(vFile) instanceof ProjectFileType); log("T: ------"); }); } private <T extends Throwable> void runWithDetector(@NotNull FileTypeRegistry.FileTypeDetector detector, @NotNull ThrowableRunnable<T> runnable) throws T { Disposable disposable = Disposer.newDisposable(); FileTypeRegistry.FileTypeDetector.EP_NAME.getPoint().registerExtension(detector, disposable); FileTypeManagerImpl fileTypeManager = myFileTypeManager; fileTypeManager.toLog = true; try { runnable.run(); } finally { fileTypeManager.toLog = false; Disposer.dispose(disposable); } } private static void log(String message) { LOG.debug(message); //System.out.println(message); } private void ensureReDetected(@NotNull VirtualFile vFile, @NotNull Set<VirtualFile> detectorCalled) { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); log("T: ensureReDetected: commit. re-detect queue: " + myFileTypeManager.dumpReDetectQueue()); UIUtil.dispatchAllInvocationEvents(); log("T: ensureReDetected: dispatch. re-detect queue: " + myFileTypeManager.dumpReDetectQueue()); myFileTypeManager.drainReDetectQueue(); log("T: ensureReDetected: drain. re-detect queue: " + myFileTypeManager.dumpReDetectQueue()); UIUtil.dispatchAllInvocationEvents(); log("T: ensureReDetected: dispatch. re-detect queue: " + myFileTypeManager.dumpReDetectQueue()); FileType type = getFileType(vFile); log("T: ensureReDetected: getFileType (" + type.getName() + ") re-detect queue: " + myFileTypeManager.dumpReDetectQueue()); assertTrue(detectorCalled.contains(vFile)); detectorCalled.clear(); log("T: ensureReDetected: clear"); } public void testReassignTextFileType() { doReassignTest(PlainTextFileType.INSTANCE, "dtd"); } private void doReassignTest(@NotNull FileType fileType, @NotNull String newExtension) { FileType oldFileType = myFileTypeManager.getFileTypeByExtension(newExtension); try { DefaultLogger.disableStderrDumping(getTestRootDisposable()); myFileTypeManager.getRegisteredFileTypes(); // ensure pending file types empty assertNotSame(FileTypes.UNKNOWN, oldFileType); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(fileType, newExtension)); WriteAction.run(() -> myFileTypeManager.getRemovedMappingTracker().add(new ExtensionFileNameMatcher(newExtension), oldFileType.getName(), true)); WriteAction.run(() -> myFileTypeManager.associateExtension(fileType, newExtension)); assertEquals(fileType, myFileTypeManager.getFileTypeByFileName("foo." + newExtension)); } finally { WriteAction.run(() -> { myFileTypeManager.removeAssociatedExtension(fileType, newExtension); myFileTypeManager.getRemovedMappingTracker().removeIf(mapping -> mapping.getFileTypeName().equals(oldFileType.getName()) && mapping.getFileNameMatcher() instanceof ExtensionFileNameMatcher && ((ExtensionFileNameMatcher)mapping.getFileNameMatcher()).getExtension().equals(newExtension)); myFileTypeManager.associateExtension(oldFileType, newExtension); }); } assertEquals(oldFileType, myFileTypeManager.getFileTypeByFileName("foo." + newExtension)); } public void testRemovedMappingSerialization() { Set<FileTypeManagerImpl.FileTypeWithDescriptor> fileTypes = new HashSet<>(myFileTypeManager.getRegisteredFileTypeWithDescriptors()); FileTypeAssocTable<FileTypeManagerImpl.FileTypeWithDescriptor> table = myFileTypeManager.getExtensionMap().copy(); FileTypeManagerImpl.FileTypeWithDescriptor fileType = FileTypeManagerImpl.coreDescriptorFor(ArchiveFileType.INSTANCE); FileNameMatcher matcher = table.getAssociations(fileType).get(0); table.removeAssociation(matcher, fileType); WriteAction.run(() -> myFileTypeManager.setPatternsTable(fileTypes, table)); myFileTypeManager.getRemovedMappingTracker().add(matcher, fileType.fileType.getName(), true); Element state = myFileTypeManager.getState(); LOG.debug(JDOMUtil.writeElement(state)); reInitFileTypeManagerComponent(state); List<RemovedMappingTracker.RemovedMapping> mappings = myFileTypeManager.getRemovedMappingTracker().getRemovedMappings(); assertEquals(1, mappings.size()); assertTrue(mappings.get(0).isApproved()); assertEquals(matcher, mappings.get(0).getFileNameMatcher()); myFileTypeManager.getRemovedMappingTracker().clear(); } public void testRemovedExactNameMapping() { Set<FileTypeManagerImpl.FileTypeWithDescriptor> fileTypes = new HashSet<>(myFileTypeManager.getRegisteredFileTypeWithDescriptors()); FileTypeAssocTable<FileTypeManagerImpl.FileTypeWithDescriptor> table = myFileTypeManager.getExtensionMap().copy(); FileTypeManagerImpl.FileTypeWithDescriptor fileType = FileTypeManagerImpl.coreDescriptorFor(ArchiveFileType.INSTANCE); ExactFileNameMatcher matcher = new ExactFileNameMatcher("foo.bar"); table.addAssociation(matcher, fileType); table.removeAssociation(matcher, fileType); WriteAction.run(() -> myFileTypeManager.setPatternsTable(fileTypes, table)); myFileTypeManager.getRemovedMappingTracker().add(matcher, fileType.fileType.getName(), true); Element state = myFileTypeManager.getState(); LOG.debug(JDOMUtil.writeElement(state)); reInitFileTypeManagerComponent(state); List<RemovedMappingTracker.RemovedMapping> mappings = myFileTypeManager.getRemovedMappingTracker().getRemovedMappings(); assertTrue(mappings.get(0).isApproved()); assertEquals(matcher, mappings.get(0).getFileNameMatcher()); assertOneElement(myFileTypeManager.getRemovedMappingTracker().removeIf(mapping -> mapping.getFileNameMatcher().equals(matcher))); } public void testAddExistingExtensionFromFileTypeXToFileTypeYMustSurviveRestart() throws IOException, JDOMException { String ext = ((ExtensionFileNameMatcher)Arrays.stream(myFileTypeManager.getRegisteredFileTypes()) .filter(type -> !(type instanceof AbstractFileType)) .flatMap(type -> myFileTypeManager.getAssociations(type).stream()) .filter(association -> association instanceof ExtensionFileNameMatcher) .findFirst() .orElseThrow()).getExtension(); FileType type = myFileTypeManager.getFileTypeByExtension(ext); FileType otherType = ContainerUtil.find(myFileTypeManager.getRegisteredFileTypes(), t -> !t.equals(type) && t instanceof AbstractFileType); // try to assign ext from type to otherType WriteAction.run(() -> myFileTypeManager.associateExtension(otherType, ext)); assertEquals(otherType, myFileTypeManager.getFileTypeByExtension(ext)); assertEmpty(myFileTypeManager.getRemovedMappingTracker().getMappingsForFileType(type.getName())); @Language("XML") String xml = "<blahblah version='" + FileTypeManagerImpl.VERSION + "'>\n" + " <extensionMap>\n" + " <mapping ext=\""+ext+"\" type=\"" + otherType.getName()+ "\" />\n" + " <removed_mapping ext=\""+ext+"\" type=\"" + type.getName()+ "\" approved=\"true\"/>\n" + " </extensionMap>\n" + "</blahblah>"; Element element = JDOMUtil.load(xml); myFileTypeManager.getRegisteredFileTypes(); // instantiate pending file types reInitFileTypeManagerComponent(element); assertEmpty(myConflicts); assertEquals(otherType, myFileTypeManager.getFileTypeByExtension(ext)); assertNotEmpty(myFileTypeManager.getRemovedMappingTracker().getMappingsForFileType(type.getName())); myFileTypeManager.getRemovedMappingTracker().clear(); } public void testAddHashBangToReassignedTypeMustSurviveRestart() throws IOException, JDOMException { FileTypeManagerImpl.FileTypeWithDescriptor ftd = ContainerUtil.find(myFileTypeManager.getRegisteredFileTypeWithDescriptors(), f -> !(f.fileType instanceof AbstractFileType)); String hashBang = "xxx"; @Language("XML") String xml = "<blahblah version='" + FileTypeManagerImpl.VERSION + "'>\n" + " <extensionMap>\n" + " <hashBang value=\"" + hashBang + "\" type=\"" + ftd.getName() + "\" />\n"+ " </extensionMap>\n" + "</blahblah>"; Element element = JDOMUtil.load(xml); myFileTypeManager.getRegisteredFileTypes(); // instantiate pending file types reInitFileTypeManagerComponent(element); assertEmpty(myConflicts); assertEquals(ftd, myFileTypeManager.getExtensionMap().findAssociatedFileTypeByHashBang("#!" + hashBang+"\n")); } public void testReassignedPredefinedFileType() { FileType perlType = myFileTypeManager.getFileTypeByFileName("foo.pl"); assertEquals("Perl", perlType.getName()); assertEquals(PlainTextFileType.INSTANCE, myFileTypeManager.getFileTypeByFileName("foo.txt")); doReassignTest(perlType, "txt"); } public void testReAddedMapping() { ArchiveFileType fileType = ArchiveFileType.INSTANCE; FileNameMatcher matcher = myFileTypeManager.getAssociations(fileType).get(0); myFileTypeManager.getRemovedMappingTracker().add(matcher, fileType.getName(), true); WriteAction.run(() -> myFileTypeManager.setPatternsTable( new HashSet<>(myFileTypeManager.getRegisteredFileTypeWithDescriptors()), myFileTypeManager.getExtensionMap().copy())); assertEmpty(myFileTypeManager.getRemovedMappingTracker().getRemovedMappings()); } public void testPreserveRemovedMappingForUnknownFileType() { myFileTypeManager.getRemovedMappingTracker().add(new ExtensionFileNameMatcher("xxx"), MyTestFileType.NAME, true); WriteAction.run(() -> myFileTypeManager.setPatternsTable( new HashSet<>(myFileTypeManager.getRegisteredFileTypeWithDescriptors()), myFileTypeManager.getExtensionMap().copy())); assertEquals(1, myFileTypeManager.getRemovedMappingTracker().getRemovedMappings().size()); myFileTypeManager.getRemovedMappingTracker().clear(); } public void testGetRemovedMappings() { FileTypeAssocTable<FileTypeManagerImpl.FileTypeWithDescriptor> table = myFileTypeManager.getExtensionMap().copy(); FileTypeManagerImpl.FileTypeWithDescriptor fileType = FileTypeManagerImpl.coreDescriptorFor(ArchiveFileType.INSTANCE); FileNameMatcher matcher = table.getAssociations(fileType).get(0); table.removeAssociation(matcher, fileType); Map<FileNameMatcher, FileTypeManagerImpl.FileTypeWithDescriptor> reassigned = myFileTypeManager.getExtensionMap().getRemovedMappings(table, myFileTypeManager.getRegisteredFileTypeWithDescriptors()); assertEquals(1, reassigned.size()); } public void testRenamedXmlToUnknownAndBack() throws Exception { FileType propFileType = myFileTypeManager.getFileTypeByFileName("xx.xml"); assertEquals("XML", propFileType.getName()); File file = createTempFile("xx.xml", "<foo></foo>"); VirtualFile vFile = getVirtualFile(file); assertEquals(propFileType, myFileTypeManager.getFileTypeByFile(vFile)); rename(vFile, "xx.zxm_cnb_zmx_nbc"); UIUtil.dispatchAllInvocationEvents(); assertEquals(PlainTextFileType.INSTANCE, myFileTypeManager.getFileTypeByFile(vFile)); rename(vFile, "xx.xml"); myFileTypeManager.drainReDetectQueue(); for (int i = 0; i < 100; i++) { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); UIUtil.dispatchAllInvocationEvents(); assertEquals(propFileType, myFileTypeManager.getFileTypeByFile(vFile)); assertEmpty(myFileTypeManager.dumpReDetectQueue()); } } // IDEA-114804 "File types mapped to text are not remapped when a corresponding plugin is installed" public void testRemappingToInstalledPluginExtension() throws WriteExternalException, InvalidDataException { myFileTypeManager.getRegisteredFileTypes(); WriteAction.run(() -> myFileTypeManager.associateExtension(PlainTextFileType.INSTANCE, MyTestFileType.EXTENSION)); Element element = myFileTypeManager.getState(); FileTypeBean bean = new FileTypeBean(); bean.name = MyTestFileType.NAME; bean.implementationClass = MyTestFileType.class.getName(); bean.extensions = MyTestFileType.EXTENSION; IdeaPluginDescriptorImpl pluginDescriptor = PluginDescriptorTestKt.readDescriptorForTest(Path.of(""), false, "<idea-plugin/>".getBytes(StandardCharsets.UTF_8), PluginId.getId("myPlugin")); Disposable disposable = registerFileType(bean, pluginDescriptor); try { reInitFileTypeManagerComponent(element); List<RemovedMappingTracker.RemovedMapping> mappings = myFileTypeManager.getRemovedMappingTracker().getRemovedMappings(); assertEquals(1, mappings.size()); assertEquals(MyTestFileType.NAME, mappings.get(0).getFileTypeName()); } finally { WriteAction.run(() -> Disposer.dispose(disposable)); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(PlainTextFileType.INSTANCE, MyTestFileType.EXTENSION)); } } private void reInitFileTypeManagerComponent(@Nullable Element element) { myFileTypeManager.getRemovedMappingTracker().clear(); myFileTypeManager.clearStandardFileTypesBeforeTest(); if (element != null) { myFileTypeManager.loadState(element); } myFileTypeManager.initializeComponent(); myFileTypeManager.getRegisteredFileTypes(); } public void testRegisterConflictingExtensionMustBeReported() throws WriteExternalException, InvalidDataException { String myWeirdExtension = "my_weird_extension"; WriteAction.run(() -> myFileTypeManager.associateExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); Disposable disposable = Disposer.newDisposable(); try { myFileTypeManager.getRegisteredFileTypes(); // ensure pending file types empty assertEmpty(myConflicts); createFakeType("myType", "myDisplayName", "myDescription", myWeirdExtension, disposable); assertNotEmpty(myConflicts); } finally { Disposer.dispose(disposable); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); } } public void testPreserveUninstalledPluginAssociations() { FileType typeFromPlugin = new MyTestFileType(); FileTypeFactory factory = new FileTypeFactory() { @Override public void createFileTypes(@NotNull FileTypeConsumer consumer) { consumer.consume(typeFromPlugin); } }; Element element = myFileTypeManager.getState(); Disposable disposable = Disposer.newDisposable(); try { FileTypeFactory.FILE_TYPE_FACTORY_EP.getPoint().registerExtension(factory, disposable); reInitFileTypeManagerComponent(element); WriteAction.run(() -> myFileTypeManager.associateExtension(typeFromPlugin, "foo")); element = myFileTypeManager.getState(); Disposer.dispose(disposable); disposable = Disposer.newDisposable(); reInitFileTypeManagerComponent(element); element = myFileTypeManager.getState(); FileTypeFactory.FILE_TYPE_FACTORY_EP.getPoint().registerExtension(factory, disposable); reInitFileTypeManagerComponent(element); assertEquals(typeFromPlugin, myFileTypeManager.getFileTypeByFileName("foo.foo")); myFileTypeManager.unregisterFileType(typeFromPlugin); } finally { Disposer.dispose(disposable); } } // IDEA-139409 Persistent message "File type recognized: File extension *.vm was reassigned to VTL" public void testReassign() throws Exception { myFileTypeManager.getRegisteredFileTypes(); String unresolved = "Velocity Template files"; assertNull(myFileTypeManager.findFileTypeByName(unresolved)); @Language("XML") String xml = "<component name=\"FileTypeManager\" version=\"13\">\n" + " <extensionMap>\n" + " <mapping ext=\"zip\" type=\"" + unresolved + "\" />\n" + " </extensionMap>\n" + "</component>"; Element element = JDOMUtil.load(xml); reInitFileTypeManagerComponent(element); List<RemovedMappingTracker.RemovedMapping> mappings = myFileTypeManager.getRemovedMappingTracker().getRemovedMappings(); assertEquals(1, mappings.size()); assertEquals(ArchiveFileType.INSTANCE.getName(), mappings.get(0).getFileTypeName()); myFileTypeManager.getRemovedMappingTracker().clear(); assertEquals(ArchiveFileType.INSTANCE, myFileTypeManager.getFileTypeByExtension("zip")); Element map = myFileTypeManager.getState().getChild("extensionMap"); if (map != null) { List<Element> mapping = map.getChildren("mapping"); assertNull(ContainerUtil.find(mapping, o -> "zip".equals(o.getAttributeValue("ext")))); } } public void testRemovedMappingsMustNotLeadToDuplicates() throws Exception { @Language("XML") String xml = "<blahblah version='" + FileTypeManagerImpl.VERSION + "'>\n" + " <extensionMap>\n" + " </extensionMap>\n" + "</blahblah>"; Element element = JDOMUtil.load(xml); myFileTypeManager.getRegisteredFileTypes(); // instantiate pending file types reInitFileTypeManagerComponent(element); List<RemovedMappingTracker.RemovedMapping> removedMappings = myFileTypeManager.getRemovedMappingTracker().getRemovedMappings(); assertEmpty(removedMappings); FileType type = myFileTypeManager.getFileTypeByFileName("x.txt"); assertEquals(PlainTextFileType.INSTANCE, type); RemovedMappingTracker.RemovedMapping mapping = myFileTypeManager.getRemovedMappingTracker().add(new ExtensionFileNameMatcher("txt"), PlainTextFileType.INSTANCE.getName(), true); try { Element result = myFileTypeManager.getState().getChildren().get(0); @Language("XML") String expectedXml = "<extensionMap>\n" + " <removed_mapping ext=\"txt\" approved=\"true\" type=\"PLAIN_TEXT\" />\n" + "</extensionMap>"; assertEquals(expectedXml, JDOMUtil.write(result)); } finally { assertOneElement(myFileTypeManager.getRemovedMappingTracker().removeIf(m -> m.equals(mapping))); } } public void testDefaultFileType() { final String extension = "very_rare_extension"; FileType idl = Objects.requireNonNull(myFileTypeManager.findFileTypeByName("IDL")); WriteAction.run(() -> myFileTypeManager.associatePattern(idl, "*." + extension)); Element element = myFileTypeManager.getState(); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(idl, extension)); reInitFileTypeManagerComponent(element); FileType extensions = myFileTypeManager.getFileTypeByExtension(extension); assertEquals("IDL", extensions.getName()); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(idl, extension)); } public void testIfDetectorRanThenIdeaReopenedTheDetectorShouldBeReRun() throws IOException { UserBinaryFileType stuffType = new UserBinaryFileType() {}; stuffType.setName("stuffType"); Set<VirtualFile> detectorCalled = ContainerUtil.newConcurrentSet(); FileTypeRegistry.FileTypeDetector detector = new FileTypeRegistry.FileTypeDetector() { @Override public @Nullable FileType detect(@NotNull VirtualFile file, @NotNull ByteSequence firstBytes, @Nullable CharSequence firstCharsIfText) { detectorCalled.add(file); FileType result = FileUtil.isHashBangLine(firstCharsIfText, "stuff") ? stuffType : null; log("T: my detector for file "+file.getName()+" run. result="+(result == null ? null : result.getName())); return result; } @Override public int getDesiredContentPrefixLength() { return 48; } }; runWithDetector(detector, () -> { log("T: ------ akj_dhf_ksd_jgf"); File f = createTempFile("xx.asf_das_dfs", "akj_dhf_ksd_jgf"); VirtualFile file = getVirtualFile(f); ensureReDetected(file, detectorCalled); assertTrue(getFileType(file).toString(), getFileType(file) instanceof PlainTextFileType); log("T: ------ my"); setFileText(file, "#!stuff\nxx"); ensureReDetected(file, detectorCalled); assertEquals(stuffType, getFileType(file)); log("T: ------ reload"); myFileTypeManager.drainReDetectQueue(); getPsiManager().dropPsiCaches(); ensureReDetected(file, detectorCalled); assertSame(getFileType(file).toString(), getFileType(file), stuffType); log("T: ------"); }); } // redirect getFileType to our own test FileTypeManagerImpl instance private @NotNull FileType getFileType(VirtualFile file) { return myFileTypeManager.getFileTypeByFile(file); } public void _testStressPlainTextFileWithEverIncreasingLength() throws IOException { FrequentEventDetector.disableUntil(getTestRootDisposable()); File f = createTempFile("xx.lkj_lkj_lkj_ljk", "a"); VirtualFile virtualFile = getVirtualFile(f); assertEquals(PlainTextFileType.INSTANCE, getFileType(virtualFile)); int NThreads = 8; int N = 1000; Random random = new Random(); AtomicReference<Exception> exception = new AtomicReference<>(); List<Thread> threads = ContainerUtil.map(new Object[NThreads], o -> new Thread(() -> { try { for (int i = 0; i < N; i++) { boolean isText = ReadAction.compute(() -> { if (getFileType(virtualFile).isBinary()) { return false; } else { LoadTextUtil.loadText(virtualFile); return true; } }); if (random.nextInt(3) == 0) { WriteCommandAction.writeCommandAction(getProject()).run(() -> { byte[] bytes = new byte[(int)PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD + (isText ? 1 : 0)]; Arrays.fill(bytes, (byte)' '); virtualFile.setBinaryContent(bytes); }); LOG.debug(i + "; f = " + f.length() + "; virtualFile=" + virtualFile.getLength() + "; type=" + getFileType(virtualFile)); } } } catch (Exception e) { exception.set(e); e.printStackTrace(); throw new RuntimeException(e); } }, "reader")); threads.forEach(Thread::start); for (Thread thread : threads) { while (thread.isAlive()) { if (exception.get() != null) throw new RuntimeException(exception.get()); UIUtil.dispatchAllInvocationEvents(); //refresh } } if (exception.get() != null) throw new RuntimeException(exception.get()); } public void _testStressPlainTextFileWithEverIncreasingLength2() throws IOException { FrequentEventDetector.disableUntil(getTestRootDisposable()); File f = createTempFile("xx.asd_kjf_hlk_asj_dhf", StringUtil.repeatSymbol(' ', (int)PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD - 100)); VirtualFile virtualFile = getVirtualFile(f); assertEquals(PlainTextFileType.INSTANCE, getFileType(virtualFile)); PsiFile psiFile = getPsiManager().findFile(virtualFile); assertTrue(psiFile instanceof PsiPlainTextFile); int NThreads = 1; int N = 10; List<Thread> threads = ContainerUtil.map(new Object[NThreads], o -> new Thread(() -> { for (int i = 0; i < N; i++) { ApplicationManager.getApplication().runReadAction(() -> { String text = psiFile.getText(); LOG.debug("text = " + text.length()); }); try { FileUtil.appendToFile(f, StringUtil.repeatSymbol(' ', 50)); LocalFileSystem.getInstance().refreshFiles(Collections.singletonList(virtualFile)); LOG.debug("f = " + f.length() + "; virtualFile=" + virtualFile.getLength() + "; psiFile=" + psiFile.isValid() + "; type=" + getFileType(virtualFile)); } catch (IOException e) { throw new RuntimeException(e); } } }, "reader")); threads.forEach(Thread::start); for (Thread thread : threads) { while (thread.isAlive()) { UIUtil.dispatchAllInvocationEvents(); //refresh } } } public void testChangeEncodingManuallyForAutoDetectedFileSticks() throws IOException { EncodingProjectManagerImpl manager = (EncodingProjectManagerImpl)EncodingProjectManager.getInstance(getProject()); String oldProject = manager.getDefaultCharsetName(); try { VirtualFile file = createTempVirtualFile("x.sld_kfj_lsk_dfj", null, "123456789", StandardCharsets.UTF_8); manager.setEncoding(file, CharsetToolkit.WIN_1251_CHARSET); file.setCharset(CharsetToolkit.WIN_1251_CHARSET); UIUtil.dispatchAllInvocationEvents(); myFileTypeManager.drainReDetectQueue(); UIUtil.dispatchAllInvocationEvents(); assertEquals(PlainTextFileType.INSTANCE, getFileType(file)); manager.setEncoding(file, StandardCharsets.US_ASCII); UIUtil.dispatchAllInvocationEvents(); myFileTypeManager.drainReDetectQueue(); UIUtil.dispatchAllInvocationEvents(); assertEquals(StandardCharsets.US_ASCII, file.getCharset()); manager.setEncoding(file, StandardCharsets.UTF_8); UIUtil.dispatchAllInvocationEvents(); myFileTypeManager.drainReDetectQueue(); UIUtil.dispatchAllInvocationEvents(); assertEquals(StandardCharsets.UTF_8, file.getCharset()); manager.setEncoding(file, StandardCharsets.US_ASCII); UIUtil.dispatchAllInvocationEvents(); myFileTypeManager.drainReDetectQueue(); UIUtil.dispatchAllInvocationEvents(); assertEquals(StandardCharsets.US_ASCII, file.getCharset()); manager.setEncoding(file, StandardCharsets.UTF_8); UIUtil.dispatchAllInvocationEvents(); myFileTypeManager.drainReDetectQueue(); UIUtil.dispatchAllInvocationEvents(); assertEquals(StandardCharsets.UTF_8, file.getCharset()); } finally { manager.setDefaultCharsetName(oldProject); } } public void testFileTypeBeanByName() { assertTrue(myFileTypeManager.getStdFileType(WorkspaceFileType.INSTANCE.getName()) instanceof WorkspaceFileType); } public void testInternalFileTypeBeanIsAlwaysRegistered() { FileType[] types = myFileTypeManager.getRegisteredFileTypes(); assertTrue(ContainerUtil.exists(types, type -> type instanceof WorkspaceFileType)); } public void testInternalFileTypeMustBeFoundByFileName() { assertInstanceOf(myFileTypeManager.getFileTypeByFileName("foo" + WorkspaceFileType.DOT_DEFAULT_EXTENSION), WorkspaceFileType.class); } public void testInternalFileTypeBeanMustBeFoundByExtensionWithFieldName() { assertSame(ModuleFileType.INSTANCE, myFileTypeManager.getFileTypeByExtension(ModuleFileType.DEFAULT_EXTENSION)); } public void testIsFileTypeMustRunDetector() throws IOException { VirtualFile vFile = createTempVirtualFile("x.bbb", null, "#!archive!!!", StandardCharsets.UTF_8); AtomicInteger detectorCalls = new AtomicInteger(); ExtensionTestUtil.maskExtensions(FileTypeRegistry.FileTypeDetector.EP_NAME, Collections.singletonList(new FileTypeRegistry.FileTypeDetector() { @Override public @Nullable FileType detect(@NotNull VirtualFile file, @NotNull ByteSequence firstBytes, @Nullable CharSequence firstCharsIfText) { if (file.equals(vFile)) { detectorCalls.incrementAndGet(); } if (firstCharsIfText != null && firstCharsIfText.toString().startsWith("#!archive")) { return ArchiveFileType.INSTANCE; } return null; } @Override public int getDesiredContentPrefixLength() { return "#!archive".length(); } }), getTestRootDisposable()); assertEquals(ArchiveFileType.INSTANCE, getFileType(vFile)); assertEquals(ArchiveFileType.INSTANCE, getFileType(vFile)); assertEquals(1, detectorCalls.get()); } public void testEveryLanguageHasOnePrimaryFileType() { Map<String, LanguageFileType> map = new HashMap<>(); for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { if (!(type instanceof LanguageFileType)) { continue; } LanguageFileType languageFileType = (LanguageFileType)type; if (!languageFileType.isSecondary()) { String id = languageFileType.getLanguage().getID(); LanguageFileType oldFileType = map.get(id); if (oldFileType != null) { fail("Multiple primary file types for language " + id + ": " + oldFileType.getName() + ", " + languageFileType.getName()); } map.put(id, languageFileType); } } } public void testDEFAULT_IGNOREDIsSorted() { List<String> strings = FileTypeManagerImpl.DEFAULT_IGNORED; List<String> sorted = strings.stream().sorted().collect(Collectors.toList()); assertEquals("FileTypeManagerImpl.DEFAULT_IGNORED entries must be sorted", sorted, FileTypeManagerImpl.DEFAULT_IGNORED); } public void testRegisterUnregisterExtension() { FileTypeBean bean = new FileTypeBean(); bean.name = MyTestFileType.NAME; bean.implementationClass = MyTestFileType.class.getName(); Disposable disposable = registerFileType(bean, FileTypeManagerImpl.coreIdeaPluginDescriptor()); assertNotNull(myFileTypeManager.findFileTypeByName(MyTestFileType.NAME)); WriteAction.run(() -> Disposer.dispose(disposable)); assertNull(myFileTypeManager.findFileTypeByName(MyTestFileType.NAME)); } private static @NotNull Disposable registerFileType(@NotNull FileTypeBean bean, @NotNull PluginDescriptor pluginDescriptor) { bean.setPluginDescriptor(pluginDescriptor); Disposable disposable = Disposer.newDisposable(); WriteAction.run(() -> FileTypeManagerImpl.EP_NAME.getPoint().registerExtension(bean, disposable)); return disposable; } public void testRegisterUnregisterExtensionWithFileName() throws IOException { String name = ".veryWeirdFileName"; File tempFile = createTempFile(name, "This is a text file"); VirtualFile vFile = getVirtualFile(tempFile); assertEquals(PlainTextFileType.INSTANCE, getFileType(vFile)); FileTypeBean bean = new FileTypeBean(); bean.name = MyTestFileType.NAME; bean.fileNames = name; bean.implementationClass = MyTestFileType.class.getName(); Disposable disposable = registerFileType(bean, FileTypeManagerImpl.coreIdeaPluginDescriptor()); try { clearFileTypeCache(); assertEquals(MyTestFileType.NAME, myFileTypeManager.getFileTypeByFileName(name).getName()); assertEquals(MyTestFileType.NAME, getFileType(vFile).getName()); } finally { WriteAction.run(() -> Disposer.dispose(disposable)); } assertNull(myFileTypeManager.findFileTypeByName(MyTestFileType.NAME)); } private static void clearFileTypeCache() { WriteAction.run(() -> CachedFileType.clearCache()); // normally this is done by PsiModificationTracker.Listener but it's not fired in this test } public void testRegisterAdditionalExtensionForExistingFileType() throws IOException { String name = ".veryUnknownFile"; File tempFile = createTempFile(name, "This is a text file"); VirtualFile vFile = getVirtualFile(tempFile); assertEquals(PlainTextFileType.INSTANCE, getFileType(vFile)); FileTypeBean bean = new FileTypeBean(); bean.name = "XML"; bean.fileNames = name; Disposable disposable = registerFileType(bean, FileTypeManagerImpl.coreIdeaPluginDescriptor()); try { clearFileTypeCache(); assertEquals("XML", myFileTypeManager.getFileTypeByFileName(name).getName()); assertEquals("XML", getFileType(vFile).getName()); } finally { WriteAction.run(() -> Disposer.dispose(disposable)); } assertEquals("UNKNOWN", myFileTypeManager.getFileTypeByFileName(name).getName()); } public void testRegisterAssociationsViaFileTypeFactoryDoesWork() { FileType anyExistingType = StdFileTypes.XML; FileType ownType = new FileType() { @Override public @NotNull String getName() { return getTestName(false) + "_FileType"; } @Override public @NotNull String getDescription() { return getTestName(false) + "_Description"; } @Override public @NotNull String getDefaultExtension() { return getTestName(false) + "_Extension"; } @Override public @Nullable Icon getIcon() { return null; } @Override public boolean isBinary() { return false; } }; // I suspect it may work when registered once, need more than 1 String[] extensionsForXml = {getTestName(true)+"_1", getTestName(true)+"_2", getTestName(true)+"_3" }; for (String nextExtension : ContainerUtil.concat(extensionsForXml, new String[]{ownType.getDefaultExtension()})) { assertEquals("precondition: should be unknown before: " + nextExtension, FileTypes.UNKNOWN, myFileTypeManager.getFileTypeByExtension(nextExtension)); } Ref<Boolean> factoryWasCalled = new Ref<>(false); FileTypeFactory factory = new FileTypeFactory() { @Override public void createFileTypes(@NotNull FileTypeConsumer consumer) { factoryWasCalled.set(true); consumer.consume(ownType); for (String nextExtension : extensionsForXml) { consumer.consume(anyExistingType, nextExtension); } } }; Disposable disposable = Disposer.newDisposable(); try { clearFileTypeCache(); FileTypeFactory.FILE_TYPE_FACTORY_EP.getPoint().registerExtension(factory, disposable); assertFalse(factoryWasCalled.get()); reInitFileTypeManagerComponent(null); assertTrue(factoryWasCalled.get()); assertEquals("factory was called, new types work fine", ownType, myFileTypeManager.getFileTypeByExtension(ownType.getDefaultExtension())); // it works for own types but does not for the external types for (String nextExtension : extensionsForXml) { assertEquals("factory was called but extension is still unknown : " + nextExtension, anyExistingType, myFileTypeManager.getFileTypeByExtension(nextExtension)); } } finally { Disposer.dispose(disposable); } } public void testPluginOverridesAbstractFileType() { assertInstanceOf(myFileTypeManager.findFileTypeByName(MyHaskellFileType.NAME), AbstractFileType.class); FileTypeBean bean = new FileTypeBean(); bean.name = MyHaskellFileType.NAME; bean.extensions = "hs"; bean.implementationClass = MyHaskellFileType.class.getName(); Disposable disposable = registerFileType(bean, FileTypeManagerImpl.coreIdeaPluginDescriptor()); assertInstanceOf(myFileTypeManager.findFileTypeByName(MyHaskellFileType.NAME), MyHaskellFileType.class); assertInstanceOf(myFileTypeManager.getFileTypeByFileName("foo.hs"), MyHaskellFileType.class); WriteAction.run(() -> Disposer.dispose(disposable)); // todo restore old AbstractFileType automatically? AbstractFileType old = new AbstractFileType(new SyntaxTable()); old.setName(MyHaskellFileType.NAME); myFileTypeManager.registerFileType(old, List.of(), myFileTypeManager); } private static class MyCustomImageFileType implements FileType { private MyCustomImageFileType() { } @Override public @NotNull String getName() { return "my.image"; } @Override public @NotNull String getDisplayName() { return getClass().getName(); } @Override public @NotNull String getDescription() { return getDisplayName(); } @Override public @NotNull String getDefaultExtension() { return "hs"; } @Override public @Nullable Icon getIcon() { return null; } @Override public boolean isBinary() { return false; } } private static class MyCustomImageFileType2 extends MyCustomImageFileType { @Override public @NotNull String getName() { return super.getName() + "2"; } } public void testPluginWhichOverridesBundledFileTypeMustWin() { FileType bundled = Objects.requireNonNull(myFileTypeManager.findFileTypeByName("Image")); // this check doesn't work because in unit test mode plugin class loader is not created //PluginDescriptor pluginDescriptor = PluginManager.getPluginByClass(bundled.getClass()); //assertTrue(pluginDescriptor.isBundled()); //LOG.debug("pluginDescriptor = " + pluginDescriptor); FileTypeBean bean = new FileTypeBean(); bean.name = new MyCustomImageFileType().getName(); String ext = myFileTypeManager.getAssociations(bundled).get(0).toString().replace("*.", ""); bean.extensions = ext; bean.implementationClass = MyCustomImageFileType.class.getName(); bean.setPluginDescriptor(new DefaultPluginDescriptor(PluginId.getId("myTestPlugin"), PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID).getPluginClassLoader())); Disposable disposable = Disposer.newDisposable(); Disposer.register(getTestRootDisposable(), disposable); WriteAction.run(() -> FileTypeManagerImpl.EP_NAME.getPoint().registerExtension(bean, disposable)); assertInstanceOf(myFileTypeManager.findFileTypeByName(bean.name), MyCustomImageFileType.class); assertInstanceOf(myFileTypeManager.getFileTypeByExtension(ext), MyCustomImageFileType.class); WriteAction.run(() -> Disposer.dispose(disposable)); } private void assertFileTypeIsUnregistered(@NotNull FileType fileType) { for (FileType type : myFileTypeManager.getRegisteredFileTypes()) { if (type.getClass() == fileType.getClass()) { throw new AssertionError(type + " is still registered"); } } FileType registered = myFileTypeManager.findFileTypeByName(fileType.getName()); if (registered != null && !(registered instanceof AbstractFileType)) { fail(registered.toString()); } } public void testTwoPluginsWhichOverrideBundledFileTypeMustNegotiateBetweenThemselves() { FileTypeManager fileTypeManager = myFileTypeManager; FileType bundled = Objects.requireNonNull(fileTypeManager.findFileTypeByName("Image")); //PluginDescriptor pluginDescriptor = Objects.requireNonNull(PluginManagerCore.getPluginDescriptorOrPlatformByClassName(bundled.getClass().getName())); //assertTrue(pluginDescriptor.isBundled()); //LOG.debug("pluginDescriptor = " + pluginDescriptor); String ext = myFileTypeManager.getAssociations(bundled).get(0).toString().replace("*.", ""); FileTypeBean bean = new FileTypeBean(); bean.name = new MyCustomImageFileType().getName(); bean.extensions = ext; bean.implementationClass = MyCustomImageFileType.class.getName(); bean.setPluginDescriptor(new DefaultPluginDescriptor(PluginId.getId("myTestPlugin"), FileTypeManagerImpl.coreIdeaPluginDescriptor().getPluginClassLoader())); FileTypeBean bean2 = new FileTypeBean(); bean2.name = new MyCustomImageFileType2().getName(); bean2.extensions = ext; bean2.implementationClass = MyCustomImageFileType2.class.getName(); bean2.setPluginDescriptor(new DefaultPluginDescriptor(PluginId.getId("myTestPlugin2"), FileTypeManagerImpl.coreIdeaPluginDescriptor().getPluginClassLoader())); Disposable disposable = Disposer.newDisposable(); Disposer.register(getTestRootDisposable(), disposable); WriteAction.run(() -> { FileTypeManagerImpl.EP_NAME.getPoint().registerExtension(bean, disposable); FileTypeManagerImpl.EP_NAME.getPoint().registerExtension(bean2, disposable); }); assertInstanceOf(fileTypeManager.findFileTypeByName(bean.name), MyCustomImageFileType.class); assertInstanceOf(fileTypeManager.findFileTypeByName(bean2.name), MyCustomImageFileType2.class); assertInstanceOf(fileTypeManager.getFileTypeByExtension(ext), MyCustomImageFileType.class); // either MyCustomImageFileType or MyCustomImageFileType2 WriteAction.run(() -> Disposer.dispose(disposable)); } public void testHashBangPatternsCanBeConfiguredDynamically() throws IOException { VirtualFile file0 = createTempVirtualFile("x.xxx", null, "#!/usr/bin/go-go-go\na=b", StandardCharsets.UTF_8); assertEquals(PlainTextFileType.INSTANCE, getFileType(file0)); FileType PROPERTIES = FileTypeManager.getInstance().getStdFileType("Properties"); FileTypeManagerImpl.FileTypeWithDescriptor fileType = FileTypeManagerImpl.coreDescriptorFor(PROPERTIES); myFileTypeManager.getExtensionMap().addHashBangPattern("go-go-go", fileType); try { VirtualFile file = createTempVirtualFile("x.xxx", null, "#!/usr/bin/go-go-go\na=b", StandardCharsets.UTF_8); assertEquals(PROPERTIES, getFileType(file)); } finally { myFileTypeManager.getExtensionMap().removeHashBangPattern("go-go-go", fileType); } } private static class MyTestFileType implements FileType { public static final String NAME = "Foo files"; public static final String EXTENSION = "from_test_plugin"; private MyTestFileType() { } @Override public @NotNull String getName() { return NAME; } @Override public @NotNull String getDescription() { return ""; } @Override public @NotNull String getDefaultExtension() { return EXTENSION; } @Override public @Nullable Icon getIcon() { return null; } @Override public boolean isBinary() { return false; } } private static class MyHaskellFileType implements FileType { public static final String NAME = "Haskell"; private MyHaskellFileType() { } @Override public @NotNull String getName() { return NAME; } @Override public @NotNull String getDescription() { return ""; } @Override public @NotNull String getDefaultExtension() { return "hs"; } @Override public @Nullable Icon getIcon() { return null; } @Override public boolean isBinary() { return false; } } public void testFileTypeConstructorsMustBeNonPublic() { FileType[] fileTypes = myFileTypeManager.getRegisteredFileTypes(); LOG.debug("Registered file types: "+fileTypes.length); for (FileType fileType : fileTypes) { assertEquals(fileType, fileType); // assert reflexivity if (fileType.getClass() == AbstractFileType.class) { continue; } Constructor<?>[] constructors = fileType.getClass().getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { assertFalse("FileType constructor must be non-public to avoid duplicates but got: " + constructor, Modifier.isPublic(constructor.getModifiers())); } } } public void testDetectedAsTextMustNotStuckWithUnknownFileTypeWhenShrunkToZeroLength() throws IOException { File f = createTempFile("xx.lkj_lkj_lkj_ljk", "a"); VirtualFile virtualFile = getVirtualFile(f); assertEquals(PlainTextFileType.INSTANCE, getFileType(virtualFile)); setBinaryContent(virtualFile, new byte[0]); myFileTypeManager.drainReDetectQueue(); assertEquals(UnknownFileType.INSTANCE, getFileType(virtualFile)); setBinaryContent(virtualFile, "qwe\newq".getBytes(StandardCharsets.UTF_8)); myFileTypeManager.drainReDetectQueue(); assertEquals(PlainTextFileType.INSTANCE, getFileType(virtualFile)); } public void testRegisterFileTypesWithIdenticalDisplayNameOrDescriptionMustThrow() { DefaultLogger.disableStderrDumping(getTestRootDisposable()); Disposable disposable1 = Disposer.newDisposable(); try { createFakeType("myCreativeName0", "display1", "descr1", "ext1", disposable1); assertThrows(Throwable.class, () -> createFakeType("myCreativeName1", "display1", "descr2", "ext2", disposable1)); } finally { Disposer.dispose(disposable1); } Disposable disposable2 = Disposer.newDisposable(); try { createFakeType("myCreativeName2", "display0", "descr", "ext1", disposable2); assertThrows(Throwable.class, () -> createFakeType("myCreativeName3", "display1", "descr", "ext2", disposable2)); } finally { Disposer.dispose(disposable2); } } private @NotNull FileType createFakeType(@NotNull String name, @NotNull String displayName, @NotNull String description, @NotNull String extension, @NotNull Disposable disposable) { FileType myType = new FakeFileType() { @Override public boolean isMyFileType(@NotNull VirtualFile file) { return false; } @Override public @NotNull String getName() { return name; } @Override public @Nls @NotNull String getDisplayName() { return displayName; } @Override public @NotNull @NlsContexts.Label String getDescription() { return description; } }; myFileTypeManager.registerFileType(myType, List.of(new ExtensionFileNameMatcher(extension)), disposable); return myType; } public void testDetectorMustWorkForEmptyFileNow() throws IOException { Set<VirtualFile> detectorCalled = ContainerUtil.newConcurrentSet(); String magicName = "blah-blah.to.detect"; FileTypeRegistry.FileTypeDetector detector = (file, __, ___) -> { detectorCalled.add(file); return file.getName().equals(magicName) ? new MyTestFileType() : null; }; runWithDetector(detector, () -> { VirtualFile vFile = createTempVirtualFile(magicName, null, "", StandardCharsets.UTF_8); ensureReDetected(vFile, detectorCalled); assertTrue(getFileType(vFile).toString(), getFileType(vFile) instanceof MyTestFileType); }); } public void testNewRegisteredFileTypeWithMatchersDuplicatingNativeFileTypeMustWin() { String nativeExt = myFileTypeManager.getAssociations(NativeFileType.INSTANCE).get(0).toString().replace("*.", ""); assertFalse(StringUtil.isEmpty(nativeExt)); assertEquals(NativeFileType.INSTANCE, myFileTypeManager.getFileTypeByExtension(nativeExt)); FakeFileType newFileType = new FakeFileType() { @Override public boolean isMyFileType(@NotNull VirtualFile file) { return false; } @Override public @NotNull String getName() { return "Foo"; } @Override public @NotNull String getDescription() { return "Foo"; } }; Disposable disposable = Disposer.newDisposable(); try { myFileTypeManager.registerFileType(newFileType, List.of(new ExtensionFileNameMatcher(nativeExt)), disposable); assertEquals("Foo", myFileTypeManager.getFileTypeByFileName("foo." + nativeExt).getName()); } finally { Disposer.dispose(disposable); } } public void testFileTypeManagerInitMustReadRemovedMappingBeforeShowingConflictNotification() { String myWeirdExtension = "my_weird_extension"; myFileTypeManager.getRemovedMappingTracker().add(new ExtensionFileNameMatcher(myWeirdExtension), PlainTextFileType.INSTANCE.getName(), true); Element stateWithRemovedMapping = myFileTypeManager.getState(); WriteAction.run(() -> myFileTypeManager.associateExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); Disposable disposable = Disposer.newDisposable(); try { // now, ordinarily we'd get conflict, but thanks to externalized removed mapping tracker, we won't reInitFileTypeManagerComponent(stateWithRemovedMapping); FileType myType = createFakeType("myType", "myDisplayName", "myDescription", myWeirdExtension, disposable); assertEmpty(myConflicts); assertEquals(myType, myFileTypeManager.getFileTypeByExtension(myWeirdExtension)); } finally { Disposer.dispose(disposable); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); } } public void testFileTypeManagerInitMustReadRemovedMappingBeforeShowingConflictNotification2() { String myWeirdExtension = "my_weird_extension"; Disposable disposable = Disposer.newDisposable(); try { FileType myType = createFakeType("myType", "myDisplayName", "myDescription", myWeirdExtension, disposable); myFileTypeManager.getRemovedMappingTracker().add(new ExtensionFileNameMatcher(myWeirdExtension), myType.getName(), true); Element stateWithRemovedMapping = myFileTypeManager.getState(); WriteAction.run(() -> myFileTypeManager.associateExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); // now, ordinarily we'd get conflict, but thanks to externalized removed mapping tracker, we won't reInitFileTypeManagerComponent(stateWithRemovedMapping); assertEmpty(myConflicts); assertEquals(PlainTextFileType.INSTANCE, myFileTypeManager.getFileTypeByExtension(myWeirdExtension)); } finally { Disposer.dispose(disposable); WriteAction.run(() -> myFileTypeManager.removeAssociatedExtension(PlainTextFileType.INSTANCE, myWeirdExtension)); } } public void testIsFileOfTypeMustNotQueryAllFileTypesIdentifiableByVirtualFileForPerformanceReasons() throws IOException { Disposable disposable = Disposer.newDisposable(); try { AtomicInteger myFileTypeCalledCount = new AtomicInteger(); class MyFileTypeIdentifiableByFile extends FakeFileType { @Override public boolean isMyFileType(@NotNull VirtualFile file) { myFileTypeCalledCount.incrementAndGet(); return false; } @Override public @NotNull String getName() { return "myfake"; } @Override public @Nls @NotNull String getDisplayName() { return getName(); } @Override public @NotNull @NlsContexts.Label String getDescription() { return getName(); } } myFileTypeManager.registerFileType(new MyFileTypeIdentifiableByFile(), List.of(), disposable); AtomicInteger otherFileTypeCalledCount = new AtomicInteger(); class MyOtherFileTypeIdentifiableByFile extends FakeFileType { @Override public boolean isMyFileType(@NotNull VirtualFile file) { otherFileTypeCalledCount.incrementAndGet(); return false; } @Override public @NotNull String getName() { return "myotherfake"; } @Override public @Nls @NotNull String getDisplayName() { return getName(); } @Override public @NotNull @NlsContexts.Label String getDescription() { return getName(); } } myFileTypeManager.registerFileType(new MyOtherFileTypeIdentifiableByFile(), List.of(), disposable); File f = createTempFile("xx.lkj_lkj_lkj_ljk", "a"); VirtualFile virtualFile = getVirtualFile(f); FakeVirtualFile vf = new FakeVirtualFile(virtualFile, "myname.myname") { @Override public @NotNull FileType getFileType() { return myFileTypeManager.getFileTypeByFile(this); // otherwise this call will be redirected to FileTypeManger.getInstance() which is not what we are testing } @Override public boolean isValid() { return false; //to avoid detect by content } }; FileType ft = myFileTypeManager.getFileTypeByFile(vf); assertEquals(UnknownFileType.INSTANCE, ft); // during getFileType() we must check all possible file types assertTrue(myFileTypeCalledCount.toString(), myFileTypeCalledCount.get() > 0); assertTrue(otherFileTypeCalledCount.toString(), otherFileTypeCalledCount.get() > 0); myFileTypeCalledCount.set(0); otherFileTypeCalledCount.set(0); assertFalse(myFileTypeManager.isFileOfType(vf, PlainTextFileType.INSTANCE)); assertEquals(myFileTypeCalledCount.toString(), 0, myFileTypeCalledCount.get()); assertEquals(otherFileTypeCalledCount.toString(), 0, otherFileTypeCalledCount.get()); assertFalse(myFileTypeManager.isFileOfType(vf, new MyOtherFileTypeIdentifiableByFile())); assertEquals(myFileTypeCalledCount.toString(), 0, myFileTypeCalledCount.get()); // must not call irrelevant file types assertTrue(otherFileTypeCalledCount.toString(), otherFileTypeCalledCount.get() > 0); // must call requested file type } finally { Disposer.dispose(disposable); } } }
{ "content_hash": "9dd8d7c8478b537772dc8442784f95b7", "timestamp": "", "source": "github", "line_count": 1466, "max_line_length": 166, "avg_line_length": 46.53547066848567, "alnum_prop": 0.7252752085135076, "repo_name": "smmribeiro/intellij-community", "id": "c86b476d152102fbc96a6de42ff2b3518d555571", "size": "68342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.bytebeats.codelab.generator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; public class CodeGenerator { public static void generate(Map<String, Object> root, File templateDir, String templateFilename, File outputFile) throws IOException, TemplateException{ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(templateDir); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Template temp = cfg.getTemplate(templateFilename); // load E:/Work/Freemarker/templates/person.ftl // Writer out = new OutputStreamWriter(System.out); OutputStream fos = new FileOutputStream(outputFile); //生成java文件的路径 Writer out = new OutputStreamWriter(fos); temp.process(root, out); fos.flush(); fos.close(); System.out.println("gen code success!"); } }
{ "content_hash": "d318b1de62fb858b7069bc8d5b399267", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 153, "avg_line_length": 32.73684210526316, "alnum_prop": 0.77491961414791, "repo_name": "FBing/cglib-demo", "id": "fcc6c62b27976ce4847ade226f97ff779f16d4cf", "size": "1258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code-generator/src/main/java/com/bytebeats/codelab/generator/CodeGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8065" } ], "symlink_target": "" }
const versionMixin = { data () { return { clientVersionName: '', apiVersionName: '' } }, methods: { refreshVersionNames () { const capabilities = this.$store.get('capabilities') if (capabilities) { if (capabilities.client) { this.clientVersionName = capabilities.client.version if (capabilities.client.buildNumber) { this.clientVersionName += ' (' + capabilities.client.buildNumber + ')' } } if (capabilities.api) { this.apiVersionName = capabilities.api.version if (capabilities.api.buildNumber) { this.apiVersionName += ' (' + capabilities.api.buildNumber + ')' } } } } }, created () { this.refreshVersionNames() this.$events.$on('capabilities-api-changed', this.refreshVersionNames) }, beforeDestroy () { this.$events.$off('capabilities-api-changed', this.refreshVersionNames) } } export default versionMixin
{ "content_hash": "f3aebf7520886d0bdeb983919a7c7fc8", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 82, "avg_line_length": 27.86111111111111, "alnum_prop": 0.5962113659022931, "repo_name": "kalisio/kCore", "id": "afaaf46773ddbbcc5f7e45b1bb783b5ad9dde590", "size": "1003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/mixins/mixin.version.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "196155" }, { "name": "Vue", "bytes": "186008" } ], "symlink_target": "" }
<div class="leaflet-control-timeline leaflet-control-timeline-collapsed leaflet-control"> <a class="leaflet-control-timeline-toggle" href="#" title="Timeline"></a> </div>
{ "content_hash": "018c2d3ac033765a455a44697d31ec59", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 89, "avg_line_length": 58, "alnum_prop": 0.7471264367816092, "repo_name": "kirschbombe/boulevardier", "id": "409ecd80542320716a3cc772e3ad036d93ac06e2", "size": "174", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "dist/partials/timeline.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11367" }, { "name": "HTML", "bytes": "21909" }, { "name": "JavaScript", "bytes": "97729" }, { "name": "Shell", "bytes": "694" }, { "name": "XSLT", "bytes": "15612" } ], "symlink_target": "" }
#include "rawdataset.h" #include "ogr_spatialref.h" #include "cpl_string.h" #include "ershdrnode.h" CPL_CVSID("$Id: ersdataset.cpp 24927 2012-09-16 12:14:44Z rouault $"); /************************************************************************/ /* ==================================================================== */ /* ERSDataset */ /* ==================================================================== */ /************************************************************************/ class ERSRasterBand; class ERSDataset : public RawDataset { friend class ERSRasterBand; VSILFILE *fpImage; // image data file. GDALDataset *poDepFile; int bGotTransform; double adfGeoTransform[6]; char *pszProjection; CPLString osRawFilename; int bHDRDirty; ERSHdrNode *poHeader; const char *Find( const char *, const char * ); int nGCPCount; GDAL_GCP *pasGCPList; char *pszGCPProjection; void ReadGCPs(); int bHasNoDataValue; double dfNoDataValue; CPLString osProj; CPLString osDatum; CPLString osUnits; void WriteProjectionInfo(const char* pszProj, const char* pszDatum, const char* pszUnits); CPLStringList oERSMetadataList; protected: virtual int CloseDependentDatasets(); public: ERSDataset(); ~ERSDataset(); virtual void FlushCache(void); virtual CPLErr GetGeoTransform( double * padfTransform ); virtual CPLErr SetGeoTransform( double *padfTransform ); virtual const char *GetProjectionRef(void); virtual CPLErr SetProjection( const char * ); virtual char **GetFileList(void); virtual int GetGCPCount(); virtual const char *GetGCPProjection(); virtual const GDAL_GCP *GetGCPs(); virtual CPLErr SetGCPs( int nGCPCount, const GDAL_GCP *pasGCPList, const char *pszGCPProjection ); virtual const char *GetMetadataItem( const char * pszName, const char * pszDomain = "" ); virtual char **GetMetadata( const char * pszDomain = "" ); static GDALDataset *Open( GDALOpenInfo * ); static int Identify( GDALOpenInfo * ); static GDALDataset *Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszParmList ); }; /************************************************************************/ /* ERSDataset() */ /************************************************************************/ ERSDataset::ERSDataset() { fpImage = NULL; poDepFile = NULL; pszProjection = CPLStrdup(""); bGotTransform = FALSE; adfGeoTransform[0] = 0.0; adfGeoTransform[1] = 1.0; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = 0.0; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = 1.0; poHeader = NULL; bHDRDirty = FALSE; nGCPCount = 0; pasGCPList = NULL; pszGCPProjection = CPLStrdup(""); bHasNoDataValue = FALSE; dfNoDataValue = 0.0; } /************************************************************************/ /* ~ERSDataset() */ /************************************************************************/ ERSDataset::~ERSDataset() { FlushCache(); if( fpImage != NULL ) { VSIFCloseL( fpImage ); } CloseDependentDatasets(); CPLFree( pszProjection ); CPLFree( pszGCPProjection ); if( nGCPCount > 0 ) { GDALDeinitGCPs( nGCPCount, pasGCPList ); CPLFree( pasGCPList ); } if( poHeader != NULL ) delete poHeader; } /************************************************************************/ /* CloseDependentDatasets() */ /************************************************************************/ int ERSDataset::CloseDependentDatasets() { int bHasDroppedRef = RawDataset::CloseDependentDatasets(); if( poDepFile != NULL ) { int iBand; bHasDroppedRef = TRUE; for( iBand = 0; iBand < nBands; iBand++ ) papoBands[iBand] = NULL; nBands = 0; GDALClose( (GDALDatasetH) poDepFile ); poDepFile = NULL; } return bHasDroppedRef; } /************************************************************************/ /* FlushCache() */ /************************************************************************/ void ERSDataset::FlushCache() { if( bHDRDirty ) { VSILFILE * fpERS = VSIFOpenL( GetDescription(), "w" ); if( fpERS == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to rewrite %s header.", GetDescription() ); } else { VSIFPrintfL( fpERS, "DatasetHeader Begin\n" ); poHeader->WriteSelf( fpERS, 1 ); VSIFPrintfL( fpERS, "DatasetHeader End\n" ); VSIFCloseL( fpERS ); } } RawDataset::FlushCache(); } /************************************************************************/ /* GetMetadataItem() */ /************************************************************************/ const char *ERSDataset::GetMetadataItem( const char * pszName, const char * pszDomain ) { if (pszDomain != NULL && EQUAL(pszDomain, "ERS") && pszName != NULL) { if (EQUAL(pszName, "PROJ")) return osProj.size() ? osProj.c_str() : NULL; if (EQUAL(pszName, "DATUM")) return osDatum.size() ? osDatum.c_str() : NULL; if (EQUAL(pszName, "UNITS")) return osUnits.size() ? osUnits.c_str() : NULL; } return GDALPamDataset::GetMetadataItem(pszName, pszDomain); } /************************************************************************/ /* GetMetadata() */ /************************************************************************/ char **ERSDataset::GetMetadata( const char *pszDomain ) { if( pszDomain != NULL && EQUAL(pszDomain, "ERS") ) { oERSMetadataList.Clear(); if (osProj.size()) oERSMetadataList.AddString(CPLSPrintf("%s=%s", "PROJ", osProj.c_str())); if (osDatum.size()) oERSMetadataList.AddString(CPLSPrintf("%s=%s", "DATUM", osDatum.c_str())); if (osUnits.size()) oERSMetadataList.AddString(CPLSPrintf("%s=%s", "UNITS", osUnits.c_str())); return oERSMetadataList.List(); } else return GDALPamDataset::GetMetadata( pszDomain ); } /************************************************************************/ /* GetGCPCount() */ /************************************************************************/ int ERSDataset::GetGCPCount() { return nGCPCount; } /************************************************************************/ /* GetGCPProjection() */ /************************************************************************/ const char *ERSDataset::GetGCPProjection() { return pszGCPProjection; } /************************************************************************/ /* GetGCPs() */ /************************************************************************/ const GDAL_GCP *ERSDataset::GetGCPs() { return pasGCPList; } /************************************************************************/ /* SetGCPs() */ /************************************************************************/ CPLErr ERSDataset::SetGCPs( int nGCPCountIn, const GDAL_GCP *pasGCPListIn, const char *pszGCPProjectionIn ) { /* -------------------------------------------------------------------- */ /* Clean old gcps. */ /* -------------------------------------------------------------------- */ CPLFree( pszGCPProjection ); pszGCPProjection = NULL; if( nGCPCount > 0 ) { GDALDeinitGCPs( nGCPCount, pasGCPList ); CPLFree( pasGCPList ); pasGCPList = NULL; nGCPCount = 0; } /* -------------------------------------------------------------------- */ /* Copy new ones. */ /* -------------------------------------------------------------------- */ nGCPCount = nGCPCountIn; pasGCPList = GDALDuplicateGCPs( nGCPCount, pasGCPListIn ); pszGCPProjection = CPLStrdup( pszGCPProjectionIn ); /* -------------------------------------------------------------------- */ /* Setup the header contents corresponding to these GCPs. */ /* -------------------------------------------------------------------- */ bHDRDirty = TRUE; poHeader->Set( "RasterInfo.WarpControl.WarpType", "Polynomial" ); if( nGCPCount > 6 ) poHeader->Set( "RasterInfo.WarpControl.WarpOrder", "2" ); else poHeader->Set( "RasterInfo.WarpControl.WarpOrder", "1" ); poHeader->Set( "RasterInfo.WarpControl.WarpSampling", "Nearest" ); /* -------------------------------------------------------------------- */ /* Translate the projection. */ /* -------------------------------------------------------------------- */ OGRSpatialReference oSRS( pszGCPProjection ); char szERSProj[32], szERSDatum[32], szERSUnits[32]; oSRS.exportToERM( szERSProj, szERSDatum, szERSUnits ); /* Write the above computed values, unless they have been overriden by */ /* the creation options PROJ, DATUM or UNITS */ poHeader->Set( "RasterInfo.WarpControl.CoordinateSpace.Datum", CPLString().Printf( "\"%s\"", (osDatum.size()) ? osDatum.c_str() : szERSDatum ) ); poHeader->Set( "RasterInfo.WarpControl.CoordinateSpace.Projection", CPLString().Printf( "\"%s\"", (osProj.size()) ? osProj.c_str() : szERSProj ) ); poHeader->Set( "RasterInfo.WarpControl.CoordinateSpace.CoordinateType", CPLString().Printf( "EN" ) ); poHeader->Set( "RasterInfo.WarpControl.CoordinateSpace.Units", CPLString().Printf( "\"%s\"", (osUnits.size()) ? osUnits.c_str() : szERSUnits ) ); poHeader->Set( "RasterInfo.WarpControl.CoordinateSpace.Rotation", "0:0:0.0" ); /* -------------------------------------------------------------------- */ /* Translate the GCPs. */ /* -------------------------------------------------------------------- */ CPLString osControlPoints = "{\n"; int iGCP; for( iGCP = 0; iGCP < nGCPCount; iGCP++ ) { CPLString osLine; CPLString osId = pasGCPList[iGCP].pszId; if( strlen(osId) == 0 ) osId.Printf( "%d", iGCP + 1 ); osLine.Printf( "\t\t\t\t\"%s\"\tYes\tYes\t%.6f\t%.6f\t%.15g\t%.15g\t%.15g\n", osId.c_str(), pasGCPList[iGCP].dfGCPPixel, pasGCPList[iGCP].dfGCPLine, pasGCPList[iGCP].dfGCPX, pasGCPList[iGCP].dfGCPY, pasGCPList[iGCP].dfGCPZ ); osControlPoints += osLine; } osControlPoints += "\t\t}"; poHeader->Set( "RasterInfo.WarpControl.ControlPoints", osControlPoints ); return CE_None; } /************************************************************************/ /* GetProjectionRef() */ /************************************************************************/ const char *ERSDataset::GetProjectionRef() { // try xml first const char* pszPrj = GDALPamDataset::GetProjectionRef(); if(pszPrj && strlen(pszPrj) > 0) return pszPrj; return pszProjection; } /************************************************************************/ /* SetProjection() */ /************************************************************************/ CPLErr ERSDataset::SetProjection( const char *pszSRS ) { if( pszProjection && EQUAL(pszSRS,pszProjection) ) return CE_None; if( pszSRS == NULL ) pszSRS = ""; CPLFree( pszProjection ); pszProjection = CPLStrdup(pszSRS); OGRSpatialReference oSRS( pszSRS ); char szERSProj[32], szERSDatum[32], szERSUnits[32]; oSRS.exportToERM( szERSProj, szERSDatum, szERSUnits ); /* Write the above computed values, unless they have been overriden by */ /* the creation options PROJ, DATUM or UNITS */ WriteProjectionInfo( (osProj.size()) ? osProj.c_str() : szERSProj, (osDatum.size()) ? osDatum.c_str() : szERSDatum, (osUnits.size()) ? osUnits.c_str() : szERSUnits ); return CE_None; } /************************************************************************/ /* WriteProjectionInfo() */ /************************************************************************/ void ERSDataset::WriteProjectionInfo(const char* pszProj, const char* pszDatum, const char* pszUnits) { bHDRDirty = TRUE; poHeader->Set( "CoordinateSpace.Datum", CPLString().Printf( "\"%s\"", pszDatum ) ); poHeader->Set( "CoordinateSpace.Projection", CPLString().Printf( "\"%s\"", pszProj ) ); poHeader->Set( "CoordinateSpace.CoordinateType", CPLString().Printf( "EN" ) ); poHeader->Set( "CoordinateSpace.Units", CPLString().Printf( "\"%s\"", pszUnits ) ); poHeader->Set( "CoordinateSpace.Rotation", "0:0:0.0" ); /* -------------------------------------------------------------------- */ /* It seems that CoordinateSpace needs to come before */ /* RasterInfo. Try moving it up manually. */ /* -------------------------------------------------------------------- */ int iRasterInfo = -1; int iCoordSpace = -1; int i; for( i = 0; i < poHeader->nItemCount; i++ ) { if( EQUAL(poHeader->papszItemName[i],"RasterInfo") ) iRasterInfo = i; if( EQUAL(poHeader->papszItemName[i],"CoordinateSpace") ) { iCoordSpace = i; break; } } if( iCoordSpace > iRasterInfo && iRasterInfo != -1 ) { for( i = iCoordSpace; i > 0 && i != iRasterInfo; i-- ) { char *pszTemp; ERSHdrNode *poTemp = poHeader->papoItemChild[i]; poHeader->papoItemChild[i] = poHeader->papoItemChild[i-1]; poHeader->papoItemChild[i-1] = poTemp; pszTemp = poHeader->papszItemName[i]; poHeader->papszItemName[i] = poHeader->papszItemName[i-1]; poHeader->papszItemName[i-1] = pszTemp; pszTemp = poHeader->papszItemValue[i]; poHeader->papszItemValue[i] = poHeader->papszItemValue[i-1]; poHeader->papszItemValue[i-1] = pszTemp; } } } /************************************************************************/ /* GetGeoTransform() */ /************************************************************************/ CPLErr ERSDataset::GetGeoTransform( double * padfTransform ) { if( bGotTransform ) { memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 ); return CE_None; } else { return GDALPamDataset::GetGeoTransform( padfTransform ); } } /************************************************************************/ /* SetGeoTransform() */ /************************************************************************/ CPLErr ERSDataset::SetGeoTransform( double *padfTransform ) { if( memcmp( padfTransform, adfGeoTransform, sizeof(double)*6 ) == 0 ) return CE_None; if( adfGeoTransform[2] != 0 || adfGeoTransform[4] != 0 ) { CPLError( CE_Failure, CPLE_AppDefined, "Rotated and skewed geotransforms not currently supported for ERS driver." ); return CE_Failure; } bGotTransform = TRUE; memcpy( adfGeoTransform, padfTransform, sizeof(double) * 6 ); bHDRDirty = TRUE; poHeader->Set( "RasterInfo.CellInfo.Xdimension", CPLString().Printf( "%.15g", fabs(adfGeoTransform[1]) ) ); poHeader->Set( "RasterInfo.CellInfo.Ydimension", CPLString().Printf( "%.15g", fabs(adfGeoTransform[5]) ) ); poHeader->Set( "RasterInfo.RegistrationCoord.Eastings", CPLString().Printf( "%.15g", adfGeoTransform[0] ) ); poHeader->Set( "RasterInfo.RegistrationCoord.Northings", CPLString().Printf( "%.15g", adfGeoTransform[3] ) ); return CE_None; } /************************************************************************/ /* ERSDMS2Dec() */ /* */ /* Convert ERS DMS format to decimal degrees. Input is like */ /* "-180:00:00". */ /************************************************************************/ static double ERSDMS2Dec( const char *pszDMS ) { char **papszTokens = CSLTokenizeStringComplex( pszDMS, ":", FALSE, FALSE ); if( CSLCount(papszTokens) != 3 ) { CSLDestroy(papszTokens); return CPLAtof( pszDMS ); } else { double dfResult = fabs(CPLAtof(papszTokens[0])) + CPLAtof(papszTokens[1]) / 60.0 + CPLAtof(papszTokens[2]) / 3600.0; if( CPLAtof(papszTokens[0]) < 0 ) dfResult *= -1; CSLDestroy( papszTokens ); return dfResult; } } /************************************************************************/ /* GetFileList() */ /************************************************************************/ char **ERSDataset::GetFileList() { char **papszFileList = NULL; // Main data file, etc. papszFileList = GDALPamDataset::GetFileList(); // Add raw data file if we have one. if( strlen(osRawFilename) > 0 ) papszFileList = CSLAddString( papszFileList, osRawFilename ); // If we have a dependent file, merge it's list of files in. if( poDepFile ) { char **papszDepFiles = poDepFile->GetFileList(); papszFileList = CSLInsertStrings( papszFileList, -1, papszDepFiles ); CSLDestroy( papszDepFiles ); } return papszFileList; } /************************************************************************/ /* ReadGCPs() */ /* */ /* Read the GCPs from the header. */ /************************************************************************/ void ERSDataset::ReadGCPs() { const char *pszCP = poHeader->Find( "RasterInfo.WarpControl.ControlPoints", NULL ); if( pszCP == NULL ) return; /* -------------------------------------------------------------------- */ /* Parse the control points. They will look something like: */ /* */ /* "1035" Yes No 2344.650885 3546.419458 483270.73 3620906.21 3.105 */ /* -------------------------------------------------------------------- */ char **papszTokens = CSLTokenizeStringComplex( pszCP, "{ \t}", TRUE,FALSE); int nItemsPerLine; int nItemCount = CSLCount(papszTokens); /* -------------------------------------------------------------------- */ /* Work out if we have elevation values or not. */ /* -------------------------------------------------------------------- */ if( nItemCount == 7 ) nItemsPerLine = 7; else if( nItemCount == 8 ) nItemsPerLine = 8; else if( nItemCount < 14 ) { CPLDebug("ERS", "Invalid item count for ControlPoints"); CSLDestroy( papszTokens ); return; } else if( EQUAL(papszTokens[8],"Yes") || EQUAL(papszTokens[8],"No") ) nItemsPerLine = 7; else if( EQUAL(papszTokens[9],"Yes") || EQUAL(papszTokens[9],"No") ) nItemsPerLine = 8; else { CPLDebug("ERS", "Invalid format for ControlPoints"); CSLDestroy( papszTokens ); return; } /* -------------------------------------------------------------------- */ /* Setup GCPs. */ /* -------------------------------------------------------------------- */ int iGCP; CPLAssert( nGCPCount == 0 ); nGCPCount = nItemCount / nItemsPerLine; pasGCPList = (GDAL_GCP *) CPLCalloc(nGCPCount,sizeof(GDAL_GCP)); GDALInitGCPs( nGCPCount, pasGCPList ); for( iGCP = 0; iGCP < nGCPCount; iGCP++ ) { GDAL_GCP *psGCP = pasGCPList + iGCP; CPLFree( psGCP->pszId ); psGCP->pszId = CPLStrdup(papszTokens[iGCP*nItemsPerLine+0]); psGCP->dfGCPPixel = atof(papszTokens[iGCP*nItemsPerLine+3]); psGCP->dfGCPLine = atof(papszTokens[iGCP*nItemsPerLine+4]); psGCP->dfGCPX = atof(papszTokens[iGCP*nItemsPerLine+5]); psGCP->dfGCPY = atof(papszTokens[iGCP*nItemsPerLine+6]); if( nItemsPerLine == 8 ) psGCP->dfGCPZ = atof(papszTokens[iGCP*nItemsPerLine+7]); } CSLDestroy( papszTokens ); /* -------------------------------------------------------------------- */ /* Parse the GCP projection. */ /* -------------------------------------------------------------------- */ OGRSpatialReference oSRS; osProj = poHeader->Find( "RasterInfo.WarpControl.CoordinateSpace.Projection", "" ); osDatum = poHeader->Find( "RasterInfo.WarpControl.CoordinateSpace.Datum", "" ); osUnits = poHeader->Find( "RasterInfo.WarpControl.CoordinateSpace.Units", "" ); oSRS.importFromERM( osProj.size() ? osProj.c_str() : "RAW", osDatum.size() ? osDatum.c_str() : "WGS84", osUnits.size() ? osUnits.c_str() : "METERS" ); CPLFree( pszGCPProjection ); oSRS.exportToWkt( &pszGCPProjection ); } /************************************************************************/ /* ==================================================================== */ /* ERSRasterBand */ /* ==================================================================== */ /************************************************************************/ class ERSRasterBand : public RawRasterBand { public: ERSRasterBand( GDALDataset *poDS, int nBand, void * fpRaw, vsi_l_offset nImgOffset, int nPixelOffset, int nLineOffset, GDALDataType eDataType, int bNativeOrder, int bIsVSIL = FALSE, int bOwnsFP = FALSE ); virtual double GetNoDataValue( int *pbSuccess = NULL ); virtual CPLErr SetNoDataValue( double ); }; /************************************************************************/ /* ERSRasterBand() */ /************************************************************************/ ERSRasterBand::ERSRasterBand( GDALDataset *poDS, int nBand, void * fpRaw, vsi_l_offset nImgOffset, int nPixelOffset, int nLineOffset, GDALDataType eDataType, int bNativeOrder, int bIsVSIL, int bOwnsFP ) : RawRasterBand(poDS, nBand, fpRaw, nImgOffset, nPixelOffset, nLineOffset, eDataType, bNativeOrder, bIsVSIL, bOwnsFP) { } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double ERSRasterBand::GetNoDataValue( int *pbSuccess ) { ERSDataset* poGDS = (ERSDataset*) poDS; if (poGDS->bHasNoDataValue) { if (pbSuccess) *pbSuccess = TRUE; return poGDS->dfNoDataValue; } return RawRasterBand::GetNoDataValue(pbSuccess); } /************************************************************************/ /* SetNoDataValue() */ /************************************************************************/ CPLErr ERSRasterBand::SetNoDataValue( double dfNoDataValue ) { ERSDataset* poGDS = (ERSDataset*) poDS; if (!poGDS->bHasNoDataValue || poGDS->dfNoDataValue != dfNoDataValue) { poGDS->bHasNoDataValue = TRUE; poGDS->dfNoDataValue = dfNoDataValue; poGDS->bHDRDirty = TRUE; poGDS->poHeader->Set( "RasterInfo.NullCellValue", CPLString().Printf( "%.16g", dfNoDataValue) ); } return CE_None; } /************************************************************************/ /* Identify() */ /************************************************************************/ int ERSDataset::Identify( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* We assume the user selects the .ers file. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes > 15 && EQUALN((const char *) poOpenInfo->pabyHeader,"Algorithm Begin",15) ) { CPLError( CE_Failure, CPLE_OpenFailed, "%s appears to be an algorithm ERS file, which is not currently supported.", poOpenInfo->pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* We assume the user selects the .ers file. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes < 15 || !EQUALN((const char *) poOpenInfo->pabyHeader,"DatasetHeader ",14) ) return FALSE; return TRUE; } /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *ERSDataset::Open( GDALOpenInfo * poOpenInfo ) { if( !Identify( poOpenInfo ) ) return NULL; /* -------------------------------------------------------------------- */ /* Open the .ers file, and read the first line. */ /* -------------------------------------------------------------------- */ VSILFILE *fpERS = VSIFOpenL( poOpenInfo->pszFilename, "rb" ); if( fpERS == NULL ) return NULL; CPLReadLineL( fpERS ); /* -------------------------------------------------------------------- */ /* Now ingest the rest of the file as a tree of header nodes. */ /* -------------------------------------------------------------------- */ ERSHdrNode *poHeader = new ERSHdrNode(); if( !poHeader->ParseChildren( fpERS ) ) { delete poHeader; VSIFCloseL( fpERS ); return NULL; } VSIFCloseL( fpERS ); /* -------------------------------------------------------------------- */ /* Do we have the minimum required information from this header? */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.NrOfLines" ) == NULL || poHeader->Find( "RasterInfo.NrOfCellsPerLine" ) == NULL || poHeader->Find( "RasterInfo.NrOfBands" ) == NULL ) { if( poHeader->FindNode( "Algorithm" ) != NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "%s appears to be an algorithm ERS file, which is not currently supported.", poOpenInfo->pszFilename ); } delete poHeader; return NULL; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ ERSDataset *poDS; poDS = new ERSDataset(); poDS->poHeader = poHeader; poDS->eAccess = poOpenInfo->eAccess; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ int nBands = atoi(poHeader->Find( "RasterInfo.NrOfBands" )); poDS->nRasterXSize = atoi(poHeader->Find( "RasterInfo.NrOfCellsPerLine" )); poDS->nRasterYSize = atoi(poHeader->Find( "RasterInfo.NrOfLines" )); if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) || !GDALCheckBandCount(nBands, FALSE)) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Get the HeaderOffset if it exists in the header */ /* -------------------------------------------------------------------- */ GIntBig nHeaderOffset = 0; if( poHeader->Find( "HeaderOffset" ) != NULL ) { nHeaderOffset = atoi(poHeader->Find( "HeaderOffset" )); } /* -------------------------------------------------------------------- */ /* Establish the data type. */ /* -------------------------------------------------------------------- */ GDALDataType eType; CPLString osCellType = poHeader->Find( "RasterInfo.CellType", "Unsigned8BitInteger" ); if( EQUAL(osCellType,"Unsigned8BitInteger") ) eType = GDT_Byte; else if( EQUAL(osCellType,"Signed8BitInteger") ) eType = GDT_Byte; else if( EQUAL(osCellType,"Unsigned16BitInteger") ) eType = GDT_UInt16; else if( EQUAL(osCellType,"Signed16BitInteger") ) eType = GDT_Int16; else if( EQUAL(osCellType,"Unsigned32BitInteger") ) eType = GDT_UInt32; else if( EQUAL(osCellType,"Signed32BitInteger") ) eType = GDT_Int32; else if( EQUAL(osCellType,"IEEE4ByteReal") ) eType = GDT_Float32; else if( EQUAL(osCellType,"IEEE8ByteReal") ) eType = GDT_Float64; else { CPLDebug( "ERS", "Unknown CellType '%s'", osCellType.c_str() ); eType = GDT_Byte; } /* -------------------------------------------------------------------- */ /* Pick up the word order. */ /* -------------------------------------------------------------------- */ int bNative; #ifdef CPL_LSB bNative = EQUAL(poHeader->Find( "ByteOrder", "LSBFirst" ), "LSBFirst"); #else bNative = EQUAL(poHeader->Find( "ByteOrder", "MSBFirst" ), "MSBFirst"); #endif /* -------------------------------------------------------------------- */ /* Figure out the name of the target file. */ /* -------------------------------------------------------------------- */ CPLString osPath = CPLGetPath( poOpenInfo->pszFilename ); CPLString osDataFile = poHeader->Find( "DataFile", "" ); CPLString osDataFilePath; if( osDataFile.length() == 0 ) // just strip off extension. { osDataFile = CPLGetFilename( poOpenInfo->pszFilename ); osDataFile = osDataFile.substr( 0, osDataFile.find_last_of('.') ); } osDataFilePath = CPLFormFilename( osPath, osDataFile, NULL ); /* -------------------------------------------------------------------- */ /* DataSetType = Translated files are links to things like ecw */ /* files. */ /* -------------------------------------------------------------------- */ if( EQUAL(poHeader->Find("DataSetType",""),"Translated") ) { poDS->poDepFile = (GDALDataset *) GDALOpenShared( osDataFilePath, poOpenInfo->eAccess ); if( poDS->poDepFile != NULL && poDS->poDepFile->GetRasterCount() >= nBands ) { int iBand; for( iBand = 0; iBand < nBands; iBand++ ) { // Assume pixel interleaved. poDS->SetBand( iBand+1, poDS->poDepFile->GetRasterBand( iBand+1 ) ); } } } /* ==================================================================== */ /* While ERStorage indicates a raw file. */ /* ==================================================================== */ else if( EQUAL(poHeader->Find("DataSetType",""),"ERStorage") ) { // Open data file. if( poOpenInfo->eAccess == GA_Update ) poDS->fpImage = VSIFOpenL( osDataFilePath, "r+" ); else poDS->fpImage = VSIFOpenL( osDataFilePath, "r" ); poDS->osRawFilename = osDataFilePath; if( poDS->fpImage != NULL ) { int iWordSize = GDALGetDataTypeSize(eType) / 8; int iBand; for( iBand = 0; iBand < nBands; iBand++ ) { // Assume pixel interleaved. poDS->SetBand( iBand+1, new ERSRasterBand( poDS, iBand+1, poDS->fpImage, nHeaderOffset + iWordSize * iBand * poDS->nRasterXSize, iWordSize, iWordSize * nBands * poDS->nRasterXSize, eType, bNative, TRUE )); if( EQUAL(osCellType,"Signed8BitInteger") ) poDS->GetRasterBand(iBand+1)-> SetMetadataItem( "PIXELTYPE", "SIGNEDBYTE", "IMAGE_STRUCTURE" ); } } } /* -------------------------------------------------------------------- */ /* Otherwise we have an error! */ /* -------------------------------------------------------------------- */ if( poDS->nBands == 0 ) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Look for band descriptions. */ /* -------------------------------------------------------------------- */ int iChild, iBand = 0; ERSHdrNode *poRI = poHeader->FindNode( "RasterInfo" ); for( iChild = 0; poRI != NULL && iChild < poRI->nItemCount && iBand < poDS->nBands; iChild++ ) { if( poRI->papoItemChild[iChild] != NULL && EQUAL(poRI->papszItemName[iChild],"BandId") ) { const char *pszValue = poRI->papoItemChild[iChild]->Find( "Value", NULL ); iBand++; if( pszValue ) { CPLPushErrorHandler( CPLQuietErrorHandler ); poDS->GetRasterBand( iBand )->SetDescription( pszValue ); CPLPopErrorHandler(); } pszValue = poRI->papoItemChild[iChild]->Find( "Units", NULL ); if ( pszValue ) { CPLPushErrorHandler( CPLQuietErrorHandler ); poDS->GetRasterBand( iBand )->SetUnitType( pszValue ); CPLPopErrorHandler(); } } } /* -------------------------------------------------------------------- */ /* Look for projection. */ /* -------------------------------------------------------------------- */ OGRSpatialReference oSRS; poDS->osProj = poHeader->Find( "CoordinateSpace.Projection", "" ); poDS->osDatum = poHeader->Find( "CoordinateSpace.Datum", "" ); poDS->osUnits = poHeader->Find( "CoordinateSpace.Units", "" ); oSRS.importFromERM( poDS->osProj.size() ? poDS->osProj.c_str() : "RAW", poDS->osDatum.size() ? poDS->osDatum.c_str() : "WGS84", poDS->osUnits.size() ? poDS->osUnits.c_str() : "METERS" ); CPLFree( poDS->pszProjection ); oSRS.exportToWkt( &(poDS->pszProjection) ); /* -------------------------------------------------------------------- */ /* Look for the geotransform. */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.RegistrationCoord.Eastings", NULL ) ) { poDS->bGotTransform = TRUE; poDS->adfGeoTransform[0] = CPLAtof( poHeader->Find( "RasterInfo.RegistrationCoord.Eastings", "" )); poDS->adfGeoTransform[1] = CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Xdimension", "1.0" )); poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = CPLAtof( poHeader->Find( "RasterInfo.RegistrationCoord.Northings", "" )); poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Ydimension", "1.0" )); } else if( poHeader->Find( "RasterInfo.RegistrationCoord.Latitude", NULL ) && poHeader->Find( "RasterInfo.CellInfo.Xdimension", NULL ) ) { poDS->bGotTransform = TRUE; poDS->adfGeoTransform[0] = ERSDMS2Dec( poHeader->Find( "RasterInfo.RegistrationCoord.Longitude", "" )); poDS->adfGeoTransform[1] = CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Xdimension", "" )); poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = ERSDMS2Dec( poHeader->Find( "RasterInfo.RegistrationCoord.Latitude", "" )); poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Ydimension", "" )); } /* -------------------------------------------------------------------- */ /* Adjust if we have a registration cell. */ /* -------------------------------------------------------------------- */ int iCellX = atoi(poHeader->Find("RasterInfo.RegistrationCellX", "1")); int iCellY = atoi(poHeader->Find("RasterInfo.RegistrationCellY", "1")); if( poDS->bGotTransform ) { poDS->adfGeoTransform[0] -= (iCellX-1) * poDS->adfGeoTransform[1] + (iCellY-1) * poDS->adfGeoTransform[2]; poDS->adfGeoTransform[3] -= (iCellX-1) * poDS->adfGeoTransform[4] + (iCellY-1) * poDS->adfGeoTransform[5]; } /* -------------------------------------------------------------------- */ /* Check for null values. */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.NullCellValue", NULL ) ) { poDS->bHasNoDataValue = TRUE; poDS->dfNoDataValue = CPLAtofM(poHeader->Find( "RasterInfo.NullCellValue" )); if (poDS->poDepFile != NULL) { CPLPushErrorHandler( CPLQuietErrorHandler ); for( iBand = 1; iBand <= poDS->nBands; iBand++ ) poDS->GetRasterBand(iBand)->SetNoDataValue(poDS->dfNoDataValue); CPLPopErrorHandler(); } } /* -------------------------------------------------------------------- */ /* Do we have an "All" region? */ /* -------------------------------------------------------------------- */ ERSHdrNode *poAll = NULL; for( iChild = 0; poRI != NULL && iChild < poRI->nItemCount; iChild++ ) { if( poRI->papoItemChild[iChild] != NULL && EQUAL(poRI->papszItemName[iChild],"RegionInfo") ) { if( EQUAL(poRI->papoItemChild[iChild]->Find("RegionName",""), "All") ) poAll = poRI->papoItemChild[iChild]; } } /* -------------------------------------------------------------------- */ /* Do we have statistics? */ /* -------------------------------------------------------------------- */ if( poAll && poAll->FindNode( "Stats" ) ) { CPLPushErrorHandler( CPLQuietErrorHandler ); for( iBand = 1; iBand <= poDS->nBands; iBand++ ) { const char *pszValue = poAll->FindElem( "Stats.MinimumValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MINIMUM", pszValue ); pszValue = poAll->FindElem( "Stats.MaximumValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MAXIMUM", pszValue ); pszValue = poAll->FindElem( "Stats.MeanValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MEAN", pszValue ); pszValue = poAll->FindElem( "Stats.MedianValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MEDIAN", pszValue ); } CPLPopErrorHandler(); } /* -------------------------------------------------------------------- */ /* Do we have GCPs. */ /* -------------------------------------------------------------------- */ if( poHeader->FindNode( "RasterInfo.WarpControl" ) ) poDS->ReadGCPs(); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); // if no SR in xml, try aux const char* pszPrj = poDS->GDALPamDataset::GetProjectionRef(); if( !pszPrj || strlen(pszPrj) == 0 ) { // try aux GDALDataset* poAuxDS = GDALFindAssociatedAuxFile( poOpenInfo->pszFilename, GA_ReadOnly, poDS ); if( poAuxDS ) { pszPrj = poAuxDS->GetProjectionRef(); if( pszPrj && strlen(pszPrj) > 0 ) { CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(pszPrj); } GDALClose( poAuxDS ); } } /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return( poDS ); } /************************************************************************/ /* Create() */ /************************************************************************/ GDALDataset *ERSDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszOptions ) { /* -------------------------------------------------------------------- */ /* Verify settings. */ /* -------------------------------------------------------------------- */ if (nBands <= 0) { CPLError( CE_Failure, CPLE_NotSupported, "ERS driver does not support %d bands.\n", nBands); return NULL; } if( eType != GDT_Byte && eType != GDT_Int16 && eType != GDT_UInt16 && eType != GDT_Int32 && eType != GDT_UInt32 && eType != GDT_Float32 && eType != GDT_Float64 ) { CPLError( CE_Failure, CPLE_AppDefined, "The ERS driver does not supporting creating files of types %s.", GDALGetDataTypeName( eType ) ); return NULL; } /* -------------------------------------------------------------------- */ /* Work out the name we want to use for the .ers and binary */ /* data files. */ /* -------------------------------------------------------------------- */ CPLString osBinFile, osErsFile; if( EQUAL(CPLGetExtension( pszFilename ), "ers") ) { osErsFile = pszFilename; osBinFile = osErsFile.substr(0,osErsFile.length()-4); } else { osBinFile = pszFilename; osErsFile = osBinFile + ".ers"; } /* -------------------------------------------------------------------- */ /* Work out some values we will write. */ /* -------------------------------------------------------------------- */ const char *pszCellType = "Unsigned8BitInteger"; if( eType == GDT_Byte ) pszCellType = "Unsigned8BitInteger"; else if( eType == GDT_Int16 ) pszCellType = "Signed16BitInteger"; else if( eType == GDT_UInt16 ) pszCellType = "Unsigned16BitInteger"; else if( eType == GDT_Int32 ) pszCellType = "Signed32BitInteger"; else if( eType == GDT_UInt32 ) pszCellType = "Unsigned32BitInteger"; else if( eType == GDT_Float32 ) pszCellType = "IEEE4ByteReal"; else if( eType == GDT_Float64 ) pszCellType = "IEEE8ByteReal"; else { CPLAssert( FALSE ); } /* -------------------------------------------------------------------- */ /* Handling for signed eight bit data. */ /* -------------------------------------------------------------------- */ const char *pszPixelType = CSLFetchNameValue( papszOptions, "PIXELTYPE" ); if( pszPixelType && EQUAL(pszPixelType,"SIGNEDBYTE") && eType == GDT_Byte ) pszCellType = "Signed8BitInteger"; /* -------------------------------------------------------------------- */ /* Write binary file. */ /* -------------------------------------------------------------------- */ GUIntBig nSize; GByte byZero = 0; VSILFILE *fpBin = VSIFOpenL( osBinFile, "w" ); if( fpBin == NULL ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to create %s:\n%s", osBinFile.c_str(), VSIStrerror( errno ) ); return NULL; } nSize = nXSize * (GUIntBig) nYSize * nBands * (GDALGetDataTypeSize(eType) / 8); if( VSIFSeekL( fpBin, nSize-1, SEEK_SET ) != 0 || VSIFWriteL( &byZero, 1, 1, fpBin ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to write %s:\n%s", osBinFile.c_str(), VSIStrerror( errno ) ); VSIFCloseL( fpBin ); return NULL; } VSIFCloseL( fpBin ); /* -------------------------------------------------------------------- */ /* Try writing header file. */ /* -------------------------------------------------------------------- */ VSILFILE *fpERS = VSIFOpenL( osErsFile, "w" ); if( fpERS == NULL ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to create %s:\n%s", osErsFile.c_str(), VSIStrerror( errno ) ); return NULL; } VSIFPrintfL( fpERS, "DatasetHeader Begin\n" ); VSIFPrintfL( fpERS, "\tVersion\t\t = \"6.0\"\n" ); VSIFPrintfL( fpERS, "\tName\t\t= \"%s\"\n", CPLGetFilename(osErsFile) ); // Last updated requires timezone info which we don't necessarily get // get from VSICTime() so perhaps it is better to omit this. // VSIFPrintfL( fpERS, "\tLastUpdated\t= %s", // VSICTime( VSITime( NULL ) ) ); VSIFPrintfL( fpERS, "\tDataSetType\t= ERStorage\n" ); VSIFPrintfL( fpERS, "\tDataType\t= Raster\n" ); VSIFPrintfL( fpERS, "\tByteOrder\t= LSBFirst\n" ); VSIFPrintfL( fpERS, "\tRasterInfo Begin\n" ); VSIFPrintfL( fpERS, "\t\tCellType\t= %s\n", pszCellType ); VSIFPrintfL( fpERS, "\t\tNrOfLines\t= %d\n", nYSize ); VSIFPrintfL( fpERS, "\t\tNrOfCellsPerLine\t= %d\n", nXSize ); VSIFPrintfL( fpERS, "\t\tNrOfBands\t= %d\n", nBands ); VSIFPrintfL( fpERS, "\tRasterInfo End\n" ); if( VSIFPrintfL( fpERS, "DatasetHeader End\n" ) < 17 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to write %s:\n%s", osErsFile.c_str(), VSIStrerror( errno ) ); return NULL; } VSIFCloseL( fpERS ); /* -------------------------------------------------------------------- */ /* Reopen. */ /* -------------------------------------------------------------------- */ GDALOpenInfo oOpenInfo( osErsFile, GA_Update ); ERSDataset* poDS = (ERSDataset*) Open( &oOpenInfo ); if (poDS == NULL) return NULL; /* -------------------------------------------------------------------- */ /* Fetch DATUM, PROJ and UNITS creation option */ /* -------------------------------------------------------------------- */ const char *pszDatum = CSLFetchNameValue( papszOptions, "DATUM" ); if (pszDatum) poDS->osDatum = pszDatum; const char *pszProj = CSLFetchNameValue( papszOptions, "PROJ" ); if (pszProj) poDS->osProj = pszProj; const char *pszUnits = CSLFetchNameValue( papszOptions, "UNITS" ); if (pszUnits) poDS->osUnits = pszUnits; if (pszDatum || pszProj || pszUnits) { poDS->WriteProjectionInfo(pszProj ? pszProj : "RAW", pszDatum ? pszDatum : "RAW", pszUnits ? pszUnits : "METERS"); } return poDS; } /************************************************************************/ /* GDALRegister_ERS() */ /************************************************************************/ void GDALRegister_ERS() { GDALDriver *poDriver; if( GDALGetDriverByName( "ERS" ) == NULL ) { poDriver = new GDALDriver(); poDriver->SetDescription( "ERS" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "ERMapper .ers Labelled" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_ers.html" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte Int16 UInt16 Int32 UInt32 Float32 Float64" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" " <Option name='PIXELTYPE' type='string' description='By setting this to SIGNEDBYTE, a new Byte file can be forced to be written as signed byte'/>" " <Option name='PROJ' type='string' description='ERS Projection Name'/>" " <Option name='DATUM' type='string' description='ERS Datum Name' />" " <Option name='UNITS' type='string-select' description='ERS Projection Units'>" " <Value>METERS</Value>" " <Value>FEET</Value>" " </Option>" "</CreationOptionList>" ); poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); poDriver->pfnOpen = ERSDataset::Open; poDriver->pfnIdentify = ERSDataset::Identify; poDriver->pfnCreate = ERSDataset::Create; GetGDALDriverManager()->RegisterDriver( poDriver ); } }
{ "content_hash": "105b8097e38036e81cb0431458c2d652", "timestamp": "", "source": "github", "line_count": 1412, "max_line_length": 149, "avg_line_length": 37.39589235127479, "alnum_prop": 0.4208662386606822, "repo_name": "TUW-GEO/OGRSpatialRef3D", "id": "ac30ae3af5a68e8466c3675cbc66b48e75c3daa9", "size": "54371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gdal-1.10.0/frmts/ers/ersdataset.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9944221" }, { "name": "C#", "bytes": "134293" }, { "name": "C++", "bytes": "33482636" }, { "name": "IDL", "bytes": "68" }, { "name": "Java", "bytes": "741034" }, { "name": "Objective-C", "bytes": "42440" }, { "name": "OpenEdge ABL", "bytes": "28024" }, { "name": "PHP", "bytes": "106999" }, { "name": "Perl", "bytes": "41158" }, { "name": "Python", "bytes": "904411" }, { "name": "Shell", "bytes": "592442" }, { "name": "TeX", "bytes": "344" }, { "name": "Visual Basic", "bytes": "49037" } ], "symlink_target": "" }
namespace Nz { bool TaskSchedulerImpl::Initialize(std::size_t workerCount) { if (IsInitialized()) return true; // Déjà initialisé #if NAZARA_CORE_SAFE if (workerCount == 0) { NazaraError("Invalid worker count ! (0)"); return false; } #endif s_workerCount = static_cast<DWORD>(workerCount); s_doneEvents.reset(new HANDLE[workerCount]); s_workers.reset(new Worker[workerCount]); s_workerThreads.reset(new HANDLE[workerCount]); // L'identifiant de chaque worker doit rester en vie jusqu'à ce que chaque thread soit correctement lancé std::unique_ptr<std::size_t[]> workerIDs(new std::size_t[workerCount]); for (std::size_t i = 0; i < workerCount; ++i) { // On initialise les évènements, mutex et threads de chaque worker Worker& worker = s_workers[i]; InitializeCriticalSection(&worker.queueMutex); worker.wakeEvent = CreateEventW(nullptr, false, false, nullptr); worker.running = true; worker.workCount = 0; s_doneEvents[i] = CreateEventW(nullptr, true, false, nullptr); // Le thread va se lancer, signaler qu'il est prêt à travailler (s_doneEvents) et attendre d'être réveillé workerIDs[i] = i; s_workerThreads[i] = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, &WorkerProc, &workerIDs[i], 0, nullptr)); } // On attend que les workers se mettent en attente WaitForMultipleObjects(s_workerCount, &s_doneEvents[0], true, INFINITE); return true; } bool TaskSchedulerImpl::IsInitialized() { return s_workerCount > 0; } void TaskSchedulerImpl::Run(Functor** tasks, std::size_t count) { // On s'assure que des tâches ne sont pas déjà en cours WaitForMultipleObjects(s_workerCount, &s_doneEvents[0], true, INFINITE); std::lldiv_t div = std::lldiv(count, s_workerCount); // Division et modulo en une opération, y'a pas de petit profit for (std::size_t i = 0; i < s_workerCount; ++i) { // On va maintenant répartir les tâches entre chaque worker et les envoyer dans la queue de chacun Worker& worker = s_workers[i]; std::size_t taskCount = (i == 0) ? div.quot + div.rem : div.quot; for (std::size_t j = 0; j < taskCount; ++j) worker.queue.push(*tasks++); // On stocke le nombre de tâches à côté dans un entier atomique pour éviter d'entrer inutilement dans une section critique worker.workCount = taskCount; } // On les lance une fois qu'ils sont tous initialisés (pour éviter qu'un worker ne passe en pause détectant une absence de travaux) for (std::size_t i = 0; i < s_workerCount; ++i) { ResetEvent(s_doneEvents[i]); SetEvent(s_workers[i].wakeEvent); } } void TaskSchedulerImpl::Uninitialize() { #ifdef NAZARA_CORE_SAFE if (s_workerCount == 0) { NazaraError("Task scheduler is not initialized"); return; } #endif // On commence par vider la queue de chaque worker pour s'assurer qu'ils s'arrêtent for (unsigned int i = 0; i < s_workerCount; ++i) { Worker& worker = s_workers[i]; worker.running = false; worker.workCount = 0; EnterCriticalSection(&worker.queueMutex); std::queue<Functor*> emptyQueue; std::swap(worker.queue, emptyQueue); // Et on vide la queue (merci std::swap) LeaveCriticalSection(&worker.queueMutex); // On réveille le worker pour qu'il sorte de la boucle et termine le thread SetEvent(worker.wakeEvent); } // On attend que chaque thread se termine WaitForMultipleObjects(s_workerCount, &s_workerThreads[0], true, INFINITE); // Et on libère les ressources for (unsigned int i = 0; i < s_workerCount; ++i) { Worker& worker = s_workers[i]; CloseHandle(s_doneEvents[i]); CloseHandle(s_workerThreads[i]); CloseHandle(worker.wakeEvent); DeleteCriticalSection(&worker.queueMutex); } s_doneEvents.reset(); s_workers.reset(); s_workerThreads.reset(); s_workerCount = 0; } void TaskSchedulerImpl::WaitForTasks() { #ifdef NAZARA_CORE_SAFE if (s_workerCount == 0) { NazaraError("Task scheduler is not initialized"); return; } #endif WaitForMultipleObjects(s_workerCount, &s_doneEvents[0], true, INFINITE); } Functor* TaskSchedulerImpl::StealTask(std::size_t workerID) { bool shouldRetry; do { shouldRetry = false; for (std::size_t i = 0; i < s_workerCount; ++i) { // On ne vole pas la famille, ni soi-même. if (i == workerID) continue; Worker& worker = s_workers[i]; // Ce worker a-t-il encore des tâches dans sa file d'attente ? if (worker.workCount > 0) { Functor* task = nullptr; // Est-ce qu'il utilise la queue maintenant ? if (TryEnterCriticalSection(&worker.queueMutex)) { // Non, super ! Profitons-en pour essayer de lui voler un job if (!worker.queue.empty()) // On vérifie que la queue n'est pas vide (peut avoir changé avant le verrouillage) { // Et hop, on vole la tâche task = worker.queue.front(); worker.queue.pop(); worker.workCount = worker.queue.size(); } LeaveCriticalSection(&worker.queueMutex); } else shouldRetry = true; // Il est encore possible d'avoir un job // Avons-nous notre tâche ? if (task) return task; // Parfait, sortons de là ! } } } while (shouldRetry); // Bon à priori plus aucun worker n'a de tâche return nullptr; } unsigned int __stdcall TaskSchedulerImpl::WorkerProc(void* userdata) { unsigned int workerID = *static_cast<unsigned int*>(userdata); SetEvent(s_doneEvents[workerID]); Worker& worker = s_workers[workerID]; WaitForSingleObject(worker.wakeEvent, INFINITE); while (worker.running) { Functor* task = nullptr; if (worker.workCount > 0) // Permet d'éviter d'entrer inutilement dans une section critique { EnterCriticalSection(&worker.queueMutex); if (!worker.queue.empty()) // Nécessaire car le workCount peut être tombé à zéro juste avant l'entrée dans la section critique { task = worker.queue.front(); worker.queue.pop(); worker.workCount = worker.queue.size(); } LeaveCriticalSection(&worker.queueMutex); } // Que faire quand vous n'avez plus de travail ? if (!task) task = StealTask(workerID); // Voler le travail des autres ! if (task) { // On exécute la tâche avant de la supprimer task->Run(); delete task; } else { SetEvent(s_doneEvents[workerID]); WaitForSingleObject(worker.wakeEvent, INFINITE); } } // Au cas où un thread attendrait sur WaitForTasks() pendant qu'un autre appellerait Uninitialize() // Ça ne devrait pas arriver, mais comme ça ne coûte pas grand chose.. SetEvent(s_doneEvents[workerID]); return 0; } std::unique_ptr<HANDLE[]> TaskSchedulerImpl::s_doneEvents; // Doivent être contigus std::unique_ptr<TaskSchedulerImpl::Worker[]> TaskSchedulerImpl::s_workers; std::unique_ptr<HANDLE[]> TaskSchedulerImpl::s_workerThreads; // Doivent être contigus DWORD TaskSchedulerImpl::s_workerCount; } #include <Nazara/Core/AntiWindows.hpp>
{ "content_hash": "336d943532dd15b5079f610b9547337c", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 133, "avg_line_length": 29.259414225941423, "alnum_prop": 0.6796796796796797, "repo_name": "DigitalPulseSoftware/NazaraEngine", "id": "87742ba3033ab475100704655fec9674b0d91ba5", "size": "7457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Nazara/Core/Win32/TaskSchedulerImpl.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "7133540" }, { "name": "Lua", "bytes": "67543" }, { "name": "Objective-C++", "bytes": "456" } ], "symlink_target": "" }
package ssdp import ( "fmt" "log" "net/http" "net/url" "regexp" "strconv" "sync" "time" "gx/ipfs/QmQtBcHtRy9BxjawZjWJBn8aSKbqraBnQiVsc3wt9w9TTn/goupnp/httpu" ) const ( maxExpiryTimeSeconds = 24 * 60 * 60 ) var ( maxAgeRx = regexp.MustCompile("max-age=([0-9]+)") ) const ( EventAlive = EventType(iota) EventUpdate EventByeBye ) type EventType int8 func (et EventType) String() string { switch et { case EventAlive: return "EventAlive" case EventUpdate: return "EventUpdate" case EventByeBye: return "EventByeBye" default: return fmt.Sprintf("EventUnknown(%d)", int8(et)) } } type Update struct { // The USN of the service. USN string // What happened. EventType EventType // The entry, which is nil if the service was not known and // EventType==EventByeBye. The contents of this must not be modified as it is // shared with the registry and other listeners. Once created, the Registry // does not modify the Entry value - any updates are replaced with a new // Entry value. Entry *Entry } type Entry struct { // The address that the entry data was actually received from. RemoteAddr string // Unique Service Name. Identifies a unique instance of a device or service. USN string // Notfication Type. The type of device or service being announced. NT string // Server's self-identifying string. Server string Host string // Location of the UPnP root device description. Location url.URL // Despite BOOTID,CONFIGID being required fields, apparently they are not // always set by devices. Set to -1 if not present. BootID int32 ConfigID int32 SearchPort uint16 // When the last update was received for this entry identified by this USN. LastUpdate time.Time // When the last update's cached values are advised to expire. CacheExpiry time.Time } func newEntryFromRequest(r *http.Request) (*Entry, error) { now := time.Now() expiryDuration, err := parseCacheControlMaxAge(r.Header.Get("CACHE-CONTROL")) if err != nil { return nil, fmt.Errorf("ssdp: error parsing CACHE-CONTROL max age: %v", err) } loc, err := url.Parse(r.Header.Get("LOCATION")) if err != nil { return nil, fmt.Errorf("ssdp: error parsing entry Location URL: %v", err) } bootID, err := parseUpnpIntHeader(r.Header, "BOOTID.UPNP.ORG", -1) if err != nil { return nil, err } configID, err := parseUpnpIntHeader(r.Header, "CONFIGID.UPNP.ORG", -1) if err != nil { return nil, err } searchPort, err := parseUpnpIntHeader(r.Header, "SEARCHPORT.UPNP.ORG", ssdpSearchPort) if err != nil { return nil, err } if searchPort < 1 || searchPort > 65535 { return nil, fmt.Errorf("ssdp: search port %d is out of range", searchPort) } return &Entry{ RemoteAddr: r.RemoteAddr, USN: r.Header.Get("USN"), NT: r.Header.Get("NT"), Server: r.Header.Get("SERVER"), Host: r.Header.Get("HOST"), Location: *loc, BootID: bootID, ConfigID: configID, SearchPort: uint16(searchPort), LastUpdate: now, CacheExpiry: now.Add(expiryDuration), }, nil } func parseCacheControlMaxAge(cc string) (time.Duration, error) { matches := maxAgeRx.FindStringSubmatch(cc) if len(matches) != 2 { return 0, fmt.Errorf("did not find exactly one max-age in cache control header: %q", cc) } expirySeconds, err := strconv.ParseInt(matches[1], 10, 16) if err != nil { return 0, err } if expirySeconds < 1 || expirySeconds > maxExpiryTimeSeconds { return 0, fmt.Errorf("rejecting bad expiry time of %d seconds", expirySeconds) } return time.Duration(expirySeconds) * time.Second, nil } // parseUpnpIntHeader is intended to parse the // {BOOT,CONFIGID,SEARCHPORT}.UPNP.ORG header fields. It returns the def if // the head is empty or missing. func parseUpnpIntHeader(headers http.Header, headerName string, def int32) (int32, error) { s := headers.Get(headerName) if s == "" { return def, nil } v, err := strconv.ParseInt(s, 10, 32) if err != nil { return 0, fmt.Errorf("ssdp: could not parse header %s: %v", headerName, err) } return int32(v), nil } var _ httpu.Handler = new(Registry) // Registry maintains knowledge of discovered devices and services. // // NOTE: the interface for this is experimental and may change, or go away // entirely. type Registry struct { lock sync.Mutex byUSN map[string]*Entry listenersLock sync.RWMutex listeners map[chan<- Update]struct{} } func NewRegistry() *Registry { return &Registry{ byUSN: make(map[string]*Entry), listeners: make(map[chan<- Update]struct{}), } } // NewServerAndRegistry is a convenience function to create a registry, and an // httpu server to pass it messages. Call ListenAndServe on the server for // messages to be processed. func NewServerAndRegistry() (*httpu.Server, *Registry) { reg := NewRegistry() srv := &httpu.Server{ Addr: ssdpUDP4Addr, Multicast: true, Handler: reg, } return srv, reg } func (reg *Registry) AddListener(c chan<- Update) { reg.listenersLock.Lock() defer reg.listenersLock.Unlock() reg.listeners[c] = struct{}{} } func (reg *Registry) RemoveListener(c chan<- Update) { reg.listenersLock.Lock() defer reg.listenersLock.Unlock() delete(reg.listeners, c) } func (reg *Registry) sendUpdate(u Update) { reg.listenersLock.RLock() defer reg.listenersLock.RUnlock() for c := range reg.listeners { c <- u } } // GetService returns known service (or device) entries for the given service // URN. func (reg *Registry) GetService(serviceURN string) []*Entry { // Currently assumes that the map is small, so we do a linear search rather // than indexed to avoid maintaining two maps. var results []*Entry reg.lock.Lock() defer reg.lock.Unlock() for _, entry := range reg.byUSN { if entry.NT == serviceURN { results = append(results, entry) } } return results } // ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to // maintain the registry of devices and services. func (reg *Registry) ServeMessage(r *http.Request) { if r.Method != methodNotify { return } nts := r.Header.Get("nts") var err error switch nts { case ntsAlive: err = reg.handleNTSAlive(r) case ntsUpdate: err = reg.handleNTSUpdate(r) case ntsByebye: err = reg.handleNTSByebye(r) default: err = fmt.Errorf("unknown NTS value: %q", nts) } if err != nil { log.Printf("goupnp/ssdp: failed to handle %s message from %s: %v", nts, r.RemoteAddr, err) } } func (reg *Registry) handleNTSAlive(r *http.Request) error { entry, err := newEntryFromRequest(r) if err != nil { return err } reg.lock.Lock() reg.byUSN[entry.USN] = entry reg.lock.Unlock() reg.sendUpdate(Update{ USN: entry.USN, EventType: EventAlive, Entry: entry, }) return nil } func (reg *Registry) handleNTSUpdate(r *http.Request) error { entry, err := newEntryFromRequest(r) if err != nil { return err } nextBootID, err := parseUpnpIntHeader(r.Header, "NEXTBOOTID.UPNP.ORG", -1) if err != nil { return err } entry.BootID = nextBootID reg.lock.Lock() reg.byUSN[entry.USN] = entry reg.lock.Unlock() reg.sendUpdate(Update{ USN: entry.USN, EventType: EventUpdate, Entry: entry, }) return nil } func (reg *Registry) handleNTSByebye(r *http.Request) error { usn := r.Header.Get("USN") reg.lock.Lock() entry := reg.byUSN[usn] delete(reg.byUSN, usn) reg.lock.Unlock() reg.sendUpdate(Update{ USN: usn, EventType: EventByeBye, Entry: entry, }) return nil }
{ "content_hash": "7ed0fb6bbe5577df6585185772ff9043", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 92, "avg_line_length": 23.92628205128205, "alnum_prop": 0.6951105157401206, "repo_name": "cpacia/openbazaar-go", "id": "fd240c9df17d534c4ecd5c6b881fff0e7e0c2638", "size": "7465", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/gx/ipfs/QmQtBcHtRy9BxjawZjWJBn8aSKbqraBnQiVsc3wt9w9TTn/goupnp/ssdp/registry.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "726889" }, { "name": "Makefile", "bytes": "1386" }, { "name": "Protocol Buffer", "bytes": "28710" }, { "name": "Python", "bytes": "178340" }, { "name": "Shell", "bytes": "3196" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "99cc6c6d529219450bed9a0f1650a285", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "cb434f6622939f25dfce01032c21954ec6ee5c00", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Anacardiaceae/Mauria/Mauria biringo/Mauria biringo ruizii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package city.tests.roles; import junit.framework.TestCase; public class RestaurantTimmsCookTest extends TestCase { public void setUp() throws Exception { super.setUp(); } public void testNormativeScenario() throws InterruptedException { System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); assertTrue("", true); } }
{ "content_hash": "c5dd8a01f943935ac7397bba4d9ff415", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 80, "avg_line_length": 21.235294117647058, "alnum_prop": 0.7506925207756233, "repo_name": "zhangtdavid/SimCity", "id": "ed5600c3b2e2da97722d9ec90542d757425eba86", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/city/tests/roles/RestaurantTimmsCookTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1685675" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>City-R-US API</title> <link href="{{ asset('swagger/css/typography.css') }}" media='screen' rel='stylesheet' type='text/css'/> <link href="{{ asset('swagger/css/reset.css') }}" media='screen' rel='stylesheet' type='text/css'/> <link href="{{ asset('swagger/css/screen.css') }}" media='screen' rel='stylesheet' type='text/css'/> <link href="{{ asset('swagger/css/reset.css') }}" media='print' rel='stylesheet' type='text/css'/> <link href="{{ asset('swagger/css/print.css') }}" media='print' rel='stylesheet' type='text/css'/> <script src="{{ asset('swagger/lib/jquery-1.8.0.min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/jquery.slideto.min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/jquery.wiggle.min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/jquery.ba-bbq.min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/handlebars-2.0.0.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/underscore-min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/backbone-min.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/swagger-ui.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/highlight.7.3.pack.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/marked.js') }}" type='text/javascript'></script> <script src="{{ asset('swagger/lib/swagger-oauth.js') }}" type='text/javascript'></script> <!-- Some basic translations --> <!-- <script src='lang/translator.js' type='text/javascript'></script> --> <!-- <script src='lang/ru.js' type='text/javascript'></script> --> <!-- <script src='lang/en.js' type='text/javascript'></script> --> <script type="text/javascript"> $(function () { var url = window.location.search.match(/url=([^&]+)/); if (url && url.length > 1) { url = decodeURIComponent(url[1]); } else { url = "{{ asset('/api/swagger.json') }}"; } // Pre load translate... if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } window.swaggerUi = new SwaggerUi({ url: url, dom_id: "swagger-ui-container", supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'], onComplete: function (swaggerApi, swaggerUi) { if (typeof initOAuth == "function") { initOAuth({ clientId: "your-client-id", clientSecret: "your-client-secret", realm: "your-realms", appName: "your-app-name", scopeSeparator: "," }); } if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } $('pre code').each(function (i, e) { hljs.highlightBlock(e) }); //addApiKeyAuthorization(); }, onFailure: function (data) { log("Unable to Load SwaggerUI"); }, docExpansion: "none", apisSorter: "alpha", showRequestHeaders: false }); /* function addApiKeyAuthorization() { var key = encodeURIComponent($('#input_apiKey')[0].value); if (key && key.trim() != "") { var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query"); window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth); log("added key " + key); } } $('#input_apiKey').change(addApiKeyAuthorization); */ // if you have an apiKey you would like to pre-populate on the page for demonstration purposes... /* var apiKey = "myApiKeyXXXX123456789"; $('#input_apiKey').val(apiKey); */ window.swaggerUi.load(); function log() { if ('console' in window) { console.log.apply(console, arguments); } } }); </script> </head> <body class="swagger-section"> <div id='header'> <div class="swagger-ui-wrap"> <img src="{{asset('img/logo.png')}}"> <!-- <a id="logo" href="http://swagger.io">swagger</a> <form id='api_selector'> <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div> <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div> <div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div> </form> --> </div> </div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div> <div id="swagger-ui-container" class="swagger-ui-wrap"></div> </body> </html>
{ "content_hash": "49ee9fdede1905ba400a35182c0354f8", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 129, "avg_line_length": 45.03333333333333, "alnum_prop": 0.5227609178386381, "repo_name": "scify/city-r-us-service", "id": "bc77776fb0a4143054dbe993247782e157f13d53", "size": "5404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/home.blade.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "444" }, { "name": "CSS", "bytes": "226103" }, { "name": "HTML", "bytes": "5601" }, { "name": "JavaScript", "bytes": "2461472" }, { "name": "PHP", "bytes": "222845" } ], "symlink_target": "" }
package org.elsys.postfix; public class Multiply extends BinaryOperation { public Multiply() { super("*"); } @Override public double calculate(double firstOperand, double secondOperand) { return firstOperand * secondOperand; } }
{ "content_hash": "9aca820263bd6cb2420ae2fc19954f79", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 69, "avg_line_length": 20.083333333333332, "alnum_prop": 0.7427385892116183, "repo_name": "arnaudoff/elsys", "id": "cd01d5a70289c7748554b386496ccfcd376ca047", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2015-2016/object-oriented-programming/second_term/PostfixCalculator/src/org/elsys/postfix/Multiply.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "60114" }, { "name": "C++", "bytes": "22055" }, { "name": "Java", "bytes": "12412" }, { "name": "M", "bytes": "169" }, { "name": "Makefile", "bytes": "158" }, { "name": "Matlab", "bytes": "5095" } ], "symlink_target": "" }
require "decent_exposure" require "haml-rails" require "jquery-rails" require "simple_form" require "spreadsheet_on_rails" require 'aasm' require "surveillance/engine" module Surveillance extend ActiveSupport::Autoload autoload :Field, "surveillance/field" autoload :PartialsCollection, "surveillance/partials_collection" autoload :SettingsCollection, "surveillance/settings_collection" autoload :Setting, "surveillance/setting" autoload :Validators, "surveillance/validators" # Defines an autorization method to be called before actions in admin # controllers to authenticate admin users # mattr_accessor :admin_authorization_method @@admin_authorization_method = nil mattr_accessor :admin_base_controller @@admin_base_controller = 'Surveillance::ApplicationController' mattr_accessor :views_layout @@views_layout = nil mattr_accessor :partials @@partials = Surveillance::PartialsCollection.new mattr_accessor :attempt_already_registered_callback @@attempt_already_registered_callback = nil mattr_accessor :surveys_root_path @@surveys_root_path = nil class << self def table_name_prefix 'surveillance_' end def options_for ary, key ary.map do |item| str = item.to_s [I18n.t("surveillance.#{ key }.#{ str }"), str] end end def config &block yield self end def unique_token (Time.now.to_f * (100 ** 10)).to_i.to_s(36) + (rand * 10 ** 10).to_i.to_s(36) end end end
{ "content_hash": "489d6cba4d1fa5cec437b8b60cd7f064", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 71, "avg_line_length": 24.721311475409838, "alnum_prop": 0.7049071618037135, "repo_name": "glyph-fr/surveillance", "id": "5b53453f835d82e6dd07701d1503ce6b0146ae9b", "size": "1508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/surveillance.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1200" }, { "name": "CoffeeScript", "bytes": "13729" }, { "name": "HTML", "bytes": "36483" }, { "name": "JavaScript", "bytes": "1638" }, { "name": "Ruby", "bytes": "79987" } ], "symlink_target": "" }
import os import sys import getopt import traceback import pprint import time import subprocess import shlex import re import operator calls = dict() # dict of dicts: {'name', 'bcet', 'wcet', 'lastcall', 'running'} list_calls = False pretty = False coverage = False covdata = {} full_stats = False filter_func = None symbol_map = None current_cycle = 0 start_cycle = None stack = list() # tuple (function, call time) wlist = dict() # decimal address => { 'BBname', 'is_begin'} wstat = dict() # BBname => {'count': how_often_visited , 'laststart': when_visited_last 'running': is_still_in_block, 'bcet', 'wcet','sum','et' } delayed_addr = None def register_broken(fun): """ Calling this marks the timing of the function unknown, due to some unexpected call/ret """ try: calls[fun]['valid'] = False except: # keyerror pass def get_stack(): """return current function stack as string""" global stack try: # try to tind find main i0 = (e for e, t in enumerate(stack) if t[0] == "main").next() except StopIteration: i0 = 0 return "=>".join([f[0] for f in stack[i0:]]) def register_call(addr, cycle): """ A function was called at given cycle. This is called *after* the call finished. fun is the address of the first insn after the call, i.e., the callee. """ fun = get_symbol(addr) if fun in calls: calls[fun]['lastcall'] = cycle calls[fun]['count'] = calls[fun]['count'] + 1 else: # newly insert calls[fun] = {'bcet': sys.maxint, 'wcet': 0, 'et': [], 'lastcall': cycle, 'count': 1, 'valid': True, 'fun': fun, 'total': 0} global stack stack.append((fun, cycle)) if list_calls: print "{} called @{}. stack={}".format(fun, cycle, get_stack()) def register_ret(next_addr, cycle): """ A function returned at the given cycle. This is called *after* the return finished. next_addr is the address of the first insn after the return, i.e., the returnee. """ global list_calls, full_stats, stack fun, callcycle = stack.pop() if fun not in calls: print "WARN @" + str(cycle) + ": RET of " + fun + ", but have seen no call" register_broken(fun) return et = cycle - callcycle if list_calls: print "{} returns at @{}, time={}. stack={}".format(fun, cycle, et, get_stack()) if et > calls[fun]['wcet']: calls[fun]['wcet'] = et if et < calls[fun]['bcet']: calls[fun]['bcet'] = et calls[fun]['total'] += et if full_stats: calls[fun]['et'].append(et) calls[fun]['running'] = False def register_visit(titl, is_begin, cycle): """ register a watchpoint that was visited """ global wstat current = wstat[titl] if is_begin: # BB starts if current["is_running"]: # print "WARN: watchpoint " + titl + " @" + str(cycle) +\ # " starts before it ended. Last visit=" + str(current["last_begin"]) pass # that is a normal case, when no end addr is given current["is_running"] = True current["last_begin"] = cycle current["count"] += 1 else: # BB ends if not current["is_running"]: print "WARN: watchpoint " + titl + " @" + str(cycle) + \ " ends before it started. Last visit=" + str(current["last_begin"]) else: duration = cycle - current["last_begin"] current["sum"] += duration current["is_running"] = False if current["bcet"] > duration: current["bcet"] = duration if current["wcet"] < duration: current["wcet"] = duration # finally...update wstat[titl] = current pending_return = False pending_call = False next_show = 0 last_shown_cycle = 0 def consume_line(line, show_progress=True): """ parses a line of simulator's trace file, and keeps track of function calls and times """ global wlist, delayed_addr, next_show, last_shown_cycle, coverage, current_cycle, start_cycle # parse line # create dict of function names and min/max execution times on the fly # <elfname> <PC>: <cycle>: <function>(+<offset>)? <asm> # offset is number of instructions, whereas one instruction is assumed 2Bytes # (though some are 4 bytes...) # XXX: function *is not necessarily* the current function! Sometimes another label # is used to compute offset. Therefore we need a symbol map parts = line.split(None) # split at any whitespace if (len(parts) < 5): return # unknown format OR last line try: hexaddr = parts[1].rstrip(":") decaddr = int(hexaddr, 16) current_cycle = int(parts[2].strip()[0:-1]) if start_cycle is None: start_cycle = current_cycle # fun = parts[3].strip() # that is unreliable. Label/Offset sometimes is based on other func asm = parts[4].strip() if len(parts) > 5: op = parts[5].strip() # print line except: print "Skipping trace line: {}".format(line) return now = time.time() if now > next_show: cps = current_cycle - last_shown_cycle last_shown_cycle = current_cycle print "Cycles: {:,} ({:,} per second), stack={}".format(current_cycle, cps, get_stack()) next_show = now + 1.0 if asm == "CPU-waitstate": return # register end of watchpoint if delayed_addr: register_visit(delayed_addr, False, current_cycle) delayed_addr = None # watchlist if decaddr in wlist: if wlist[decaddr]["is_begin"]: register_visit(wlist[decaddr]["name"], True, current_cycle) if wlist[decaddr]["is_end"]: # here we do a trick: we want to include the time of the jump to the next BB... # so we have to register the end in the NEXT non-wait-cycle # we could do the following, if the jump shall NOT count: # register_visit(wlist[decaddr]["name"], False, current_cycle) delayed_addr = wlist[decaddr]["name"] global pending_return, pending_call # this is only reached by no-wait-states instructions if pending_call: register_call(decaddr, current_cycle) # time to do the call is attributed to the caller pending_call = False elif pending_return: register_ret(decaddr, current_cycle) # time for the return is attributed to the callee pending_return = False pending_return = asm in ("RET", "RETI") pending_call = asm in ("ICALL", "CALL", "RCALL") if pending_call: # we must ignore call to next instruction, since this is actually a trick to find # the addr of the next instruction in the code, and the stack return address is # immediately popped try: if int(op, 16) == decaddr + 2: # print "Ignoring (r)call .+0 @{}".format(current_cycle) pending_call = False except ValueError: pass # could be "RCALL Z" def load_symbols(elf): """query nm for symbol addresses""" assert os.path.exists(elf), "ELF file not found (needed for symbol map)" # -- global symbol_map symbol_map = {} re_sym = re.compile(r"([0-9a-fA-F]+)[\s\t]+(.)[\s\t+](\w+)") proc = subprocess.Popen(['avr-nm', '-C', elf], stdout=subprocess.PIPE, bufsize=-1) for line in iter(proc.stdout.readline, ''): match = re_sym.match(line.rstrip()) if match: decaddr = int(match.group(1), 16) typ = match.group(2) name = match.group(3) if typ.lower() in ('t', 'u', 'v', 'w'): if decaddr in symbol_map: print "WARN: Symbol at {:x} already has a name: {}. Updating to {}.".\ format(decaddr, symbol_map[decaddr], name) # the latest is better. symbol_map[decaddr] = name print "Loaded {} symbols.".format(len(symbol_map)) def get_symbol(addr): """return name of symbol at address, or return address if not known""" global symbol_map return symbol_map.get(addr, hex(addr)) def total_cycles(): """total number of seen cycles""" global current_cycle, start_cycle return current_cycle - start_cycle def display_coverage(result): global symbol_map, pretty cov = [] for _, func in symbol_map.iteritems(): if func in result: cycles = result[func]['total'] else: cycles = 0 perc = (100.* cycles) / total_cycles() cov.append((func, cycles, perc)) sorted_by_cycles = sorted(cov, key=lambda x: x[1], reverse=True) print "Coverage by cycles:" if pretty: for entry in sorted_by_cycles: print "{:<35} {:>10,} {:>04.2f}%".format(entry[0], entry[1], entry[2]) else: print str(sorted_by_cycles) def do_work(tracefile, sim_args, elf): """either run simulation now, or inspect trace post-mortem""" global wstat, filter_func, pretty, coverage # -- load_symbols(elf) if sim_args: print "Running Simulator live..." if tracefile: print "Tracefile ignored" ret = run_simul(sim_args, elf) else: print "Parsing trace post-mortem..." ret = parse_trace(tracefile) if 0 == ret: if filter_func: if filter_func in calls: if pretty: pprint.pprint(calls[filter_func]) else: print calls[filter_func] else: print "ERROR: function \"{}\" not found in trace".format(filter_func) print "ERROR: only these available: {}".format(calls.keys()) return 1 else: if pretty: pprint.pprint(calls) else: print str(calls) if len(wlist) > 0: pprint.pprint(wstat) if coverage: display_coverage(calls) print "Total cycles: {}".format(total_cycles()) return ret def run_simul(sim_args, elf): """run simulation and simultaneously parse the trace""" def del_arg(flag): """remove given flag and arg, if present""" for c in xrange(len(cmd_split)): if cmd_split[c].startswith(flag): if len(cmd_split[c]) == 2: del cmd_split[c:c + 2] # flag and value are separate else: del cmd_split[c] # flag and value are together print "Removed cmdline flag ({}) for simulavr".format(flag) return cmd = 'simulavr ' + sim_args cmd_split = shlex.split(cmd) # override flags that the user may have given del_arg('-t') del_arg('-f') cmd_split.extend(['-t', 'stdout']) # set trace to stdout cmd_split.extend(['-f', elf]) # set same ELF that we are using print "Running Simulator: {}".format(' '.join(cmd_split)) process = subprocess.Popen(cmd_split, bufsize=-1, stdout=subprocess.PIPE) while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: consume_line(output) # rc = process.poll() #return code return 0 def parse_trace(tfile): """ parse trace post-mortem """ global wstat, filter_func try: with open(tfile, 'rb') as f: # read line by line for line in f: consume_line(line) except: print "File " + tfile + " could not be processed", sys.exc_info()[0] print(traceback.format_exc()) return 1 return 0 def get_watchpoints(wfile): """ Read a file describing watchpoints, and put them into dictionary 'wlist' """ global wlist global wstat if not wfile: return try: with open(wfile, 'rb') as f: for line in f: if line.startswith("#"): continue parts = line.split(None) # split at any whitespace hexaddr_begin = parts[0].strip() decaddr_begin = int(hexaddr_begin, 16) # hex string representing addr of watchpoint if len(parts) > 1: titl = parts[1].strip() # readable name else: titl = '' # add watchpoint for begin of BB is_single_step = True if len(parts) > 2: # add another watchpoint for end of BB, if we have an end address hexaddr_end = parts[2].strip() decaddr_end = int(hexaddr_end, 16) # hex string representing addr of watchpoint if decaddr_end != decaddr_begin: is_single_step = False wlist[decaddr_end] = {'name': titl, 'is_begin': False, 'is_end': True} wlist[decaddr_begin] = {'name': titl, 'is_begin': True, 'is_end': is_single_step} # prepare wstats; this holds the visiting statistics in the end wstat[titl] = {"addr": hexaddr_begin, "count": 0, "last_begin": -1, 'bcet': sys.maxint, 'wcet': 0, 'sum': 0, 'is_running': False} except: print "File " + wfile + " cound not be fully processed", sys.exc_info()[0] # return readable_list = [" " + hex(k) + " = " + v["name"] for k, v in wlist.iteritems()] print 'Watchpoints (' + str(len(readable_list)) + "):" print "\n".join(readable_list) return def print_usage(): print __file__ + ' [OPTION] -e <elf> -t <trace>' print '' print 'OPTIONS:' print ' -o, --only-function=<name>' print ' only show result for specific function' print ' -c, --calls' print ' show calls' print ' -w, --watchlist=<file>' print ' provide statistics for particular addresses' print ' -f, --fullstats' print ' keep execution time of every invocation, not just min/max' print ' -s, --simulate=<args>' print ' run simulavr with extra arguments and parse simultaneously' print ' -p, --pretty' print ' pretty-print the results with indentation' print ' -g, --coverage' print ' show number of cycles spend in each function (includes children)' def main(argv): global list_calls, full_stats, filter_func, pretty, coverage sim_args = None tracefile = "trace" watchfile = None elf = None try: opts, args = getopt.getopt(argv, "ht:cw:fo:s:e:pg", ["trace=", "calls", "watchlist=", "fullstats", "only-function=", "simulate=", "elf=", "pretty", "coverage"]) except getopt.GetoptError: print_usage() sys.exit(2) for opt, arg in opts: if opt == '-h': print_usage() sys.exit() elif opt in ("-o", "--only-function"): filter_func = arg elif opt in ("-f", "--fullstats"): full_stats = True elif opt in ("-e", "--elf"): elf = arg elif opt in ("-g", "--coverage"): coverage = True elif opt in ("-c", "--calls"): list_calls = True elif opt in ("-p", "--pretty"): pretty = True print "pretty-print on" elif opt in ("-s", "--simulate=<simulavr-args>"): sim_args = arg if (arg.startswith('"') and arg.endswith('"')) or\ (arg.startswith("'") and arg.endswith("'")): sim_args = arg[1:-1] else: sim_args = arg elif opt in ("-t", "--trace"): tracefile = arg elif opt in ("-w", "--watchlist"): watchfile = arg # get list of instructions to be watched (when and how often do they execute) get_watchpoints(watchfile) t0 = time.time() ret = do_work(tracefile, sim_args, elf) t1 = time.time() print "Total time: {:.1f}s".format(t1 - t0) exit(ret) if __name__ == "__main__": main(sys.argv[1:])
{ "content_hash": "014d486065b7d9e729a720433c9a8ef0", "timestamp": "", "source": "github", "line_count": 476, "max_line_length": 147, "avg_line_length": 34.220588235294116, "alnum_prop": 0.5555282706120694, "repo_name": "TRDDC-TUM/wcet-benchmarks", "id": "0b7474e2fd7246a0055986f0c3037c6c7ff7d3be", "size": "16597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/simulavr2times.py", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "9323361" }, { "name": "C", "bytes": "1563980" }, { "name": "C++", "bytes": "26102" }, { "name": "Makefile", "bytes": "170775" }, { "name": "Python", "bytes": "231587" }, { "name": "Shell", "bytes": "115791" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_72-internal) on Mon Mar 14 13:22:19 GMT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.taverna.tavlang.tools.convert.Scufl2Convert (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)</title> <meta name="date" content="2016-03-14"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.taverna.tavlang.tools.convert.Scufl2Convert (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/taverna/tavlang/tools/convert/Scufl2Convert.html" title="class in org.apache.taverna.tavlang.tools.convert">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/taverna/tavlang/tools/convert/class-use/Scufl2Convert.html" target="_top">Frames</a></li> <li><a href="Scufl2Convert.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.taverna.tavlang.tools.convert.Scufl2Convert" class="title">Uses of Class<br>org.apache.taverna.tavlang.tools.convert.Scufl2Convert</h2> </div> <div class="classUseContainer">No usage of org.apache.taverna.tavlang.tools.convert.Scufl2Convert</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/taverna/tavlang/tools/convert/Scufl2Convert.html" title="class in org.apache.taverna.tavlang.tools.convert">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/taverna/tavlang/tools/convert/class-use/Scufl2Convert.html" target="_top">Frames</a></li> <li><a href="Scufl2Convert.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015&#x2013;2016 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "db90dd8ba12e335adbca55177f35b272", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 179, "avg_line_length": 39.992063492063494, "alnum_prop": 0.6189720182575907, "repo_name": "apache/incubator-taverna-site", "id": "fd5213eb598e26947b19222bd4cdaa6878df314d", "size": "5039", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "content/javadoc/taverna-language/org/apache/taverna/tavlang/tools/convert/class-use/Scufl2Convert.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10003" }, { "name": "Clojure", "bytes": "49413" }, { "name": "Dockerfile", "bytes": "1398" }, { "name": "HTML", "bytes": "72209" }, { "name": "Perl", "bytes": "2822" }, { "name": "Python", "bytes": "31455" }, { "name": "Shell", "bytes": "374" } ], "symlink_target": "" }
FROM balenalib/imx8mm-var-dart-ubuntu:cosmic-build ENV GO_VERSION 1.14.13 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "445b719ebf46d8825360dabad65226db154ca8053de60609bc20f80a17452cbb go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.14.13 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "24fe9e3a314a5337bbb7e516199c1230", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 675, "avg_line_length": 64.03225806451613, "alnum_prop": 0.726448362720403, "repo_name": "nghiant2710/base-images", "id": "471eea8755b565735852a67e2eff407f3d98bb58", "size": "2006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/imx8mm-var-dart/ubuntu/cosmic/1.14.13/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title>Angular Cron Gen</title> <!-- angular --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <!-- lib --> <script src="../build/cron-gen.min.js"></script> <!--<script src="../build/cron-gen.module.js"></script>--> <!--<script src="../build/templates.js"></script>--> <link href="../build/cron-gen.min.css" rel="stylesheet"/> <!-- example app --> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="app.js"></script> <link href="app.css" rel="stylesheet"/> <link href="http://fonts.googleapis.com/css?family=Oxygen:300,400,700" rel="stylesheet" type="text/css"> </head> <body ng-app="ExampleApp" ng-controller="ExampleCtrl"> <div class="container"> <div class="row"> <div class="jumbotron"> <h1>Cron Generator</h1> <p>A cron expression generator for AngularJS.</p> <p> <a href="https://github.com/vincentjames501/angular-cron-gen" class="btn btn-primary btn-lg"> <i class="glyphicon glyphicon-download"></i>&nbsp;&nbsp;Download </a> <a href="https://github.com/vincentjames501/angular-cron-gen" class="btn btn-default btn-lg"> <i class="glyphicon glyphicon-random"></i>&nbsp;&nbsp;Fork on GitHub </a> </p> </div> </div> <div class="row"> <div class="panel"> <div class="panel-body"> <div class="row container"> <div class="col-xs-12"> <h3>Demo</h3> </div> </div> <hr/> <div class="row container"> <div class="col-xs-12"> <form name="cronForm"> <cron-gen ng-model="cronExpression" ng-disabled="isCronDisabled" options="cronOptions" name="cron"> </cron-gen> </form> </div> </div> <hr/> <div class="row container"> <div class="col-xs-12"> Generated Cron Expression: <span class="text-success"><b>{{cronExpression}}</b></span> </div> <div class="col-xs-12"> Is Valid: <span class="text-success" ng-show="cronForm.cron.$valid"><b>True</b></span> <span class="text-danger" ng-show="cronForm.cron.$invalid"><b>False</b></span> </div> </div> </div> </div> </div> <div class="row"> <div class="panel"> <div class="panel-body"> <div class="row container"> <div class="col-xs-12"> <h3>Usage</h3> </div> </div> <hr/> <div class="row container"> <div class="col-xs-12"> <pre>&lt;cron-gen ng-model="cronExpression" ng-disabled="isCronDisabled" template-url="your optional, custom template (Defaults to a bootstrap 3 template)" cron-format="quartz (Currently only compatible with 'quartz' and defaults to 'quartz')" options="cronOptions"&gt; &lt;/cron-gen&gt;</pre> <pre>angular.module('ExampleApp', ['angular-cron-gen']) .controller('ExampleCtrl', ['$scope', function ($scope) { $scope.cronExpression = '0 8 9 9 1/8 ? *'; $scope.cronOptions = { hideAdvancedTab: false }; $scope.isCronDisabled = false; }]);</pre> </div> </div> <div class="row container"> <div class="col-xs-12"> <h3>Options</h3> </div> </div> <hr/> <div class="row container"> <div class="col-xs-12"> <table class="table table-striped table-bordered"> <thead> <tr> <th>Options</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td>formInputClass</td> <td>The input class override</td> <td>String</td> <td>"form-control cron-gen-input"</td> </tr> <tr> <td>formSelectClass</td> <td>The select class override</td> <td>String</td> <td>"form-control cron-gen-select"</td> </tr> <tr> <td>formRadioClass</td> <td>The radio class override</td> <td>String</td> <td>"cron-gen-radio"</td> </tr> <tr> <td>formCheckboxClass</td> <td>The checkbox class override</td> <td>String</td> <td>"cron-gen-checkbox"</td> </tr> <tr> <td>hideMinutesTab</td> <td>Whether the minutes tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideHourlyTab</td> <td>Whether the hourly tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideDailyTab</td> <td>Whether the daily tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideWeeklyTab</td> <td>Whether the weekly tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideMonthlyTab</td> <td>Whether the monthly tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideYearlyTab</td> <td>Whether the yearly tab should be hidden</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideAdvancedTab</td> <td>Whether the advanced tab should be hidden</td> <td>boolean</td> <td>true</td> </tr> <tr> <td>use24HourTime</td> <td>Whether to show AM/PM on the time selectors</td> <td>boolean</td> <td>false</td> </tr> <tr> <td>hideSeconds</td> <td>Whether to show/hide the seconds time picker</td> <td>boolean</td> <td>false</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </body> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"> </script> </html>
{ "content_hash": "89b5edd2ab9f90fac5405f39c7182fb4", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 115, "avg_line_length": 35.244239631336406, "alnum_prop": 0.44939853556485354, "repo_name": "vincentjames501/angular-cron-gen", "id": "a34c103236089e336626e2161ec7a0b4494ef255", "size": "7648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2564" }, { "name": "HTML", "bytes": "41734" }, { "name": "JavaScript", "bytes": "52482" } ], "symlink_target": "" }
package mll.beans; import java.io.Serializable; public class Artist implements Serializable { private static final long serialVersionUID = -152269388788828458L; private Integer id; private Integer songId; private String name; private String skills; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSongId() { return songId; } public void setSongId(Integer songId) { this.songId = songId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSkills() { return skills; } public void setSkills(String skills) { this.skills = skills; } }
{ "content_hash": "1dd5c4978b82699ccbacf2fa6f5eb762", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 67, "avg_line_length": 18.263157894736842, "alnum_prop": 0.7132564841498559, "repo_name": "akhil0/MLL", "id": "0d525e9fa26bb701ccdba95478e89039deeebc79", "size": "694", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/mll/beans/Artist.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13461" }, { "name": "HTML", "bytes": "181664" }, { "name": "Java", "bytes": "267714" }, { "name": "JavaScript", "bytes": "274735" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>rockymusic</artifactId> <groupId>com.rockhoppertech</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>rockymusic-fx</artifactId> <name>Rocky Music FX</name> <packaging>jar</packaging> <description>Some JavaFX apps using Rockhopper Music</description> <organization> <!-- Used as the 'Vendor' for JNLP generation --> <name>Rockhopper Technologies</name> </organization> <properties> <!-- so you can specify which main to run from the cmd line: -DappClassname=whatever --> <!-- In eclipse, add a parameter in the run configuration --> <appClassname>com.rockhoppertech.music.fx.MainApp</appClassname> </properties> <dependencies> <dependency> <groupId>com.rockhoppertech</groupId> <artifactId>rockymusic-core</artifactId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <artifactId>jcl-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.aquafx-project</groupId> <artifactId>aquafx</artifactId> <version>0.1</version> </dependency> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.4</version> </dependency> </dependencies> <build> <finalName>rockymusic-fx</finalName> <plugins> <!-- goal jfx:run --> <plugin> <groupId>com.zenjava</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>2.0</version> <configuration> <mainClass>${appClassname}</mainClass> <!-- only required if signing the jar file --> <keyStoreAlias>example-user</keyStoreAlias> <keyStorePassword>example-password</keyStorePassword> <allPermissions>true</allPermissions> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>github-site-docs</id> <build> <plugins> <plugin> <groupId>com.github.github</groupId> <artifactId>site-maven-plugin</artifactId> <version>0.9</version> <configuration> <message>Builiding ${project.artifactId}</message> <merge>true</merge> <path>rockymusic-fx</path> <repositoryOwner>${repositoryOwner}</repositoryOwner> <repositoryName>${repositoryName}</repositoryName> </configuration> <executions> <execution> <goals> <goal>site</goal> </goals> <phase>site</phase> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>
{ "content_hash": "459750d7bbce146f942bc2d4fc3bf2d4", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 104, "avg_line_length": 26.46153846153846, "alnum_prop": 0.6411498708010336, "repo_name": "genedelisa/rockymusic", "id": "458a9e5b348042c3a92eea3c1502df7b28c63a9c", "size": "3096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rockymusic-fx/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7488" }, { "name": "Java", "bytes": "2900732" } ], "symlink_target": "" }
<?php namespace Codeception\Subscriber; use Codeception\Event\FailEvent; use Codeception\Event\PrintResultEvent; use Codeception\Event\StepEvent; use Codeception\Event\SuiteEvent; use Codeception\Event\TestEvent; use Codeception\Events; use Codeception\Lib\Console\Message; use Codeception\Lib\Console\MessageFactory; use Codeception\Lib\Console\Output; use Codeception\Lib\Notification; use Codeception\Step; use Codeception\Step\Comment; use Codeception\Suite; use Codeception\Test\Descriptor; use Codeception\Test\Interfaces\ScenarioDriven; use Codeception\Util\Debug; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class Console implements EventSubscriberInterface { use Shared\StaticEvents; /** * @var string[] */ public static $events = [ Events::SUITE_BEFORE => 'beforeSuite', Events::SUITE_AFTER => 'afterSuite', Events::TEST_START => 'startTest', Events::TEST_END => 'endTest', Events::STEP_BEFORE => 'beforeStep', Events::STEP_AFTER => 'afterStep', Events::TEST_SUCCESS => 'testSuccess', Events::TEST_FAIL => 'testFail', Events::TEST_ERROR => 'testError', Events::TEST_INCOMPLETE => 'testIncomplete', Events::TEST_SKIPPED => 'testSkipped', Events::TEST_FAIL_PRINT => 'printFail', Events::RESULT_PRINT_AFTER => 'afterResult', ]; /** * @var Step */ protected $metaStep; /** * @var Message */ protected $message = null; protected $steps = true; protected $debug = false; protected $ansi = true; protected $silent = false; protected $lastTestFailed = false; protected $printedTest = null; protected $rawStackTrace = false; protected $traceLength = 5; protected $width; /** * @var OutputInterface */ protected $output; protected $fails = []; protected $reports = []; protected $namespace = ''; protected $chars = ['success' => '+', 'fail' => 'x', 'of' => ':']; protected $options = [ 'debug' => false, 'ansi' => false, 'steps' => true, 'verbosity' => 0, 'xml' => null, 'html' => null, 'tap' => null, 'json' => null, ]; /** * @var MessageFactory */ protected $messageFactory; public function __construct($options) { $this->prepareOptions($options); $this->output = new Output($options); $this->messageFactory = new MessageFactory($this->output); if ($this->debug) { Debug::setOutput($this->output); } $this->detectWidth(); if ($this->options['ansi'] && !$this->isWin()) { $this->chars['success'] = '✔'; $this->chars['fail'] = '✖'; } foreach (['html', 'xml', 'tap', 'json'] as $report) { if (!$this->options[$report]) { continue; } $path = $this->absolutePath($this->options[$report]); $this->reports[] = sprintf( "- <bold>%s</bold> report generated in <comment>file://%s</comment>", strtoupper($report), $path ); } } // triggered for scenario based tests: cept, cest public function beforeSuite(SuiteEvent $e) { $this->namespace = ""; $settings = $e->getSettings(); if (isset($settings['namespace'])) { $this->namespace = $settings['namespace']; } $this->message("%s Tests (%d) ") ->with(ucfirst($e->getSuite()->getName()), $e->getSuite()->count()) ->style('bold') ->width($this->width, '-') ->prepend("\n") ->writeln(); if ($e->getSuite() instanceof Suite) { $message = $this->message( implode( ', ', array_map( function ($module) { return $module->_getName(); }, $e->getSuite()->getModules() ) ) ); $message->style('info') ->prepend('Modules: ') ->writeln(OutputInterface::VERBOSITY_VERBOSE); } $this->message('')->width($this->width, '-')->writeln(OutputInterface::VERBOSITY_VERBOSE); } // triggered for all tests public function startTest(TestEvent $e) { $this->fails = []; $test = $e->getTest(); $this->printedTest = $test; $this->message = null; if (!$this->output->isInteractive() and !$this->isDetailed($test)) { return; } $this->writeCurrentTest($test); if ($this->isDetailed($test)) { $this->output->writeln(''); $this->message(Descriptor::getTestSignature($test)) ->style('info') ->prepend('Signature: ') ->writeln(); $this->message(codecept_relative_path(Descriptor::getTestFullName($test))) ->style('info') ->prepend('Test: ') ->writeln(); if ($this->steps) { $this->message('Scenario --')->style('comment')->writeln(); $this->output->waitForDebugOutput = false; } } } public function afterStep(StepEvent $e) { $step = $e->getStep(); if ($step->hasFailed() and $step instanceof Step\ConditionalAssertion) { $this->fails[] = $step; } } /** * @param PrintResultEvent $event */ public function afterResult(PrintResultEvent $event) { $result = $event->getResult(); if ($result->skippedCount() + $result->notImplementedCount() > 0 and $this->options['verbosity'] < OutputInterface::VERBOSITY_VERBOSE) { $this->output->writeln("run with `-v` to get more info about skipped or incomplete tests"); } foreach ($this->reports as $message) { $this->output->writeln($message); } } private function absolutePath($path) { if ((strpos($path, '/') === 0) or (strpos($path, ':') === 1)) { // absolute path return $path; } return codecept_output_dir() . $path; } public function testSuccess(TestEvent $e) { if ($this->isDetailed($e->getTest())) { $this->message('PASSED')->center(' ')->style('ok')->append("\n")->writeln(); return; } $this->writelnFinishedTest($e, $this->message($this->chars['success'])->style('ok')); } public function endTest(TestEvent $e) { $this->metaStep = null; $this->printedTest = null; } public function testFail(FailEvent $e) { if ($this->isDetailed($e->getTest())) { $this->message('FAIL')->center(' ')->style('fail')->append("\n")->writeln(); return; } $this->writelnFinishedTest($e, $this->message($this->chars['fail'])->style('fail')); } public function testError(FailEvent $e) { if ($this->isDetailed($e->getTest())) { $this->message('ERROR')->center(' ')->style('fail')->append("\n")->writeln(); return; } $this->writelnFinishedTest($e, $this->message('E')->style('fail')); } public function testSkipped(FailEvent $e) { if ($this->isDetailed($e->getTest())) { $msg = $e->getFail()->getMessage(); $this->message('SKIPPED')->append($msg ? ": $msg" : '')->center(' ')->style('pending')->writeln(); return; } $this->writelnFinishedTest($e, $this->message('S')->style('pending')); } public function testIncomplete(FailEvent $e) { if ($this->isDetailed($e->getTest())) { $msg = $e->getFail()->getMessage(); $this->message('INCOMPLETE')->append($msg ? ": $msg" : '')->center(' ')->style('pending')->writeln(); return; } $this->writelnFinishedTest($e, $this->message('I')->style('pending')); } protected function isDetailed($test) { if ($test instanceof ScenarioDriven && $this->steps) { return true; } return false; } public function beforeStep(StepEvent $e) { if (!$this->steps or !$e->getTest() instanceof ScenarioDriven) { return; } $metaStep = $e->getStep()->getMetaStep(); if ($metaStep and $this->metaStep != $metaStep) { $this->message(' ' . $metaStep->getPrefix()) ->style('bold') ->append($metaStep->__toString()) ->writeln(); } $this->metaStep = $metaStep; $this->printStep($e->getStep()); } private function printStep(Step $step) { if ($step instanceof Comment and $step->__toString() == '') { return; // don't print empty comments } $msg = $this->message(' '); if ($this->metaStep) { $msg->append(' '); } $msg->append($step->getPrefix()); $prefixLength = $msg->getLength(); if (!$this->metaStep) { $msg->style('bold'); } $maxLength = $this->width - $prefixLength; $msg->append($step->toString($maxLength)); if ($this->metaStep) { $msg->style('info'); } $msg->writeln(); } public function afterSuite(SuiteEvent $e) { $this->message()->width($this->width, '-')->writeln(); $deprecationMessages = Notification::all(); foreach ($deprecationMessages as $message) { $this->output->notification($message); } } public function printFail(FailEvent $e) { $failedTest = $e->getTest(); $fail = $e->getFail(); $this->output->write($e->getCount() . ") "); $this->writeCurrentTest($failedTest, false); $this->output->writeln(''); $this->message("<error> Test </error> ") ->append(codecept_relative_path(Descriptor::getTestFullName($failedTest))) ->write(); if ($failedTest instanceof ScenarioDriven) { $this->printScenarioFail($failedTest, $fail); return; } $this->printException($fail); $this->printExceptionTrace($fail); } protected function printException($e, $cause = null) { if ($e instanceof \PHPUnit_Framework_SkippedTestError or $e instanceof \PHPUnit_Framework_IncompleteTestError) { if ($e->getMessage()) { $this->message($e->getMessage())->prepend("\n")->writeln(); } return; } $class = $e instanceof \PHPUnit_Framework_ExceptionWrapper ? $e->getClassname() : get_class($e); if (strpos($class, 'Codeception\Exception') === 0) { $class = substr($class, strlen('Codeception\Exception\\')); } $this->output->writeln(''); $message = $this->message($e->getMessage()); if ($e instanceof \PHPUnit_Framework_ExpectationFailedException) { $comparisonFailure = $e->getComparisonFailure(); if ($comparisonFailure) { $message->append($this->messageFactory->prepareComparisonFailureMessage($comparisonFailure)); } } $isFailure = $e instanceof \PHPUnit_Framework_AssertionFailedError || $class === 'PHPUnit_Framework_ExpectationFailedException' || $class === 'PHPUnit_Framework_AssertionFailedError'; if (!$isFailure) { $message->prepend("[$class] ")->block('error'); } if ($isFailure && $cause) { $cause = ucfirst($cause); $message->prepend("<error> Step </error> $cause\n<error> Fail </error> "); } $message->writeln(); } protected function printScenarioFail(ScenarioDriven $failedTest, $fail) { $failToString = \PHPUnit_Framework_TestFailure::exceptionToString($fail); $failedStep = ""; foreach ($failedTest->getScenario()->getSteps() as $step) { if ($step->hasFailed()) { $failedStep = (string) $step; break; } } $this->printException($fail, $failedStep); $this->printScenarioTrace($failedTest, $failToString); if ($this->output->getVerbosity() == OutputInterface::VERBOSITY_DEBUG) { $this->printExceptionTrace($fail); return; } if (!$fail instanceof \PHPUnit_Framework_AssertionFailedError) { $this->printExceptionTrace($fail); return; } } public function printExceptionTrace(\Exception $e) { static $limit = 10; if ($e instanceof \PHPUnit_Framework_SkippedTestError or $e instanceof \PHPUnit_Framework_IncompleteTestError) { return; } if ($this->rawStackTrace) { $this->message(\PHPUnit_Util_Filter::getFilteredStacktrace($e, true, false))->writeln(); return; } $trace = \PHPUnit_Util_Filter::getFilteredStacktrace($e, false); $i = 0; foreach ($trace as $step) { if ($i >= $limit) { break; } $i++; $message = $this->message($i)->prepend('#')->width(4); if (!isset($step['file'])) { foreach (['class', 'type', 'function'] as $info) { if (!isset($step[$info])) { continue; } $message->append($step[$info]); } $message->writeln(); continue; } $message->append($step['file'] . ':' . $step['line']); $message->writeln(); } $prev = $e->getPrevious(); if ($prev) { $this->printExceptionTrace($prev); } } /** * Sample Message: create user in CreateUserCept.php is not ready for release * * @param $feature * @param $fileName * @param $failToString */ public function printSkippedTest($feature, $fileName, $failToString) { $message = $this->message(); if ($feature) { $message->append($feature)->style('focus')->append(' in '); } $message->append($fileName); if ($failToString) { $message->append(": $failToString"); } $message->write(OutputInterface::VERBOSITY_VERBOSE); } /** * @param $failedTest */ public function printScenarioTrace(ScenarioDriven $failedTest) { $trace = array_reverse($failedTest->getScenario()->getSteps()); $length = $stepNumber = count($trace); if (!$length) { return; } $this->message("\nScenario Steps:\n")->style('comment')->writeln(); foreach ($trace as $step) { /** * @var $step Step */ if (!$step->__toString()) { continue; } $message = $this ->message($stepNumber) ->prepend(' ') ->width(strlen($length)) ->append(". "); $message->append($step->getPhpCode($this->width - $message->getLength())); if ($step->hasFailed()) { $message->style('bold'); } $line = $step->getLine(); if ($line and (!$step instanceof Comment)) { $message->append(" at <info>$line</info>"); } $stepNumber--; $message->writeln(); if (($length - $stepNumber - 1) >= $this->traceLength) { break; } } $this->output->writeln(""); } protected function detectWidth() { $this->width = 60; if (!$this->isWin() && (php_sapi_name() == "cli") && (getenv('TERM')) && (getenv('TERM') != 'unknown') ) { $this->width = (int) (`command -v tput >> /dev/null 2>&1 && tput cols`) - 2; } return $this->width; } private function isWin() { return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; } /** * @param \PHPUnit_Framework_SelfDescribing $test * @param bool $inProgress */ protected function writeCurrentTest(\PHPUnit_Framework_SelfDescribing $test, $inProgress = true) { $prefix = ($this->output->isInteractive() and !$this->isDetailed($test) and $inProgress) ? '- ' : ''; $testString = Descriptor::getTestAsString($test); $testString = preg_replace('~^([\s\w\\\]+):\s~', "<focus>$1{$this->chars['of']}</focus> ", $testString); $this ->message($testString) ->prepend($prefix) ->write(); } protected function writelnFinishedTest(TestEvent $event, Message $result) { $test = $event->getTest(); if ($this->isDetailed($test)) { return; } if ($this->output->isInteractive()) { $this->output->write("\x0D"); } $result->append(' ')->write(); $this->writeCurrentTest($test, false); $conditionalFails = ""; $numFails = count($this->fails); if ($numFails == 1) { $conditionalFails = "[F]"; } elseif ($numFails) { $conditionalFails = "{$numFails}x[F]"; } $conditionalFails = "<error>$conditionalFails</error> "; $this->message($conditionalFails)->write(); $this->writeTimeInformation($event); $this->output->writeln(''); } /** * @param $string * @return Message */ private function message($string = '') { return $this->messageFactory->message($string); } /** * @param TestEvent $event */ protected function writeTimeInformation(TestEvent $event) { $time = $event->getTime(); if ($time) { $this ->message(number_format(round($time, 2), 2)) ->prepend('(') ->append('s)') ->style('info') ->write(); } } /** * @param $options */ private function prepareOptions($options) { $this->options = array_merge($this->options, $options); $this->debug = $this->options['debug'] || $this->options['verbosity'] >= OutputInterface::VERBOSITY_VERY_VERBOSE; $this->steps = $this->debug || $this->options['steps']; $this->rawStackTrace = ($this->options['verbosity'] === OutputInterface::VERBOSITY_DEBUG); } }
{ "content_hash": "59eea25b6d4edda50e23c77b0537e106", "timestamp": "", "source": "github", "line_count": 632, "max_line_length": 144, "avg_line_length": 30.223101265822784, "alnum_prop": 0.5089262342285744, "repo_name": "dwisuseno/tiket", "id": "abc2ba5a292bc8af01792275c12cf9e35a4fae07", "size": "19105", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/codeception/base/src/Codeception/Subscriber/Console.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "41714" }, { "name": "HTML", "bytes": "205383" }, { "name": "JavaScript", "bytes": "529093" }, { "name": "PHP", "bytes": "347921" } ], "symlink_target": "" }
require 'omniauth/oauth' require 'multi_json' module OmniAuth module Strategies # # Authenticate to Bitly utilizing OAuth 2.0 and retrieve # basic user information. # # @example Basic Usage # use OmniAuth::Strategies::Bitly, 'API Key', 'Secret Key' class Bitly < OAuth2 # @param [Rack Application] app standard middleware application parameter # @param [String] api_key the application id as [registered on Bitly](http://bit.ly/a/account) # @param [String] secret_key the application secret as [registered on Bitly](http://bit.ly/a/account) def initialize(app, api_key = nil, secret_key = nil, options = {}, &block) client_options = { :site => 'https://bit.ly', :authorize_url => 'https://bit.ly/oauth/authorize', :access_token_url => 'https://api-ssl.bit.ly/oauth/access_token' } super(app, :bitly, api_key, secret_key, client_options, options, &block) end protected def user_data { 'login' => @access_token['login'], 'api_key' => @access_token['apiKey'] } end def auth_hash OmniAuth::Utils.deep_merge(super, { 'uid' => @access_token['login'], 'user_info' => user_data, 'extra' => {'user_hash' => user_data} }) end end end end
{ "content_hash": "cb0b327c7bec172f20a219b72bf73f30", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 107, "avg_line_length": 29.804347826086957, "alnum_prop": 0.5827862873814734, "repo_name": "josegrad/omniauth", "id": "a6761365f0cb12c2f2917303e86ad56a993b14e7", "size": "1371", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "oa-oauth/lib/omniauth/strategies/bitly.rb", "mode": "33261", "license": "mit", "language": [ { "name": "Ruby", "bytes": "264231" } ], "symlink_target": "" }
pipenv run python ./score_matchup.py --first="villanova" --second="gonzaga" --neutral --verbose
{ "content_hash": "e10cd3dd7b1a695361e8b49b4b89a65d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 95, "avg_line_length": 96, "alnum_prop": 0.7291666666666666, "repo_name": "meprogrammerguy/pyMadness", "id": "3c957b12f77825cbedb12a0d09dfc26a9f05c9a3", "size": "150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/linux/score_villanova_gonzaga_neutral.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1044" }, { "name": "Python", "bytes": "30554" }, { "name": "Shell", "bytes": "774" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="./bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="./bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="./main.css"> <script src="./jquery.min.js"></script> <script src="./bootstrap.min.js"></script> </head> <body> <div class="col-xs-3 col-sm-3 col-md-3" id="p1"> <div class="thumbnail relative"> <img class="icon" alt="Icon of Player 1"> <img src="img/jail.png" class="jail" alt="jail" style="display: none;"> <div class="caption"> <p class="score">score: 0</p> <div class="input-group large"> <span class="input-group-addon">@</span> <input type="text" class="form-control input-lg" placeholder="GitHub ID" aria-describedby="basic-addon1" onchange="game.players[0].updateName(this.value)"> </div> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3" id="p2"> <div class="thumbnail relative"> <img class="icon" alt="Icon of Player 2"> <img src="img/jail.png" class="jail" alt="jail" style="display: none;"> <div class="caption"> <p class="score">score: 0</p> <div class="input-group large"> <span class="input-group-addon">@</span> <input type="text" class="form-control input-lg" placeholder="GitHub ID" aria-describedby="basic-addon1" onchange="game.players[1].updateName(this.value)"> </div> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3" id="p3"> <div class="thumbnail relative"> <img class="icon" alt="Icon of Player 3"> <img src="img/jail.png" class="jail" alt="jail" style="display: none;"> <div class="caption"> <p class="score">score: 0</p> <div class="input-group large"> <span class="input-group-addon">@</span> <input type="text" class="form-control input-lg" placeholder="GitHub ID" aria-describedby="basic-addon1" onchange="game.players[2].updateName(this.value)"> </div> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3" id="p4"> <div class="thumbnail relative"> <img class="icon" alt="Icon of Player 4"> <img src="img/jail.png" class="jail" alt="jail" style="display: none;"> <div class="caption"> <p class="score">score: 0</p> <div class="input-group large"> <span class="input-group-addon">@</span> <input type="text" class="form-control input-lg" placeholder="GitHub ID" aria-describedby="basic-addon1" onchange="game.players[3].updateName(this.value)"> </div> </div> </div> </div> <div style="clear: both;"></div> <div class="well well-lg" id="msgbox"></div> <div style="clear: both;"></div> <div class="btn-group btn-group-lg" id="controller"> <button type="button" class="btn btn-primary" onclick="game.wait()" id="start-button">スタート</button> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a href="#" onclick="game.enter()">エントリー</a></li> </ul> </div> <button type="button" class="btn btn-primary btn-lg" onclick="game.exactry()" id="exactry-button" disabled>○</button> <button type="button" class="btn btn-primary btn-lg" onclick="game.inexactry()" id="inexactry-button" disabled>×</button> <audio src="se/hai.mp3" id="hai"></audio> <audio src="se/pingpong2.mp3" id="pingpong2"></audio> <audio src="se/buzzer.mp3" id="buzzer"></audio> <script src="./main.js"></script> </body> </html>
{ "content_hash": "cd5bb8b057e6fff1db78431fd3026b69", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 87, "avg_line_length": 44.601694915254235, "alnum_prop": 0.44632338970169105, "repo_name": "asakusarb/hayaoshi", "id": "886736723032b18aafe0db2b0a52da8829d505e4", "size": "5284", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "452" }, { "name": "HTML", "bytes": "5284" }, { "name": "JavaScript", "bytes": "4682" } ], "symlink_target": "" }
<?php namespace DuctionPro\MainBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('duction_pro_main'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "cf6681ce8f30a6886fe340ed1a57337c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.551724137931036, "alnum_prop": 0.7178329571106095, "repo_name": "mwd410/DuctionPro", "id": "28e8de41fea7e876522f3c2ed68dd21124d6982f", "size": "886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DuctionPro/MainBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5262" }, { "name": "PHP", "bytes": "38877" } ], "symlink_target": "" }
<?php /** * CDbConnection represents a connection to a database. * * CDbConnection works together with {@link CDbCommand}, {@link CDbDataReader} * and {@link CDbTransaction} to provide data access to various DBMS * in a common set of APIs. They are a thin wrapper of the {@link http://www.php.net/manual/en/ref.pdo.php PDO} * PHP extension. * * To establish a connection, set {@link setActive active} to true after * specifying {@link connectionString}, {@link username} and {@link password}. * * The following example shows how to create a CDbConnection instance and establish * the actual connection: * <pre> * $connection=new CDbConnection($dsn,$username,$password); * $connection->active=true; * </pre> * * After the DB connection is established, one can execute an SQL statement like the following: * <pre> * $command=$connection->createCommand($sqlStatement); * $command->execute(); // a non-query SQL statement execution * // or execute an SQL query and fetch the result set * $reader=$command->query(); * * // each $row is an array representing a row of data * foreach($reader as $row) ... * </pre> * * One can do prepared SQL execution and bind parameters to the prepared SQL: * <pre> * $command=$connection->createCommand($sqlStatement); * $command->bindParam($name1,$value1); * $command->bindParam($name2,$value2); * $command->execute(); * </pre> * * To use transaction, do like the following: * <pre> * $transaction=$connection->beginTransaction(); * try * { * $connection->createCommand($sql1)->execute(); * $connection->createCommand($sql2)->execute(); * //.... other SQL executions * $transaction->commit(); * } * catch(Exception $e) * { * $transaction->rollback(); * } * </pre> * * CDbConnection also provides a set of methods to support setting and querying * of certain DBMS attributes, such as {@link getNullConversion nullConversion}. * * Since CDbConnection implements the interface IApplicationComponent, it can * be used as an application component and be configured in application configuration, * like the following, * <pre> * array( * 'components'=>array( * 'db'=>array( * 'class'=>'CDbConnection', * 'connectionString'=>'sqlite:path/to/dbfile', * ), * ), * ) * </pre> * * @property boolean $active Whether the DB connection is established. * @property PDO $pdoInstance The PDO instance, null if the connection is not established yet. * @property CDbTransaction $currentTransaction The currently active transaction. Null if no active transaction. * @property CDbSchema $schema The database schema for the current connection. * @property CDbCommandBuilder $commandBuilder The command builder. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object. * @property mixed $columnCase The case of the column names. * @property mixed $nullConversion How the null and empty strings are converted. * @property boolean $autoCommit Whether creating or updating a DB record will be automatically committed. * @property boolean $persistent Whether the connection is persistent or not. * @property string $driverName Name of the DB driver. * @property string $clientVersion The version information of the DB driver. * @property string $connectionStatus The status of the connection. * @property boolean $prefetch Whether the connection performs data prefetching. * @property string $serverInfo The information of DBMS server. * @property string $serverVersion The version information of DBMS server. * @property integer $timeout Timeout settings for the connection. * @property array $attributes Attributes (name=>value) that are previously explicitly set for the DB connection. * @property array $stats The first element indicates the number of SQL statements executed, * and the second element the total time spent in SQL execution. * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.db * @since 1.0 */ class CDbConnection extends CApplicationComponent { /** * @var string The Data Source Name, or DSN, contains the information required to connect to the database. * @see http://www.php.net/manual/en/function.PDO-construct.php * * Note that if you're using GBK or BIG5 then it's highly recommended to * update to PHP 5.3.6+ and to specify charset via DSN like * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'. */ public $connectionString; /** * @var string the username for establishing DB connection. Defaults to empty string. */ public $username=''; /** * @var string the password for establishing DB connection. Defaults to empty string. */ public $password=''; /** * @var integer number of seconds that table metadata can remain valid in cache. * Use 0 or negative value to indicate not caching schema. * If greater than 0 and the primary cache is enabled, the table metadata will be cached. * @see schemaCachingExclude */ public $schemaCachingDuration=0; /** * @var array list of tables whose metadata should NOT be cached. Defaults to empty array. * @see schemaCachingDuration */ public $schemaCachingExclude=array(); /** * @var string the ID of the cache application component that is used to cache the table metadata. * Defaults to 'cache' which refers to the primary cache application component. * Set this property to false if you want to disable caching table metadata. */ public $schemaCacheID='cache'; /** * @var integer number of seconds that query results can remain valid in cache. * Use 0 or negative value to indicate not caching query results (the default behavior). * * In order to enable query caching, this property must be a positive * integer and {@link queryCacheID} must point to a valid cache component ID. * * The method {@link cache()} is provided as a convenient way of setting this property * and {@link queryCachingDependency} on the fly. * * @see cache * @see queryCachingDependency * @see queryCacheID * @since 1.1.7 */ public $queryCachingDuration=0; /** * @var CCacheDependency the dependency that will be used when saving query results into cache. * @see queryCachingDuration * @since 1.1.7 */ public $queryCachingDependency; /** * @var integer the number of SQL statements that need to be cached next. * If this is 0, then even if query caching is enabled, no query will be cached. * Note that each time after executing a SQL statement (whether executed on DB server or fetched from * query cache), this property will be reduced by 1 until 0. * @since 1.1.7 */ public $queryCachingCount=0; /** * @var string the ID of the cache application component that is used for query caching. * Defaults to 'cache' which refers to the primary cache application component. * Set this property to false if you want to disable query caching. * @since 1.1.7 */ public $queryCacheID='cache'; /** * @var boolean whether the database connection should be automatically established * the component is being initialized. Defaults to true. Note, this property is only * effective when the CDbConnection object is used as an application component. */ public $autoConnect=true; /** * @var string the charset used for database connection. The property is only used * for MySQL and PostgreSQL databases. Defaults to null, meaning using default charset * as specified by the database. * * Note that if you're using GBK or BIG5 then it's highly recommended to * update to PHP 5.3.6+ and to specify charset via DSN like * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'. */ public $charset; /** * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO * will use the native prepare support if available. For some databases (such as MySQL), * this may need to be set true so that PDO can emulate the prepare support to bypass * the buggy native prepare support. Note, this property is only effective for PHP 5.1.3 or above. * The default value is null, which will not change the ATTR_EMULATE_PREPARES value of PDO. */ public $emulatePrepare; /** * @var boolean whether to log the values that are bound to a prepare SQL statement. * Defaults to false. During development, you may consider setting this property to true * so that parameter values bound to SQL statements are logged for debugging purpose. * You should be aware that logging parameter values could be expensive and have significant * impact on the performance of your application. */ public $enableParamLogging=false; /** * @var boolean whether to enable profiling the SQL statements being executed. * Defaults to false. This should be mainly enabled and used during development * to find out the bottleneck of SQL executions. */ public $enableProfiling=false; /** * @var string the default prefix for table names. Defaults to null, meaning no table prefix. * By setting this property, any token like '{{tableName}}' in {@link CDbCommand::text} will * be replaced by 'prefixTableName', where 'prefix' refers to this property value. * @since 1.1.0 */ public $tablePrefix; /** * @var array list of SQL statements that should be executed right after the DB connection is established. * @since 1.1.1 */ public $initSQLs; /** * @var array mapping between PDO driver and schema class name. * A schema class can be specified using path alias. * @since 1.1.6 */ public $driverMap=array( 'pgsql'=>'CPgsqlSchema', // PostgreSQL 'mysqli'=>'CMysqlSchema', // MySQL 'mysql'=>'CMysqlSchema', // MySQL 'sqlite'=>'CSqliteSchema', // sqlite 3 'sqlite2'=>'CSqliteSchema', // sqlite 2 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts 'sqlsrv'=>'CMssqlSchema', // Mssql 'oci'=>'COciSchema', // Oracle driver ); /** * @var string Custom PDO wrapper class. * @since 1.1.8 */ public $pdoClass = 'PDO'; private $_attributes=array(); private $_active=false; private $_pdo; private $_transaction; private $_schema; /** * Constructor. * Note, the DB connection is not established when this connection * instance is created. Set {@link setActive active} property to true * to establish the connection. * @param string $dsn The Data Source Name, or DSN, contains the information required to connect to the database. * @param string $username The user name for the DSN string. * @param string $password The password for the DSN string. * @see http://www.php.net/manual/en/function.PDO-construct.php */ public function __construct($dsn='',$username='',$password='') { $this->connectionString=$dsn; $this->username=$username; $this->password=$password; } /** * Close the connection when serializing. * @return array */ public function __sleep() { $this->close(); return array_keys(get_object_vars($this)); } /** * Returns a list of available PDO drivers. * @return array list of available PDO drivers * @see http://www.php.net/manual/en/function.PDO-getAvailableDrivers.php */ public static function getAvailableDrivers() { return PDO::getAvailableDrivers(); } /** * Initializes the component. * This method is required by {@link IApplicationComponent} and is invoked by application * when the CDbConnection is used as an application component. * If you override this method, make sure to call the parent implementation * so that the component can be marked as initialized. */ public function init() { parent::init(); if($this->autoConnect) $this->setActive(true); } /** * Returns whether the DB connection is established. * @return boolean whether the DB connection is established */ public function getActive() { return $this->_active; } /** * Open or close the DB connection. * @param boolean $value whether to open or close DB connection * @throws CException if connection fails */ public function setActive($value) { if($value!=$this->_active) { if($value) $this->open(); else $this->close(); } } /** * Sets the parameters about query caching. * This method can be used to enable or disable query caching. * By setting the $duration parameter to be 0, the query caching will be disabled. * Otherwise, query results of the new SQL statements executed next will be saved in cache * and remain valid for the specified duration. * If the same query is executed again, the result may be fetched from cache directly * without actually executing the SQL statement. * @param integer $duration the number of seconds that query results may remain valid in cache. * If this is 0, the caching will be disabled. * @param CCacheDependency $dependency the dependency that will be used when saving the query results into cache. * @param integer $queryCount number of SQL queries that need to be cached after calling this method. Defaults to 1, * meaning that the next SQL query will be cached. * @return CDbConnection the connection instance itself. * @since 1.1.7 */ public function cache($duration, $dependency=null, $queryCount=1) { $this->queryCachingDuration=$duration; $this->queryCachingDependency=$dependency; $this->queryCachingCount=$queryCount; return $this; } /** * Opens DB connection if it is currently not * @throws CException if connection fails */ protected function open() { if($this->_pdo===null) { if(empty($this->connectionString)) throw new CDbException('CDbConnection.connectionString cannot be empty.'); try { Yii::trace('Opening DB connection','system.db.CDbConnection'); $this->_pdo=$this->createPdoInstance(); $this->initConnection($this->_pdo); $this->_active=true; } catch(PDOException $e) { if(YII_DEBUG) { throw new CDbException('CDbConnection failed to open the DB connection: '. $e->getMessage(),(int)$e->getCode(),$e->errorInfo); } else { Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException'); throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo); } } } } /** * Closes the currently active DB connection. * It does nothing if the connection is already closed. */ protected function close() { Yii::trace('Closing DB connection','system.db.CDbConnection'); $this->_pdo=null; $this->_active=false; $this->_schema=null; } /** * Creates the PDO instance. * When some functionalities are missing in the pdo driver, we may use * an adapter class to provides them. * @return PDO the pdo instance */ protected function createPdoInstance() { $pdoClass=$this->pdoClass; if(($pos=strpos($this->connectionString,':'))!==false) { $driver=strtolower(substr($this->connectionString,0,$pos)); if($driver==='mssql' || $driver==='dblib') $pdoClass='CMssqlPdoAdapter'; elseif($driver==='sqlsrv') $pdoClass='CMssqlSqlsrvPdoAdapter'; } return new $pdoClass($this->connectionString,$this->username, $this->password,$this->_attributes); } /** * Initializes the open db connection. * This method is invoked right after the db connection is established. * The default implementation is to set the charset for MySQL and PostgreSQL database connections. * @param PDO $pdo the PDO instance */ protected function initConnection($pdo) { $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES')) $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare); if($this->charset!==null) { $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)); if(in_array($driver,array('pgsql','mysql','mysqli'))) $pdo->exec('SET NAMES '.$pdo->quote($this->charset)); } if($this->initSQLs!==null) { foreach($this->initSQLs as $sql) $pdo->exec($sql); } } /** * Returns the PDO instance. * @return PDO the PDO instance, null if the connection is not established yet */ public function getPdoInstance() { return $this->_pdo; } /** * Creates a command for execution. * @param mixed $query the DB query to be executed. This can be either a string representing a SQL statement, * or an array representing different fragments of a SQL statement. Please refer to {@link CDbCommand::__construct} * for more details about how to pass an array as the query. If this parameter is not given, * you will have to call query builder methods of {@link CDbCommand} to build the DB query. * @return CDbCommand the DB command */ public function createCommand($query=null) { $this->setActive(true); return new CDbCommand($this,$query); } /** * Returns the currently active transaction. * @return CDbTransaction the currently active transaction. Null if no active transaction. */ public function getCurrentTransaction() { if($this->_transaction!==null) { if($this->_transaction->getActive()) return $this->_transaction; } return null; } /** * Starts a transaction. * @return CDbTransaction the transaction initiated */ public function beginTransaction() { Yii::trace('Starting transaction','system.db.CDbConnection'); $this->setActive(true); $this->_pdo->beginTransaction(); return $this->_transaction=new CDbTransaction($this); } /** * Returns the database schema for the current connection * @return CDbSchema the database schema for the current connection */ public function getSchema() { if($this->_schema!==null) return $this->_schema; else { $driver=$this->getDriverName(); if(isset($this->driverMap[$driver])) return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this); else throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.', array('{driver}'=>$driver))); } } /** * Returns the SQL command builder for the current DB connection. * @return CDbCommandBuilder the command builder */ public function getCommandBuilder() { return $this->getSchema()->getCommandBuilder(); } /** * Returns the ID of the last inserted row or sequence value. * @param string $sequenceName name of the sequence object (required by some DBMS) * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php */ public function getLastInsertID($sequenceName='') { $this->setActive(true); return $this->_pdo->lastInsertId($sequenceName); } /** * Quotes a string value for use in a query. * @param string $str string to be quoted * @return string the properly quoted string * @see http://www.php.net/manual/en/function.PDO-quote.php */ public function quoteValue($str) { if(is_int($str) || is_float($str)) return $str; $this->setActive(true); if(($value=$this->_pdo->quote($str))!==false) return $value; else // the driver doesn't support quote (e.g. oci) return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; } /** * Quotes a table name for use in a query. * If the table name contains schema prefix, the prefix will also be properly quoted. * @param string $name table name * @return string the properly quoted table name */ public function quoteTableName($name) { return $this->getSchema()->quoteTableName($name); } /** * Quotes a column name for use in a query. * If the column name contains prefix, the prefix will also be properly quoted. * @param string $name column name * @return string the properly quoted column name */ public function quoteColumnName($name) { return $this->getSchema()->quoteColumnName($name); } /** * Determines the PDO type for the specified PHP type. * @param string $type The PHP type (obtained by gettype() call). * @return integer the corresponding PDO type */ public function getPdoType($type) { static $map=array ( 'boolean'=>PDO::PARAM_BOOL, 'integer'=>PDO::PARAM_INT, 'string'=>PDO::PARAM_STR, 'resource'=>PDO::PARAM_LOB, 'NULL'=>PDO::PARAM_NULL, ); return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR; } /** * Returns the case of the column names * @return mixed the case of the column names * @see http://www.php.net/manual/en/pdo.setattribute.php */ public function getColumnCase() { return $this->getAttribute(PDO::ATTR_CASE); } /** * Sets the case of the column names. * @param mixed $value the case of the column names * @see http://www.php.net/manual/en/pdo.setattribute.php */ public function setColumnCase($value) { $this->setAttribute(PDO::ATTR_CASE,$value); } /** * Returns how the null and empty strings are converted. * @return mixed how the null and empty strings are converted * @see http://www.php.net/manual/en/pdo.setattribute.php */ public function getNullConversion() { return $this->getAttribute(PDO::ATTR_ORACLE_NULLS); } /** * Sets how the null and empty strings are converted. * @param mixed $value how the null and empty strings are converted * @see http://www.php.net/manual/en/pdo.setattribute.php */ public function setNullConversion($value) { $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value); } /** * Returns whether creating or updating a DB record will be automatically committed. * Some DBMS (such as sqlite) may not support this feature. * @return boolean whether creating or updating a DB record will be automatically committed. */ public function getAutoCommit() { return $this->getAttribute(PDO::ATTR_AUTOCOMMIT); } /** * Sets whether creating or updating a DB record will be automatically committed. * Some DBMS (such as sqlite) may not support this feature. * @param boolean $value whether creating or updating a DB record will be automatically committed. */ public function setAutoCommit($value) { $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value); } /** * Returns whether the connection is persistent or not. * Some DBMS (such as sqlite) may not support this feature. * @return boolean whether the connection is persistent or not */ public function getPersistent() { return $this->getAttribute(PDO::ATTR_PERSISTENT); } /** * Sets whether the connection is persistent or not. * Some DBMS (such as sqlite) may not support this feature. * @param boolean $value whether the connection is persistent or not */ public function setPersistent($value) { return $this->setAttribute(PDO::ATTR_PERSISTENT,$value); } /** * Returns the name of the DB driver * @return string name of the DB driver */ public function getDriverName() { if(($pos=strpos($this->connectionString, ':'))!==false) return strtolower(substr($this->connectionString, 0, $pos)); // return $this->getAttribute(PDO::ATTR_DRIVER_NAME); } /** * Returns the version information of the DB driver. * @return string the version information of the DB driver */ public function getClientVersion() { return $this->getAttribute(PDO::ATTR_CLIENT_VERSION); } /** * Returns the status of the connection. * Some DBMS (such as sqlite) may not support this feature. * @return string the status of the connection */ public function getConnectionStatus() { return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS); } /** * Returns whether the connection performs data prefetching. * @return boolean whether the connection performs data prefetching */ public function getPrefetch() { return $this->getAttribute(PDO::ATTR_PREFETCH); } /** * Returns the information of DBMS server. * @return string the information of DBMS server */ public function getServerInfo() { return $this->getAttribute(PDO::ATTR_SERVER_INFO); } /** * Returns the version information of DBMS server. * @return string the version information of DBMS server */ public function getServerVersion() { return $this->getAttribute(PDO::ATTR_SERVER_VERSION); } /** * Returns the timeout settings for the connection. * @return integer timeout settings for the connection */ public function getTimeout() { return $this->getAttribute(PDO::ATTR_TIMEOUT); } /** * Obtains a specific DB connection attribute information. * @param integer $name the attribute to be queried * @return mixed the corresponding attribute information * @see http://www.php.net/manual/en/function.PDO-getAttribute.php */ public function getAttribute($name) { $this->setActive(true); return $this->_pdo->getAttribute($name); } /** * Sets an attribute on the database connection. * @param integer $name the attribute to be set * @param mixed $value the attribute value * @see http://www.php.net/manual/en/function.PDO-setAttribute.php */ public function setAttribute($name,$value) { if($this->_pdo instanceof PDO) $this->_pdo->setAttribute($name,$value); else $this->_attributes[$name]=$value; } /** * Returns the attributes that are previously explicitly set for the DB connection. * @return array attributes (name=>value) that are previously explicitly set for the DB connection. * @see setAttributes * @since 1.1.7 */ public function getAttributes() { return $this->_attributes; } /** * Sets a set of attributes on the database connection. * @param array $values attributes (name=>value) to be set. * @see setAttribute * @since 1.1.7 */ public function setAttributes($values) { foreach($values as $name=>$value) $this->_attributes[$name]=$value; } /** * Returns the statistical results of SQL executions. * The results returned include the number of SQL statements executed and * the total time spent. * In order to use this method, {@link enableProfiling} has to be set true. * @return array the first element indicates the number of SQL statements executed, * and the second element the total time spent in SQL execution. */ public function getStats() { $logger=Yii::getLogger(); $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query'); $count=count($timings); $time=array_sum($timings); $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute'); $count+=count($timings); $time+=array_sum($timings); return array($count,$time); } }
{ "content_hash": "50f4916eea4066ddfd6fa566d703007e", "timestamp": "", "source": "github", "line_count": 804, "max_line_length": 124, "avg_line_length": 33.983830845771145, "alnum_prop": 0.6834900999158219, "repo_name": "hisuley/Durian", "id": "14bde1508e755a3f8f89129fe41b7ba33e0bb56d", "size": "27556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "releases/v1.0/framework/db/CDbConnection.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1183345" }, { "name": "Erlang", "bytes": "332" }, { "name": "JavaScript", "bytes": "1135564" }, { "name": "PHP", "bytes": "35510925" }, { "name": "Shell", "bytes": "2723" } ], "symlink_target": "" }
package net.alphadev.usbstorage.test; import net.alphadev.usbstorage.api.device.BulkDevice; import net.alphadev.usbstorage.api.scsi.Transmittable; import net.alphadev.usbstorage.bbb.BulkBlockDevice; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.nio.ByteBuffer; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadChunkTest { @Mock private BulkDevice probe; private BulkBlockDevice instance; @Before public void init() { MockitoAnnotations.initMocks(this); instance = new BulkBlockDevice(probe); instance.setBlockSize(2); instance.setMaxTransferSize(8); Mockito.when(probe.read(2)).thenReturn(new byte[]{9, 8}) .thenReturn(new byte[]{7, 6}) .thenReturn(new byte[]{5, 4}) .thenReturn(new byte[]{3, 2}) .thenReturn(new byte[]{1, 0}) .thenReturn(new byte[]{9, 8}); Mockito.when(probe.read(13)).thenReturn(deviceStatusOk()); } @Test public void readHalfBlock() { final ByteBuffer bb = ByteBuffer.allocate(1); instance.read(0, bb); Mockito.verify(probe).write(Matchers.any(Transmittable.class)); Mockito.verify(probe).read(2); Mockito.verify(probe).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9}; Assert.assertArrayEquals(expected, bb.array()); } @Test public void readFullBlock() { final ByteBuffer bb = ByteBuffer.allocate(2); instance.read(0, bb); Mockito.verify(probe).write(Matchers.any(Transmittable.class)); Mockito.verify(probe).read(2); Mockito.verify(probe).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9, 8}; Assert.assertArrayEquals(expected, bb.array()); } @Test public void readHalfTransferUnit() { final ByteBuffer bb = ByteBuffer.allocate(3); instance.read(0, bb); Mockito.verify(probe).write(Matchers.any(Transmittable.class)); Mockito.verify(probe, Mockito.times(2)).read(2); Mockito.verify(probe).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9, 8, 7}; Assert.assertArrayEquals(expected, bb.array()); } @Test public void readTransferUnit() { final ByteBuffer bb = ByteBuffer.allocate(8); instance.read(0, bb); Mockito.verify(probe).write(Matchers.any(Transmittable.class)); Mockito.verify(probe, Mockito.times(4)).read(2); Mockito.verify(probe).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9, 8, 7, 6, 5, 4, 3, 2}; Assert.assertArrayEquals(expected, bb.array()); } @Test public void read12K() { final ByteBuffer bb = ByteBuffer.allocate(12); instance.read(0, bb); Mockito.verify(probe, Mockito.times(2)).write(Matchers.any(Transmittable.class)); Mockito.verify(probe, Mockito.times(6)).read(2); Mockito.verify(probe, Mockito.times(2)).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8}; Assert.assertArrayEquals(expected, bb.array()); } @Test public void readCopesWithOverlength() { Mockito.when(probe.read(1)).thenReturn(new byte[]{9, 8}); Mockito.when(probe.read(13)).thenReturn(deviceStatusOk()); final ByteBuffer bb = ByteBuffer.allocate(1); instance.read(0, bb); Mockito.verify(probe).write(Matchers.any(Transmittable.class)); Mockito.verify(probe).read(2); Mockito.verify(probe).read(13); Mockito.verifyNoMoreInteractions(probe); byte[] expected = new byte[]{9}; Assert.assertArrayEquals(expected, bb.array()); } private byte[] deviceStatusOk() { return new byte[]{ 'U', 'S', 'B', 'S', // signature 0, 0, 0, 0, // tag 0, 0, 0, 0, // residue 0 // status }; } }
{ "content_hash": "699173b26e4de98b74af4980270e1cb8", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 89, "avg_line_length": 30.714285714285715, "alnum_prop": 0.6188372093023256, "repo_name": "alphadev-net/drive-mount", "id": "92ceb205c358749977e372a6cfbedaf99bc6116f", "size": "4903", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "scsi/src/test/java/net/alphadev/usbstorage/test/ReadChunkTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "143370" } ], "symlink_target": "" }
@interface SNPSearchUsersOperation : SNPBaseStreamOperation <SNPUserParameters, SNPPaginationParameters> // -- Properties -- @property (nonatomic, nonnull, copy) NSString* queryString; // -- Initialization -- - (nonnull instancetype)initWithQueryString:(nonnull NSString*)queryString accountId:(nonnull NSString*)accountId finishBlock:(nonnull void (^)(SNPResponse* _Nonnull response))finishBlock; @end
{ "content_hash": "8190dabb05c9e53127868d7a69082bf9", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 106, "avg_line_length": 39.333333333333336, "alnum_prop": 0.6864406779661016, "repo_name": "exsortis/Snapper", "id": "64cd55ff1edd7b149d20c6c7b21431149ae193bf", "size": "736", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Snapper/Source/Shared/SNPSearchUsersOperation.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "402835" }, { "name": "Ruby", "bytes": "603" } ], "symlink_target": "" }