defmodule Level.PostsTest do
  use Level.DataCase, async: true

  import Ecto.Query

  alias Ecto.Changeset
  alias Level.Groups
  alias Level.Notifications
  alias Level.Posts
  alias Level.Repo
  alias Level.Schemas.File
  alias Level.Schemas.Group
  alias Level.Schemas.Notification
  alias Level.Schemas.Post
  alias Level.Schemas.PostLog
  alias Level.Schemas.PostReaction
  alias Level.Schemas.PostVersion
  alias Level.Schemas.PostView
  alias Level.Schemas.Reply
  alias Level.Schemas.ReplyReaction
  alias Level.Schemas.SpaceUser
  alias Level.Schemas.User

  describe "posts_base_query/1 with users" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space(%{handle: "derrick"})
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, Map.put(result, :group, group)}
    end

    test "should not include posts not in the user's spaces", %{
      space_user: space_user,
      group: group
    } do
      {:ok, %{post: %Post{id: post_id}}} = create_post(space_user, group)
      {:ok, outside_user} = create_user()

      result =
        outside_user
        |> Posts.posts_base_query()
        |> Repo.get_by(id: post_id)

      assert result == nil
    end

    test "should not include posts in private groups the user cannot access", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, group} = Groups.privatize(group)
      {:ok, %{post: %Post{id: post_id}}} = create_post(space_user, group)
      {:ok, %{user: another_user}} = create_space_member(space)

      result =
        another_user
        |> Posts.posts_base_query()
        |> Repo.get_by(id: post_id)

      assert result == nil
    end

    test "should include posts in private groups the user can access", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, group} = Groups.privatize(group)
      {:ok, %{post: %Post{id: post_id}}} = create_post(space_user, group)
      {:ok, %{user: another_user, space_user: another_space_user}} = create_space_member(space)
      :ok = Groups.subscribe(group, another_space_user)

      assert %Post{id: ^post_id} =
               another_user
               |> Posts.posts_base_query()
               |> Repo.get_by(id: post_id)
    end

    test "should include posts in public groups", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{post: %Post{id: post_id}}} = create_post(space_user, group)
      {:ok, %{user: another_user}} = create_space_member(space)

      assert %Post{id: ^post_id} =
               another_user
               |> Posts.posts_base_query()
               |> Repo.get_by(id: post_id)
    end

    test "should include posts sent directly to the user", %{
      levelbot: levelbot,
      user: user
    } do
      {:ok, %{post: %Post{id: post_id}}} =
        Posts.create_post(levelbot, %{body: "Hello @derrick", display_name: "Level"})

      assert %Post{id: ^post_id} =
               user
               |> Posts.posts_base_query()
               |> Repo.get_by(id: post_id)
    end

    test "should exclude posts sent directly to other users", %{
      space: space,
      levelbot: levelbot
    } do
      {:ok, %{post: %Post{id: post_id}}} =
        Posts.create_post(levelbot, %{body: "Hello @derrick", display_name: "Level"})

      {:ok, %{user: another_user}} = create_space_member(space)

      refute another_user
             |> Posts.posts_base_query()
             |> Repo.get_by(id: post_id)
    end

    test "should exclude deleted posts", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{post: %Post{id: post_id} = post}} = create_post(space_user, group)
      {:ok, %{user: another_user}} = create_space_member(space)

      post
      |> Changeset.change(state: "DELETED")
      |> Repo.update()

      refute another_user
             |> Posts.posts_base_query()
             |> Repo.get_by(id: post_id)
    end
  end

  describe "get_subscribers/1" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "includes subscribers", %{space: space, space_user: space_user, post: post} do
      {:ok, %{space_user: another_user}} = create_space_member(space)
      Posts.subscribe(another_user, [post])

      {:ok, result} = Posts.get_subscribers(post)

      ids =
        result
        |> Enum.map(fn user -> user.id end)
        |> Enum.sort()

      assert ids == Enum.sort([space_user.id, another_user.id])
    end

    test "excludes unsubscribes", %{space_user: space_user, post: post} do
      Posts.unsubscribe(space_user, [post])
      assert {:ok, []} = Posts.get_subscribers(post)
    end
  end

  describe "create_post/2 with space user" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user, %{name: "room"})
      {:ok, Map.put(result, :group, group)}
    end

    test "creates a new post given valid params", %{space_user: space_user, group: group} do
      params = valid_post_params() |> Map.merge(%{body: "The body"})
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)
      assert post.space_user_id == space_user.id
      assert post.body == "The body"
    end

    test "puts the post in the given group", %{
      space_user: space_user,
      group: %Group{id: group_id} = group
    } do
      params = valid_post_params()
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      post = Repo.preload(post, :groups)
      assert [%Group{id: ^group_id} | _] = post.groups
    end

    test "subscribes the user to the post", %{space_user: space_user, group: group} do
      params = valid_post_params()
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      assert %{inbox: "EXCLUDED", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, space_user)
    end

    test "logs the event", %{space_user: space_user, group: group} do
      params = valid_post_params()
      {:ok, %{post: post, log: log}} = Posts.create_post(space_user, group, params)
      assert log.event == "POST_CREATED"
      assert log.space_user_id == space_user.id
      assert log.post_id == post.id
    end

    test "subscribes mentioned users and marks as unread", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{space_user: mentioned}} = create_space_member(space, %{handle: "tiff"})
      {:ok, %{space_user: another_mentioned}} = create_space_member(space, %{handle: "derrick"})

      params = valid_post_params() |> Map.merge(%{body: "Hey @tiff and @derrick"})
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, mentioned)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_mentioned)

      assert [%Notification{event: "POST_CREATED"}] = Notifications.list(mentioned, post)
    end

    test "loops in mentioned users who formerly did not have access", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{space_user: %SpaceUser{id: mentioned_id} = mentioned}} =
        create_space_member(space, %{handle: "tiff"})

      {:ok, group} = Groups.update_group(group, %{is_private: true})

      params = valid_post_params() |> Map.merge(%{body: "Hey @tiff"})

      {:ok, %{post: post, mentions: %{space_users: [%SpaceUser{id: ^mentioned_id}]}}} =
        Posts.create_post(space_user, group, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, mentioned)
    end

    test "subscribes channel watchers", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)
      Groups.watch(group, another_user)

      params = valid_post_params()
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_user)
    end

    test "does not put in author's inbox when author is watching the channel", %{
      space_user: author,
      group: group
    } do
      Groups.watch(group, author)

      params = valid_post_params()
      {:ok, %{post: post}} = Posts.create_post(author, group, params)

      assert %{inbox: "EXCLUDED", subscription: "SUBSCRIBED"} = Posts.get_user_state(post, author)
    end

    test "handles channel mentions", %{
      space: space,
      space_user: space_user,
      group: group
    } do
      {:ok, %{group: %Group{id: another_group_id} = another_group}} =
        create_group(space_user, %{name: "devs"})

      {:ok, %{space_user: another_user}} = create_space_member(space)
      Groups.subscribe(another_group, another_user)

      params = valid_post_params() |> Map.merge(%{body: "Hey @#devs"})

      assert {:ok, %{post: post, mentions: %{groups: [%Group{id: ^another_group_id}]}}} =
               Posts.create_post(space_user, group, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_user)
    end

    test "attaches file uploads", %{space_user: space_user, group: group} do
      {:ok, %File{id: file_id}} = create_file(space_user)
      params = valid_post_params() |> Map.merge(%{file_ids: [file_id]})
      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      assert [%File{id: ^file_id}] =
               post
               |> Ecto.assoc(:files)
               |> Repo.all()
    end

    test "stores the locator", %{space_user: space_user, group: group} do
      locator_params = %{scope: "level", topic: "welcome_message", key: group.id}
      params = valid_post_params() |> Map.merge(%{locator: locator_params})
      {:ok, %{post: post, locator: locator}} = Posts.create_post(space_user, group, params)

      assert locator.post_id == post.id
      assert locator.scope == "level"
      assert locator.topic == "welcome_message"
      assert locator.key == group.id
    end

    test "adds to tagged groups", %{space_user: space_user, group: group} do
      {:ok, %{group: another_group}} = create_group(space_user, %{name: "my-group"})

      params =
        valid_post_params()
        |> Map.put(:body, "Hello #my-group")

      {:ok, %{post: post}} = Posts.create_post(space_user, group, params)

      post = Repo.preload(post, :groups)
      assert Enum.any?(post.groups, fn group -> group.id == another_group.id end)
    end

    test "handles duplicate tagged groups", %{space_user: space_user, group: group} do
      params =
        valid_post_params()
        |> Map.put(:body, "Hello #room")

      assert {:ok, %{post: post}} = Posts.create_post(space_user, group, params)
    end

    test "subscribes the given recipients", %{space: space, space_user: space_user} do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      params =
        valid_post_params()
        |> Map.put(:body, "Hello")
        |> Map.put(:recipient_ids, [another_user.id])

      {:ok, %{post: post}} = Posts.create_post(space_user, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_user)
    end

    test "returns errors given invalid params", %{space_user: space_user, group: group} do
      params = valid_post_params() |> Map.merge(%{body: nil})
      {:error, :post, changeset, _} = Posts.create_post(space_user, group, params)

      assert %Ecto.Changeset{errors: [body: {"can't be blank", [validation: :required]}]} =
               changeset
    end
  end

  describe "create_post/2 with bot" do
    setup do
      {:ok, %{space: space} = result} = create_user_and_space()
      {:ok, %{space_user: recipient}} = create_space_member(space, %{handle: "bobby"})
      {:ok, Map.put(result, :recipient, recipient)}
    end

    test "creates a new post given valid params", %{levelbot: space_bot} do
      params = valid_post_params() |> Map.merge(%{body: "Hi @bobby"})
      {:ok, %{post: post}} = Posts.create_post(space_bot, params)
      assert post.space_bot_id == space_bot.id
      assert post.body == "Hi @bobby"
    end

    test "subscribes the recipient to the post", %{levelbot: space_bot, recipient: recipient} do
      params = valid_post_params() |> Map.merge(%{body: "Hi @bobby"})
      {:ok, %{post: post}} = Posts.create_post(space_bot, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, recipient)
    end

    test "stores the locator", %{levelbot: space_bot, recipient: recipient} do
      locator_params = %{scope: "level", topic: "welcome_message", key: recipient.id}
      params = valid_post_params() |> Map.merge(%{body: "Hi @bobby", locator: locator_params})
      {:ok, %{post: post, locator: locator}} = Posts.create_post(space_bot, params)

      assert locator.post_id == post.id
      assert locator.scope == "level"
      assert locator.topic == "welcome_message"
      assert locator.key == recipient.id
    end

    test "returns errors given invalid params", %{levelbot: space_bot} do
      params = valid_post_params() |> Map.merge(%{body: nil})
      {:error, :post, changeset, _} = Posts.create_post(space_bot, params)

      assert %Ecto.Changeset{errors: [body: {"can't be blank", [validation: :required]}]} =
               changeset
    end
  end

  describe "update_post/3" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group, %{body: "Old body"})
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "does not allow a non-author to edit", %{space: space, post: post} do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      assert {:error, :unauthorized} =
               Posts.update_post(another_user, post, %{body: "Hijacking this post!"})
    end

    test "allows the original author to edit", %{space_user: space_user, post: post} do
      {:ok, result} = Posts.update_post(space_user, post, %{body: "New body"})
      assert result.updated_post.body == "New body"
    end

    test "stores a version entry for the previous version", %{space_user: space_user, post: post} do
      {:ok, _} = Posts.update_post(space_user, post, %{body: "New body"})

      query =
        from pv in PostVersion,
          where: pv.post_id == ^post.id

      assert [%PostVersion{body: "Old body"}] = Repo.all(query)
    end

    test "logs the event", %{space_user: space_user, post: post} do
      {:ok, %{log: log}} = Posts.update_post(space_user, post, %{body: "New body"})
      assert log.event == "POST_EDITED"
      assert log.space_user_id == space_user.id
      assert log.post_id == post.id
    end
  end

  describe "subscribe/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "subscribes the user to the post", %{
      space: space,
      post: post
    } do
      {:ok, %{space_user: another_space_user}} = create_space_member(space)
      {:ok, [^post]} = Posts.subscribe(another_space_user, [post])
      assert %{subscription: "SUBSCRIBED"} = Posts.get_user_state(post, another_space_user)
    end

    test "ignores repeated subscribes", %{space_user: space_user, post: post} do
      assert %{subscription: "SUBSCRIBED"} = Posts.get_user_state(post, space_user)
      assert {:ok, [^post]} = Posts.subscribe(space_user, [post])
    end
  end

  describe "create_reply/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user, %{name: "marketing"})
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "creates a new reply given valid params", %{space_user: space_user, post: post} do
      params = valid_reply_params() |> Map.merge(%{body: "The body"})
      {:ok, %{reply: reply}} = Posts.create_reply(space_user, post, params)
      assert reply.space_user_id == space_user.id
      assert reply.body == "The body"
    end

    test "subscribes the user to the post", %{space_user: space_user, post: post} do
      {:ok, _} = Posts.unsubscribe(space_user, [post])
      params = valid_reply_params()
      {:ok, %{reply: _reply}} = Posts.create_reply(space_user, post, params)
      assert %{subscription: "SUBSCRIBED"} = Posts.get_user_state(post, space_user)
    end

    test "record mentions", %{space: space, space_user: space_user, post: post} do
      {:ok, %{space_user: %SpaceUser{id: mentioned_id}}} =
        create_space_member(space, %{handle: "tiff"})

      params = valid_reply_params() |> Map.merge(%{body: "Hey @tiff"})

      assert {:ok, %{mentions: %{space_users: [%SpaceUser{id: ^mentioned_id}]}}} =
               Posts.create_reply(space_user, post, params)
    end

    test "logs the event", %{space_user: space_user, post: post, group: group} do
      params = valid_reply_params()
      {:ok, %{reply: reply, log: log}} = Posts.create_reply(space_user, post, params)
      assert log.event == "REPLY_CREATED"
      assert log.space_user_id == space_user.id
      assert log.group_id == group.id
      assert log.post_id == post.id
      assert log.reply_id == reply.id
    end

    test "records a view", %{space_user: space_user, post: post} do
      params = valid_reply_params()
      {:ok, %{reply: reply, post_view: post_view}} = Posts.create_reply(space_user, post, params)
      assert post_view.post_id == post.id
      assert post_view.last_viewed_reply_id == reply.id
    end

    test "subscribes mentioned users and marks as unread", %{
      space: space,
      space_user: space_user,
      post: post
    } do
      {:ok, %{space_user: %SpaceUser{id: mentioned_id} = mentioned}} =
        create_space_member(space, %{handle: "tiff"})

      params = valid_reply_params() |> Map.merge(%{body: "Hey @tiff"})

      {:ok, %{mentions: %{space_users: [%SpaceUser{id: ^mentioned_id}]}}} =
        Posts.create_reply(space_user, post, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, mentioned)

      assert [%Notification{event: "REPLY_CREATED"}] = Notifications.list(mentioned, post)
    end

    test "subscribes channel watchers", %{
      space: space,
      space_user: space_user,
      post: post,
      group: group
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)
      Groups.watch(group, another_user)

      params = valid_reply_params()
      {:ok, _} = Posts.create_reply(space_user, post, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_user)
    end

    test "does not loop in mentioned people who previously did not have access", %{
      space: space,
      space_user: space_user,
      post: post,
      group: group
    } do
      {:ok, %{space_user: %SpaceUser{id: mentioned_id} = mentioned}} =
        create_space_member(space, %{handle: "tiff"})

      {:ok, _} = Groups.privatize(group)

      params = valid_post_params() |> Map.merge(%{body: "Hey @tiff"})

      {:ok, %{mentions: %{space_users: [%SpaceUser{id: ^mentioned_id}]}}} =
        Posts.create_reply(space_user, post, params)

      assert %{inbox: "EXCLUDED", subscription: "NOT_SUBSCRIBED"} =
               Posts.get_user_state(post, mentioned)
    end

    test "marks as unread for subscribers", %{space: space, space_user: space_user, post: post} do
      {:ok, %{space_user: another_subscriber}} = create_space_member(space)
      Posts.subscribe(another_subscriber, [post])
      {:ok, _} = Posts.create_reply(space_user, post, valid_reply_params())
      assert %{inbox: "UNREAD"} = Posts.get_user_state(post, another_subscriber)
    end

    test "handles channel mentions", %{
      space: space,
      space_user: space_user,
      post: post
    } do
      {:ok, %{group: %Group{id: another_group_id} = another_group}} =
        create_group(space_user, %{name: "devs"})

      {:ok, %{space_user: another_user}} = create_space_member(space)
      Groups.subscribe(another_group, another_user)

      params = valid_reply_params() |> Map.merge(%{body: "Hey @#devs"})

      assert {:ok, %{mentions: %{groups: [%Group{id: ^another_group_id}]}}} =
               Posts.create_reply(space_user, post, params)

      assert %{inbox: "UNREAD", subscription: "SUBSCRIBED"} =
               Posts.get_user_state(post, another_user)
    end

    test "attaches file uploads", %{space_user: space_user, post: post} do
      {:ok, %File{id: file_id}} = create_file(space_user)
      params = valid_reply_params() |> Map.merge(%{file_ids: [file_id]})
      {:ok, %{reply: reply}} = Posts.create_reply(space_user, post, params)

      assert [%File{id: ^file_id}] =
               reply
               |> Ecto.assoc(:files)
               |> Repo.all()
    end

    test "returns errors given invalid params", %{space_user: space_user, post: post} do
      params = valid_reply_params() |> Map.merge(%{body: nil})
      {:error, :reply, changeset, _} = Posts.create_reply(space_user, post, params)

      assert %Ecto.Changeset{errors: [body: {"can't be blank", [validation: :required]}]} =
               changeset
    end

    test "marks the reply as viewed by the author", %{space_user: space_user, post: post} do
      {:ok, %{reply: reply}} = Posts.create_reply(space_user, post, valid_reply_params())
      assert Posts.viewed_reply?(reply, space_user)
    end
  end

  describe "record_view/3" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "creates a post view record with last viewed reply", %{
      space_user: space_user,
      post: post
    } do
      {:ok, %{reply: %Reply{id: reply_id} = reply}} = create_reply(space_user, post)

      assert {:ok, %PostView{last_viewed_reply_id: ^reply_id}} =
               Posts.record_view(post, space_user, reply)
    end
  end

  describe "record_view/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "creates a post view record with null last viewed reply", %{
      space_user: space_user,
      post: post
    } do
      assert {:ok, %PostView{last_viewed_reply_id: nil}} = Posts.record_view(post, space_user)
    end
  end

  describe "record_reply_views/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "marks the replies as read for the given user", %{
      space: space,
      space_user: space_user,
      post: post
    } do
      {:ok, %{reply: reply}} = create_reply(space_user, post)
      {:ok, %{reply: another_reply}} = create_reply(space_user, post)
      {:ok, %{space_user: another_member}} = create_space_member(space)

      refute Posts.viewed_reply?(reply, another_member)
      refute Posts.viewed_reply?(another_reply, another_member)

      {:ok, returned_replies} = Posts.record_reply_views(another_member, [reply, another_reply])

      assert Posts.viewed_reply?(reply, another_member)
      assert Posts.viewed_reply?(another_reply, another_member)
      assert returned_replies == [reply, another_reply]
    end
  end

  describe "render_body/1" do
    setup do
      {:ok, %{viewer: %User{handle: "derrick"}}}
    end

    test "converts markdown to html", %{viewer: viewer} do
      assert Posts.render_body("Foo", viewer) == {:ok, "<p>Foo</p>"}
    end

    test "emboldens mentions", %{viewer: viewer} do
      assert Posts.render_body("@tiff Hey", %{user: viewer}) ==
               {:ok, "<p><span><span class=\"user-mention\">@tiff</span> Hey</span></p>"}

      assert Posts.render_body("@derrick Hey", %{user: viewer}) ==
               {:ok,
                "<p><span><span class=\"user-mention user-mention-current\">@derrick</span> Hey</span></p>"}
    end
  end

  describe "attach_files/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "attaches the given uploads to the post", %{space_user: space_user, post: post} do
      {:ok, %File{id: file_id} = upload} = create_file(space_user)
      {:ok, [%File{id: ^file_id}]} = Posts.attach_files(post, [upload])

      assert [%File{id: ^file_id}] =
               post
               |> Ecto.assoc(:files)
               |> Repo.all()
    end
  end

  describe "close_post/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "marks the post as closed", %{post: post, space_user: space_user} do
      assert post.state == "OPEN"
      {:ok, %{post: closed_post}} = Posts.close_post(space_user, post)
      assert closed_post.id == post.id
      assert closed_post.state == "CLOSED"
    end

    test "dismissed the post from the closer's inbox and records notifications", %{
      space: space,
      post: post,
      space_user: space_user
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      {:ok, _} = Posts.subscribe(space_user, [post])
      {:ok, _} = Posts.subscribe(another_user, [post])

      {:ok, _} = Posts.mark_as_unread(space_user, [post])
      {:ok, _} = Posts.mark_as_unread(another_user, [post])

      {:ok, _} = Posts.close_post(space_user, post)

      assert %{inbox: "DISMISSED"} = Posts.get_user_state(post, space_user)
      assert %{inbox: "UNREAD"} = Posts.get_user_state(post, another_user)

      assert [] = Notifications.list(space_user, post)
      assert [%Notification{event: "POST_CLOSED"}] = Notifications.list(another_user, post)
    end
  end

  describe "reopen_post/2" do
    setup do
      {:ok, %{space_user: space_user} = result} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, Map.merge(result, %{group: group, post: post})}
    end

    test "marks the post as closed", %{post: post, space_user: space_user} do
      {:ok, %{post: closed_post}} = Posts.close_post(space_user, post)
      {:ok, %{post: reopened_post}} = Posts.reopen_post(space_user, closed_post)

      assert reopened_post.id == post.id
      assert reopened_post.state == "OPEN"
    end

    test "records notifications", %{
      space: space,
      post: post,
      space_user: space_user
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)
      {:ok, _} = Posts.subscribe(another_user, [post])
      {:ok, _} = Posts.close_post(space_user, post)
      {:ok, _} = Posts.reopen_post(space_user, post)

      assert Enum.any?(Notifications.list(another_user, post), fn notification ->
               notification.event == "POST_REOPENED"
             end)
    end
  end

  describe "mark_as_read/2" do
    test "sets the inbox state to read" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)

      Notifications.record_post_created(space_user, post)
      assert %{inbox: "EXCLUDED"} = Posts.get_user_state(post, space_user)

      Posts.mark_as_read(space_user, [post])
      assert %{inbox: "READ"} = Posts.get_user_state(post, space_user)
    end
  end

  describe "create_post_reaction/2" do
    test "creates a reaction and handles duplicates" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)

      {:ok, _} = Posts.create_post_reaction(space_user, post, "👍")

      assert Repo.get_by(PostLog,
               space_user_id: space_user.id,
               post_id: post.id,
               event: "POST_REACTION_CREATED"
             )

      # Duplicate reaction
      space_user_id = space_user.id
      post_id = post.id

      assert {:ok, %PostReaction{space_user_id: ^space_user_id, post_id: ^post_id}} =
               Posts.create_post_reaction(space_user, post, "👍")
    end

    test "records a notification for all subscribers" do
      {:ok, %{space_user: reactor, space: space}} = create_user_and_space()
      {:ok, %{space_user: author}} = create_space_member(space)
      {:ok, %{group: group}} = create_group(reactor)
      {:ok, %{post: post}} = create_post(author, group)

      {:ok, _} = Posts.create_post_reaction(reactor, post, "👍")

      # Does not record a notification for the reactor
      refute Enum.any?(Notifications.list(reactor, post), fn notification ->
               notification.event == "POST_REACTION_CREATED"
             end)

      assert Enum.any?(Notifications.list(author, post), fn notification ->
               notification.event == "POST_REACTION_CREATED"
             end)
    end
  end

  describe "delete_post_reaction/2" do
    test "deletes the reaction if one exists" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, reaction} = Posts.create_post_reaction(space_user, post, "👍")
      {:ok, deleted_reaction} = Posts.delete_post_reaction(space_user, post, "👍")
      assert deleted_reaction.id == reaction.id
    end

    test "returns an error if the user had not reacted" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)

      {:error, "Reaction not found"} = Posts.delete_post_reaction(space_user, post, "👍")
    end
  end

  describe "create_reply_reaction/2" do
    test "creates a reaction and handles duplicates" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, %{reply: reply}} = create_reply(space_user, post)

      {:ok, _} = Posts.create_reply_reaction(space_user, post, reply, "👍")

      assert Repo.get_by(PostLog,
               space_user_id: space_user.id,
               post_id: post.id,
               reply_id: reply.id,
               event: "REPLY_REACTION_CREATED"
             )

      # Duplicate reaction
      space_user_id = space_user.id
      reply_id = reply.id

      assert {:ok, %ReplyReaction{space_user_id: ^space_user_id, reply_id: ^reply_id}} =
               Posts.create_reply_reaction(space_user, post, reply, "👍")
    end

    test "records a notification for the reply author" do
      {:ok, %{space_user: reactor, space: space}} = create_user_and_space()
      {:ok, %{space_user: author}} = create_space_member(space)
      {:ok, %{group: group}} = create_group(reactor)
      {:ok, %{post: post}} = create_post(reactor, group)
      {:ok, %{reply: reply}} = create_reply(author, post)

      {:ok, _} = Posts.create_reply_reaction(reactor, post, reply, "👍")

      # Does not record a notification for the reactor
      refute Enum.any?(Notifications.list(reactor, post), fn notification ->
               notification.event == "REPLY_REACTION_CREATED"
             end)

      assert Enum.any?(Notifications.list(author, post), fn notification ->
               notification.event == "REPLY_REACTION_CREATED"
             end)
    end
  end

  describe "delete_reply_reaction/2" do
    test "deletes the reaction if one exists" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, %{reply: reply}} = create_reply(space_user, post)

      {:ok, reaction} = Posts.create_reply_reaction(space_user, post, reply, "👍")

      {:ok, deleted_reaction} = Posts.delete_reply_reaction(space_user, reply, "👍")
      assert deleted_reaction.id == reaction.id
    end

    test "returns an error if the user had not reacted" do
      {:ok, %{space_user: space_user}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, %{reply: reply}} = create_reply(space_user, post)

      {:error, "Reaction not found"} = Posts.delete_reply_reaction(space_user, reply, "👍")
    end
  end

  describe "private?/1" do
    test "returns true if a post is a DM" do
      {:ok, %{space_user: author, space: space}} = create_user_and_space()
      {:ok, %{space_user: _}} = create_space_member(space, %{handle: "tiff"})
      {:ok, %{post: post}} = create_global_post(author, %{body: "Hey @tiff"})

      assert {:ok, true} = Posts.private?(post)
    end

    test "returns true if a post belongs to private groups only" do
      {:ok, %{space_user: author}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(author, %{is_private: true})
      {:ok, %{post: post}} = create_post(author, group)

      assert {:ok, true} = Posts.private?(post)
    end

    test "returns false if a post belongs to a public group" do
      {:ok, %{space_user: author}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(author, %{is_private: false})
      {:ok, %{post: post}} = create_post(author, group)

      assert {:ok, false} = Posts.private?(post)
    end
  end

  describe "get_accessor_ids/1" do
    setup do
      {:ok, %{space_user: space_user, space: space}} = create_user_and_space()
      {:ok, %{group: group}} = create_group(space_user)
      {:ok, %{post: post}} = create_post(space_user, group)
      {:ok, %{space_user: space_user, space: space, group: group, post: post}}
    end

    test "excludes users who are not subscribed when post is private", %{
      space: space,
      group: group,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      Groups.privatize(group)

      {:ok, ids} = Posts.get_accessor_ids(post)
      refute Enum.any?(ids, fn id -> id == another_user.id end)
    end

    test "includes users who are subscribed to groups the post is in", %{
      space: space,
      group: group,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      Groups.subscribe(group, another_user)

      {:ok, ids} = Posts.get_accessor_ids(post)
      assert Enum.any?(ids, fn id -> id == another_user.id end)
    end

    test "includes users who are watching groups the post is in", %{
      space: space,
      group: group,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      Groups.watch(group, another_user)

      {:ok, ids} = Posts.get_accessor_ids(post)
      assert Enum.any?(ids, fn id -> id == another_user.id end)
    end

    test "includes users who are not subscribed to groups", %{
      space: space,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      {:ok, ids} = Posts.get_accessor_ids(post)
      assert Enum.any?(ids, fn id -> id == another_user.id end)
    end

    test "includes users who are directly subscribed", %{
      space: space,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      Posts.mark_as_unread(another_user, [post])

      {:ok, ids} = Posts.get_accessor_ids(post)
      assert Enum.any?(ids, fn id -> id == another_user.id end)
    end

    test "includes users who have unsubscribed from a group", %{
      space: space,
      group: group,
      post: post
    } do
      {:ok, %{space_user: another_user}} = create_space_member(space)

      Groups.subscribe(group, another_user)
      Groups.unsubscribe(group, another_user)

      {:ok, ids} = Posts.get_accessor_ids(post)
      assert Enum.any?(ids, fn id -> id == another_user.id end)
    end
  end
end

{'repo_name': 'unstacked/level', 'stars': '993', 'repo_language': 'Elm', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -494127243529112882, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.tomcat.websocket;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.servlet.ServletContextEvent;
import javax.websocket.DeploymentException;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;

import org.apache.tomcat.websocket.server.Constants;
import org.apache.tomcat.websocket.server.WsContextListener;

public class TesterEchoServer {

    public static class Config extends WsContextListener {

        public static final String PATH_ASYNC = "/echoAsync";
        public static final String PATH_BASIC = "/echoBasic";
        public static final String PATH_BASIC_LIMIT_LOW = "/echoBasicLimitLow";
        public static final String PATH_BASIC_LIMIT_HIGH = "/echoBasicLimitHigh";

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            super.contextInitialized(sce);
            ServerContainer sc =
                    (ServerContainer) sce.getServletContext().getAttribute(
                            Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
            try {
                sc.addEndpoint(Async.class);
                sc.addEndpoint(Basic.class);
                sc.addEndpoint(BasicLimitLow.class);
                sc.addEndpoint(BasicLimitHigh.class);
            } catch (DeploymentException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    @ServerEndpoint("/echoAsync")
    public static class Async {

        @OnMessage
        public void echoTextMessage(Session session, String msg, boolean last) {
            try {
                session.getBasicRemote().sendText(msg, last);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }

        @OnMessage
        public void echoBinaryMessage(Session session, ByteBuffer msg,
                boolean last) {
            try {
                session.getBasicRemote().sendBinary(msg, last);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

    @ServerEndpoint("/echoBasic")
    public static class Basic {
        @OnMessage
        public void echoTextMessage(Session session, String msg) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }

        @OnMessage
        public void echoBinaryMessage(Session session, ByteBuffer msg) {
            try {
                session.getBasicRemote().sendBinary(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

    @ServerEndpoint("/echoBasicLimitLow")
    public static class BasicLimitLow {

        public static final long MAX_SIZE = 10;

        @OnMessage(maxMessageSize = MAX_SIZE)
        public void echoTextMessage(Session session, String msg) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }

        @OnMessage(maxMessageSize = MAX_SIZE)
        public void echoBinaryMessage(Session session, ByteBuffer msg) {
            try {
                session.getBasicRemote().sendBinary(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

    @ServerEndpoint("/echoBasicLimitHigh")
    public static class BasicLimitHigh {

        public static final long MAX_SIZE = 32 * 1024;

        @OnMessage(maxMessageSize = MAX_SIZE)
        public void echoTextMessage(Session session, String msg) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }

        @OnMessage(maxMessageSize = MAX_SIZE)
        public void echoBinaryMessage(Session session, ByteBuffer msg) {
            try {
                session.getBasicRemote().sendBinary(msg);
            } catch (IOException e) {
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

}

{'repo_name': 'codefollower/Tomcat-Research', 'stars': '327', 'repo_language': 'Java', 'file_name': 'context.xml', 'mime_type': 'text/xml', 'hash': -1274076767421928512, 'source_dataset': 'data'}


syntax = "proto2";
import "opera/scope/scope_descriptor.proto";

package scope;

option optimize_for         = SPEED;
option java_outer_classname = "WmProtos";
option java_package         = "com.opera.core.systems.scope.protos";

/**
 * TODO: We probably want a lot more information about each window, like URL, shortcut
 *       icon, etc.
 */
message WindowInfo
{
    required uint32 windowID      = 1;
    required string title         = 2;
    /**
     *
     * TODO: Some of these are obsolete, like "ad". Figure out which ones should really be present.
     *
     * Type is one of:
     * - "normal"
     * - "download"
     * - "cache"
     * - "plugins"
     * - "history"
     * - "help"
     * - "mail_view"
     * - "mail_compose"
     * - "newsfeed_view"
     * - "ad"
     * - "im_view"
     * - "p2p_view"
     * - "brand_view"
     * - "print_selection"
     * - "js_console"
     * - "gadget"
     * - "controller"
     * - "info"
     * - "dialog"
     * - "thumbnail"
     * - "normal_hidden"
     * - "devtools"
     */
    required string windowType    = 3;
    /**
     * The `window-id` of the window who opened the window in question,
     * or 0 if it was not opened by another window.
     */
    required uint32 openerID      = 4;
    /**
     * The name of the extension if window type is 'gadget'.
     *
     * @since 2.2
     */
    optional string extensionName = 5;
    /**
     * true if the window is in Privacy Mode.
     * @since 2.3
     */
    optional bool   isPrivate     = 6;
}

message WindowID
{
    required uint32 windowID = 1;
}

message WindowFilter
{
    required bool   clearFilter        = 1 [default = false];
    repeated uint32 includeIDList      = 2;
    /**
     * The string can currently only have one value: `"*"`, meaing all window-ids.
     * The filter automatically includes windows that are opened from windows
     * in the INCLUDE filter.
     */
    repeated string includePatternList = 3;
    repeated uint32 excludeIDList      = 4;
    repeated string excludePatternList = 5;
}

message WindowList
{
    repeated WindowInfo windowList = 1;
}

message CreateWindowArg
{
    /**
     * Type is one of:
     * - "normal"
     * - "download"
     * - "cache"
     * - "plugins"
     * - "history"
     * - "help"
     * - "mail_view"
     * - "mail_compose"
     * - "newsfeed_view"
     * - "ad"
     * - "im_view"
     * - "p2p_view"
     * - "brand_view"
     * - "print_selection"
     * - "js_console"
     * - "gadget"
     * - "controller"
     * - "info"
     * - "dialog"
     * - "thumbnail"
     * - "normal_hidden"
     * - "devtools"
     */
    optional string windowType = 1;
    /**
     * If set then it forces Privacy Mode of a window
     * else the default setting will be used.
     * @since 2.3
     */
    optional bool   isPrivate  = 2;
}

message CloseWindowArg
{
    /**
     * Close window with the specified ID. If a window with that ID does
     * not exist, an error is returned.
     */
    required uint32 windowID = 1;
}

message OpenURLArg
{
    /**
     * Start loading the URL in this Window.
     */
    required uint32 windowID = 1;
    /**
     * The URL to load.
     */
    required string url      = 2;
}

message ModifyTypeFilterArg
{
    /**
     * Possible values:
     *
     *  - "replace" clears the current filter, and replaces it with the input values.
     *  - "append" adds the input values to the current filter. It is acceptable to
     *    add a value already present in the filter (silent fail).
     *  - "default" resets the filter to its defaults. The input values are ignored.
     *    The default is ["normal_hidden", "devtools"].
     */
    required string mode     = 2;
    /**
     * A list of window types to exclude. For valid window types, see CreateWindowArg.
     */
    repeated string typeList = 1;
}

{'repo_name': 'operasoftware/operaprestodriver', 'stars': '140', 'repo_language': 'Java', 'file_name': 'org.eclipse.jdt.ui.prefs', 'mime_type': 'text/plain', 'hash': 8208813967426020997, 'source_dataset': 'data'}


/***************************************************************************
 *                   (C) Copyright 2003-2012 - Stendhal                    *
 ***************************************************************************
 ***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
package games.stendhal.client.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * A component for drawing the various color bars.
 */
public class StatusDisplayBar extends JComponent {
	/** Preferred height of the bar. */
	private static final int PREFERRED_HEIGHT = 10;
	/** Value model. */
	private final ScalingModel model;
	/** Default bar color. */
	private Color color = Color.WHITE;
	/** Painter, or null if a plain color bar is used. */
	private BarPainter painter;
	/**
	 * Image of a full color bar, or null if a plain color bar
	 * is used.
	 */
	private BufferedImage barImage;

	/**
	 * Create a StatusDisplayBar.
	 *
	 * @param model Scaling model. representation corresponds to the length
	 *	of the color bar. The StatusDisplayBar will take care of the maximum
	 *	representation value
	 */
	public StatusDisplayBar(final ScalingModel model) {
		this.model = model;
		setForeground(Color.BLACK);
		setBackground(Color.BLACK);
		model.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				valueChanged();
			}
		});
		this.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				Insets insets = getInsets();
				int barWidth = getWidth() - insets.left - insets.right - 2;
				if (painter != null && barWidth > 0) {
					int barHeight = getHeight() - insets.top - insets.bottom;
					if (barHeight > 0) {
						barImage = getGraphicsConfiguration().createCompatibleImage(barWidth, barHeight);
						Graphics2D g = barImage.createGraphics();
						painter.paint(g, barWidth, barHeight);
						g.dispose();
					}
					// Otherwise we can just keep the old image. It does not get
					// painted anyway
				}
				model.setMaxRepresentation(barWidth);
			}
		});
		setPreferredSize(new Dimension(2, PREFERRED_HEIGHT));
		setMinimumSize(getPreferredSize());
	}

	/**
	 * Return the value scaling model in use.
	 *
	 * @return model
	 */
	public ScalingModel getModel() {
		return model;
	}

	/**
	 * Set the color of the bar.
	 *
	 * @param color new color
	 */
	public void setBarColor(Color color) {
		this.color = color;
	}

	/**
	 * Set painter for fancy colored bars.
	 *
	 * @param painter painter for coloring the template image
	 */
	protected void setPainter(BarPainter painter) {
		this.painter = painter;
	}

	/**
	 * Called when the model value changes.
	 */
	protected void valueChanged() {
		repaint();
	}

	@Override
	public void paintComponent(Graphics g) {
		Insets insets = getInsets();
		int barHeight = getHeight() - insets.top - insets.bottom - 2;
		// Paint frame
		g.setColor(getForeground());
		g.drawRect(insets.left, insets.top, getWidth() - insets.left - insets.right - 1,
				getHeight() - insets.top - insets.bottom - 1);
		// Paint what is not covered by the colored bar
		g.setColor(getBackground());
		g.fillRect(insets.left + 1, insets.top + 1, getWidth() - insets.left - insets.right - 2,
				barHeight);

		if (barImage != null) {
			Graphics clipped = g.create(insets.left + 1, insets.top + 1, model.getRepresentation(), barHeight);
			clipped.drawImage(barImage, 0, 0, null);
			clipped.dispose();
		} else {
			g.setColor(color);
			g.fillRect(insets.left + 1, insets.top + 1, model.getRepresentation(), barHeight);
		}
	}

	/**
	 * Interface for bars that need more complicated drawing than a simple color
	 * bar.
	 */
	public interface BarPainter {
		/**
		 * Fill an area corresponding to a full bar.
		 *
		 * @param g graphics
		 * @param width width of the area
		 * @param height height of the area
		 */
		void paint(Graphics2D g, int width, int height);
	}
}

{'repo_name': 'arianne/stendhal', 'stars': '159', 'repo_language': 'Java', 'file_name': 'light.xml', 'mime_type': 'text/xml', 'hash': 1348834046893703754, 'source_dataset': 'data'}


// Package polyfit models a polynomial y from sample points xs and ys, to minimizes the squared residuals.
//
// See https://en.wikipedia.org/wiki/Least_squares#Linear_least_squares
//
// Since 0.5.4
package polyfit

import (
	"fmt"
	"strings"

	"gonum.org/v1/gonum/mat"
)

// Fitting models a polynomial y from sample points xs and ys, to minimizes the squared residuals.
// It returns coefficients of the polynomial y:
//
//    y = β₁ + β₂x + β₃x² + ...
//
// It use linear regression, which assumes y is in form of:
//        m
//    y = ∑ βⱼ Φⱼ(x)
//        j=1
//
// In our case:
//    Φⱼ(x) = x^(j-1)
//
// Then
//    (Xᵀ × X) βⱼ = Xᵀ × Y
//    Xᵢⱼ = [ Φⱼ(xᵢ) ]
//
// See https://en.wikipedia.org/wiki/Least_squares#Linear_least_squares
//
// Since 0.5.4
type Fitting struct {
	N      int
	Degree int

	// cache Xᵀ X
	xtx []float64
	// cache Xᵀ Y
	xty []float64
}

// NewFitting creates a new polynomial fitting context.
//
// Since 0.5.4
func NewFitting(xs, ys []float64, degree int) *Fitting {

	n := len(xs)

	m := degree + 1

	f := &Fitting{
		N:      0,
		Degree: degree,

		xtx: make([]float64, m*m),
		xty: make([]float64, m),
	}

	for i := 0; i < m*m; i++ {
		f.xtx[i] = 0
	}

	for i := 0; i < m; i++ {
		f.xty[i] = 0
	}

	for i := 0; i < n; i++ {
		f.Add(xs[i], ys[i])
	}

	return f
}

// Add a point(x, y) into this fitting.
//
// Since 0.5.4
func (f *Fitting) Add(x, y float64) {

	m := f.Degree + 1

	xpows := make([]float64, m)
	v := float64(1)
	for i := 0; i < m; i++ {
		xpows[i] = v
		v *= x
	}

	for i := 0; i < m; i++ {
		for j := 0; j < m; j++ {
			f.xtx[i*m+j] += xpows[i] * xpows[j]
		}
	}

	for i := 0; i < m; i++ {
		f.xty[i] += xpows[i] * y
	}

	f.N++
}

// Merge Combines two sets of sample data.
//
// This can be done because:
//    |X₁|ᵀ × |X₁| = X₁ᵀ × X₁ + X₂ᵀ × X₂
//    |X₂|    |X₂|
//
// Since 0.5.4
func (f *Fitting) Merge(b *Fitting) {

	if f.Degree != b.Degree {
		panic(fmt.Sprintf("different degree: %d %d", f.Degree, b.Degree))
	}

	f.N += b.N

	m := f.Degree + 1

	for i := 0; i < m; i++ {
		f.xty[i] += b.xty[i]
		for j := 0; j < m; j++ {
			f.xtx[i*m+j] += b.xtx[i*m+j]
		}
	}
}

// Solve the equation and returns coefficients of result polynomial.
// The number of coefficients is f.Degree + 1.
//
// Since 0.5.4
func (f *Fitting) Solve(minimizeDegree bool) []float64 {

	m := f.Degree + 1

	coef := mat.NewDense(m, m, f.xtx)
	right := mat.NewDense(m, 1, f.xty)

	if minimizeDegree && f.Degree+1 > f.N {

		m = f.N

		coef = coef.Slice(0, m, 0, m).(*mat.Dense)
		right = right.Slice(0, m, 0, 1).(*mat.Dense)
	}

	var beta mat.Dense
	beta.Solve(coef, right)

	rst := make([]float64, f.Degree+1)
	for i := 0; i < m; i++ {
		rst[i] = beta.At(i, 0)
	}

	for i := m; i < f.Degree+1; i++ {
		rst[i] = 0
	}

	return rst
}

// String prints human readable info of a fitting.
// It includes:
// n: the number of points.
// degree: expected degree of polynomial.
// and two matrix.
//
// Since 0.5.4
func (f *Fitting) String() string {

	m := f.Degree + 1
	ss := []string{}

	xtx := f.matrixStrings(f.xtx)

	ss = append(ss, fmt.Sprintf("n=%d degree=%d", f.N, f.Degree))
	ss = append(ss, xtx...)
	ss = append(ss, "")
	for i := 0; i < m; i++ {
		s := fmt.Sprintf("%3.3f", f.xty[i])
		ss = append(ss, s)
	}
	return strings.Join(ss, "\n")
}

func (f *Fitting) matrixStrings(mat []float64) []string {

	m := f.Degree + 1

	ss := []string{}

	for i := 0; i < m; i++ {
		line := []string{}
		for j := 0; j < m; j++ {
			s := fmt.Sprintf("%3.3f", mat[i*m+j])
			line = append(line, s)
		}

		linestr := strings.Join(line, " ")
		ss = append(ss, linestr)
	}

	return ss
}

{'repo_name': 'openacid/slim', 'stars': '1416', 'repo_language': 'Go', 'file_name': 'makedata.go', 'mime_type': 'text/x-c', 'hash': 1440470910262531225, 'source_dataset': 'data'}


#!/bin/bash
# Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE.md file.

# This program runs the Dartino VM in a virtual terminal controlled by the
# program "screen". It then attaches to the VM using the given command-line
# arguments. Normal usage would be something like:
#
#  ./tools/spawn_vm_and_attach.sh out/DebugIA32Clang/dartino in session SESSION_NAME
#
# This is a tool that's intended for people building the Dartino VM. If you find
# yourself using this to run Dartino on a regular basis, please get in touch
# with the authors and let us know why. If you're unsure about how to reach the
# authors, you're welcome to file an issue at
# https://github.com/dartino/sdk/issues/new.

dartino="${1}"
shift
if [ ! -x "${dartino}" ]; then
  echo 1>&2 Usage: "$0" PATH_TO_DARTINO_EXECUTABLE
  exit 1
fi

# Make all errors fatal
set -e

# Create a FIFO file (aka named pipe)
fifo=$(mktemp -u -t fifo)
mkfifo "${fifo}"

# Launch the Dartino VM in a detached screen session, and duplicate its output
# to the FIFO (using script)
screen -L -d -m script -t 0 -q -a "${fifo}" "${dartino}-vm"

# Wait for the first line of output from the VM
tcp_socket=$(head -1 "${fifo}" | sed 's/^Waiting for compiler on //')

# We're done with the FIFO
rm "${fifo}"

# Attach to the VM
exec "${dartino}" attach tcp_socket "${tcp_socket}" "$@"

{'repo_name': 'dartino/sdk', 'stars': '313', 'repo_language': 'Dart', 'file_name': 'README', 'mime_type': 'text/plain', 'hash': -4178701273177706176, 'source_dataset': 'data'}


/*
 * Copyright Amazon.com, Inc. or its affiliates. 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.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file 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.
 */

package software.amazon.awssdk.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * The class to which this annotation is applied is not thread-safe.
 * This annotation primarily exists for clarifying the non-thread-safety of a class
 * that might otherwise be assumed to be thread-safe, despite the fact that it is a bad
 * idea to assume a class is thread-safe without good reason.
 * <p>
 * Based on code developed by Brian Goetz and Tim Peierls and concepts
 * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls,
 * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea.
 *
 * @see ThreadSafe
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME
@SdkProtectedApi
public @interface NotThreadSafe {
}

{'repo_name': 'aws/aws-sdk-java-v2', 'stars': '890', 'repo_language': 'Java', 'file_name': 'AppTest.java', 'mime_type': 'text/x-java', 'hash': -1027272034958063417, 'source_dataset': 'data'}


/**
 *
 * WARNING! This file was autogenerated by:
 *  _   _ _   _ __   __
 * | | | | | | |\ \ / /
 * | | | | |_| | \ V /
 * | | | |  _  | /   \
 * | |_| | | | |/ /^\ \
 *  \___/\_| |_/\/   \/
 *
 * This file was autogenerated by UnrealHxGenerator using UHT definitions.
 * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
 * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal;

@:glueCppIncludes("Classes/Engine/EngineTypes.h")
@:uname("ENetDormancy")
@:uextern @:uenum extern enum ENetDormancy {

  /**
    This actor can never go network dormant.
    @DisplayName Never
  **/
  @DisplayName("Never")
  DORM_Never;

  /**
    This actor can go dormant, but is not currently dormant. Game code will tell it when it go dormant.
    @DisplayName Awake
  **/
  @DisplayName("Awake")
  DORM_Awake;

  /**
    This actor wants to go fully dormant for all connections.
    @DisplayName Dormant All
  **/
  @DisplayName("Dormant All")
  DORM_DormantAll;

  /**
    This actor may want to go dormant for some connections, GetNetDormancy() will be called to find out which.
    @DisplayName Dormant Partial
  **/
  @DisplayName("Dormant Partial")
  DORM_DormantPartial;

  /**
    This actor is initially dormant for all connection if it was placed in map.
    @DisplayName Initial
  **/
  @DisplayName("Initial")
  DORM_Initial;
  DORM_MAX;

}

{'repo_name': 'proletariatgames/unreal.hx', 'stars': '332', 'repo_language': 'Haxe', 'file_name': 'EngineLatentCommands.hx', 'mime_type': 'text/x-c++', 'hash': -7965246578727824886, 'source_dataset': 'data'}


mod constants;

mod writer;
pub use writer::Writer;

mod reader;
pub use reader::{RawTag, Reader};

mod term;
pub use term::Term;

mod encoder;
pub use encoder::{Encoder, List, A};

mod decoder;
pub use decoder::Decoder;

#[cfg(test)]
mod test;

{'repo_name': 'eirproject/eir', 'stars': '226', 'repo_language': 'Rust', 'file_name': 'tests.rs', 'mime_type': 'text/plain', 'hash': -8314236876335872945, 'source_dataset': 'data'}


/**
 * socket.io
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

(function (exports, global) {

  /**
   * Utilities namespace.
   *
   * @namespace
   */

  var util = exports.util = {};

  /**
   * Parses an URI
   *
   * @author Steven Levithan <stevenlevithan.com> (MIT license)
   * @api public
   */

  var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

  var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
               'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
               'anchor'];

  util.parseUri = function (str) {
    var m = re.exec(str || '')
      , uri = {}
      , i = 14;

    while (i--) {
      uri[parts[i]] = m[i] || '';
    }

    return uri;
  };

  /**
   * Produces a unique url that identifies a Socket.IO connection.
   *
   * @param {Object} uri
   * @api public
   */

  util.uniqueUri = function (uri) {
    var protocol = uri.protocol
      , host = uri.host
      , port = uri.port;

    if ('document' in global) {
      host = host || document.domain;
      port = port || (protocol == 'https'
        && document.location.protocol !== 'https:' ? 443 : document.location.port);
    } else {
      host = host || 'localhost';

      if (!port && protocol == 'https') {
        port = 443;
      }
    }

    return (protocol || 'http') + '://' + host + ':' + (port || 80);
  };

  /**
   * Mergest 2 query strings in to once unique query string
   *
   * @param {String} base
   * @param {String} addition
   * @api public
   */

  util.query = function (base, addition) {
    var query = util.chunkQuery(base || '')
      , components = [];

    util.merge(query, util.chunkQuery(addition || ''));
    for (var part in query) {
      if (query.hasOwnProperty(part)) {
        components.push(part + '=' + query[part]);
      }
    }

    return components.length ? '?' + components.join('&') : '';
  };

  /**
   * Transforms a querystring in to an object
   *
   * @param {String} qs
   * @api public
   */

  util.chunkQuery = function (qs) {
    var query = {}
      , params = qs.split('&')
      , i = 0
      , l = params.length
      , kv;

    for (; i < l; ++i) {
      kv = params[i].split('=');
      if (kv[0]) {
        query[kv[0]] = kv[1];
      }
    }

    return query;
  };

  /**
   * Executes the given function when the page is loaded.
   *
   *     io.util.load(function () { console.log('page loaded'); });
   *
   * @param {Function} fn
   * @api public
   */

  var pageLoaded = false;

  util.load = function (fn) {
    if ('document' in global && document.readyState === 'complete' || pageLoaded) {
      return fn();
    }

    util.on(global, 'load', fn, false);
  };

  /**
   * Adds an event.
   *
   * @api private
   */

  util.on = function (element, event, fn, capture) {
    if (element.attachEvent) {
      element.attachEvent('on' + event, fn);
    } else if (element.addEventListener) {
      element.addEventListener(event, fn, capture);
    }
  };

  /**
   * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
   *
   * @param {Boolean} [xdomain] Create a request that can be used cross domain.
   * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
   * @api private
   */

  util.request = function (xdomain) {
    // if node
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    return new XMLHttpRequest();
    // end node

    if (xdomain && 'undefined' != typeof XDomainRequest && !util.ua.hasCORS) {
      return new XDomainRequest();
    }

    if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
      return new XMLHttpRequest();
    }

    if (!xdomain) {
      try {
        return new ActiveXObject('Microsoft.XMLHTTP');
      } catch(e) { }
    }

    return null;
  };

  /**
   * XHR based transport constructor.
   *
   * @constructor
   * @api public
   */

  /**
   * Change the internal pageLoaded value.
   */

  if ('undefined' != typeof window) {
    util.load(function () {
      pageLoaded = true;
    });
  }

  /**
   * Defers a function to ensure a spinner is not displayed by the browser
   *
   * @param {Function} fn
   * @api public
   */

  util.defer = function (fn) {
    if (!util.ua.webkit || 'undefined' != typeof importScripts) {
      return fn();
    }

    util.load(function () {
      setTimeout(fn, 100);
    });
  };

  /**
   * Merges two objects.
   *
   * @api public
   */

  util.merge = function merge (target, additional, deep, lastseen) {
    var seen = lastseen || []
      , depth = typeof deep == 'undefined' ? 2 : deep
      , prop;

    for (prop in additional) {
      if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
        if (typeof target[prop] !== 'object' || !depth) {
          target[prop] = additional[prop];
          seen.push(additional[prop]);
        } else {
          util.merge(target[prop], additional[prop], depth - 1, seen);
        }
      }
    }

    return target;
  };

  /**
   * Merges prototypes from objects
   *
   * @api public
   */

  util.mixin = function (ctor, ctor2) {
    util.merge(ctor.prototype, ctor2.prototype);
  };

  /**
   * Shortcut for prototypical and static inheritance.
   *
   * @api private
   */

  util.inherit = function (ctor, ctor2) {
    function f() {};
    f.prototype = ctor2.prototype;
    ctor.prototype = new f;
  };

  /**
   * Checks if the given object is an Array.
   *
   *     io.util.isArray([]); // true
   *     io.util.isArray({}); // false
   *
   * @param Object obj
   * @api public
   */

  util.isArray = Array.isArray || function (obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  };

  /**
   * Intersects values of two arrays into a third
   *
   * @api public
   */

  util.intersect = function (arr, arr2) {
    var ret = []
      , longest = arr.length > arr2.length ? arr : arr2
      , shortest = arr.length > arr2.length ? arr2 : arr;

    for (var i = 0, l = shortest.length; i < l; i++) {
      if (~util.indexOf(longest, shortest[i]))
        ret.push(shortest[i]);
    }

    return ret;
  };

  /**
   * Array indexOf compatibility.
   *
   * @see bit.ly/a5Dxa2
   * @api public
   */

  util.indexOf = function (arr, o, i) {

    for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
         i < j && arr[i] !== o; i++) {}

    return j <= i ? -1 : i;
  };

  /**
   * Converts enumerables to array.
   *
   * @api public
   */

  util.toArray = function (enu) {
    var arr = [];

    for (var i = 0, l = enu.length; i < l; i++)
      arr.push(enu[i]);

    return arr;
  };

  /**
   * UA / engines detection namespace.
   *
   * @namespace
   */

  util.ua = {};

  /**
   * Whether the UA supports CORS for XHR.
   *
   * @api public
   */

  util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
    try {
      var a = new XMLHttpRequest();
    } catch (e) {
      return false;
    }

    return a.withCredentials != undefined;
  })();

  /**
   * Detect webkit.
   *
   * @api public
   */

  util.ua.webkit = 'undefined' != typeof navigator
    && /webkit/i.test(navigator.userAgent);

   /**
   * Detect iPad/iPhone/iPod.
   *
   * @api public
   */

  util.ua.iDevice = 'undefined' != typeof navigator
      && /iPad|iPhone|iPod/i.test(navigator.userAgent);

})('undefined' != typeof io ? io : module.exports, this);

{'repo_name': 'narayand4/nodejs', 'stars': '113', 'repo_language': 'JavaScript', 'file_name': 'series.js', 'mime_type': 'text/plain', 'hash': 2993297121500408563, 'source_dataset': 'data'}


{include file="pageheader.htm"}

  <form name="theForm" method="post" action="goods_batch.php?act=edit" onsubmit="return getGoodsIDs()">

    {$lang.select_method}

      <input name="select_method" id="sm_cat" type="radio" value="cat" checked onclick="toggleSelectMethod(this.value)">{$lang.by_cat}
      <input name="select_method" id="sm_sn" type="radio" value="sn" onclick="toggleSelectMethod(this.value)">{$lang.by_sn}

    {$lang.select_cat}
     <select name="cat" id="cat" onchange="getGoods()">
      <option value="0" selected>{$lang.select_please}</option>{$cat_list}
    </select>

    {$lang.select_brand}
     <select name="brand" id="brand" onchange="getGoods()">
      <option value="0" selected>{$lang.select_please}</option>
      {html_options options=$brand_list}
    </select>

    {$lang.goods_list}

        {$lang.src_list}

        {$lang.dest_list}

          <select name="srcList" size="10" multiple id="srcList" style="width: 100%" ondblclick="addGoods()"></select>

        <input name="add" type="button" class="button" id="add" value=">>" onclick="addGoods()" />

          <input name="del" class="button" type="button" id="del" value="<<" onclick="delGoods()" />

          <select name="destList" size="10" multiple id="destList" style="width: 100%" ondblclick="delGoods()"></select>

    {$lang.input_sn}
    <textarea name="sn_list" rows="10" cols="40" id="sn_list"></textarea>

    {$lang.edit_method}

      <input name="edit_method" type="radio" value="each" checked>
      {$lang.edit_each}
      <input type="radio" name="edit_method" value="all">{$lang.edit_all}

    <input type="submit" name="submit" value="{$lang.go_edit}" class="button" />
      <input type="hidden" name="goods_ids" value="" />

  </form>

{literal}

{/literal}
{include file="pagefooter.htm"}

{'repo_name': 'shopex/ecshop', 'stars': '371', 'repo_language': 'PHP', 'file_name': 'login.html', 'mime_type': 'text/html', 'hash': 3893821720282309584, 'source_dataset': 'data'}


#ifndef _OMFS_H
#define _OMFS_H

#include <linux/module.h>
#include <linux/fs.h>

#include "omfs_fs.h"

/* In-memory structures */
struct omfs_sb_info {
	u64 s_num_blocks;
	u64 s_bitmap_ino;
	u64 s_root_ino;
	u32 s_blocksize;
	u32 s_mirrors;
	u32 s_sys_blocksize;
	u32 s_clustersize;
	int s_block_shift;
	unsigned long **s_imap;
	int s_imap_size;
	struct mutex s_bitmap_lock;
	int s_uid;
	int s_gid;
	int s_dmask;
	int s_fmask;
};

/* convert a cluster number to a scaled block number */
static inline sector_t clus_to_blk(struct omfs_sb_info *sbi, sector_t block)
{
	return block << sbi->s_block_shift;
}

static inline struct omfs_sb_info *OMFS_SB(struct super_block *sb)
{
	return sb->s_fs_info;
}

/* bitmap.c */
extern unsigned long omfs_count_free(struct super_block *sb);
extern int omfs_allocate_block(struct super_block *sb, u64 block);
extern int omfs_allocate_range(struct super_block *sb, int min_request,
			int max_request, u64 *return_block, int *return_size);
extern int omfs_clear_range(struct super_block *sb, u64 block, int count);

/* dir.c */
extern const struct file_operations omfs_dir_operations;
extern const struct inode_operations omfs_dir_inops;
extern int omfs_make_empty(struct inode *inode, struct super_block *sb);
extern int omfs_is_bad(struct omfs_sb_info *sbi, struct omfs_header *header,
			u64 fsblock);

/* file.c */
extern const struct file_operations omfs_file_operations;
extern const struct inode_operations omfs_file_inops;
extern const struct address_space_operations omfs_aops;
extern void omfs_make_empty_table(struct buffer_head *bh, int offset);
extern int omfs_shrink_inode(struct inode *inode);

/* inode.c */
extern struct buffer_head *omfs_bread(struct super_block *sb, sector_t block);
extern struct inode *omfs_iget(struct super_block *sb, ino_t inode);
extern struct inode *omfs_new_inode(struct inode *dir, int mode);
extern int omfs_reserve_block(struct super_block *sb, sector_t block);
extern int omfs_find_empty_block(struct super_block *sb, int mode, ino_t *ino);
extern int omfs_sync_inode(struct inode *inode);

#endif

{'repo_name': 'andy-padavan/rt-n56u', 'stars': '266', 'repo_language': 'None', 'file_name': 'rc-flydvb.c', 'mime_type': 'text/x-c', 'hash': 4514077498665414037, 'source_dataset': 'data'}


#ifndef _EXT4_H
#define _EXT4_H

#include <linux/jbd.h>
/* Temporarily we need this. */
#include <linux/ext3_fs.h>

typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;

typedef uint32_t ext4_lblk_t;
typedef uint64_t ext4_fsblk_t;

/*
 * Flags used by ext4_map_blocks()
 */
	/* Allocate any needed blocks and/or convert an unwritten
	   extent to be an initialized ext4 */
#define EXT4_GET_BLOCKS_CREATE			0x0001
	/* Request the creation of an unwritten extent */
#define EXT4_GET_BLOCKS_UNWRIT_EXT		0x0002
#define EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT	(EXT4_GET_BLOCKS_UNWRIT_EXT|\
						 EXT4_GET_BLOCKS_CREATE)
	/* Caller is from the delayed allocation writeout path
	 * finally doing the actual allocation of delayed blocks */
#define EXT4_GET_BLOCKS_DELALLOC_RESERVE	0x0004
	/* caller is from the direct IO path, request to creation of an
	unwritten extents if not allocated, split the unwritten
	extent if blocks has been preallocated already*/
#define EXT4_GET_BLOCKS_PRE_IO			0x0008
#define EXT4_GET_BLOCKS_CONVERT			0x0010
#define EXT4_GET_BLOCKS_IO_CREATE_EXT		(EXT4_GET_BLOCKS_PRE_IO|\
					 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT)
	/* Convert extent to initialized after IO complete */
#define EXT4_GET_BLOCKS_IO_CONVERT_EXT		(EXT4_GET_BLOCKS_CONVERT|\
					 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT)
	/* Eventual metadata allocation (due to growing extent tree)
	 * should not fail, so try to use reserved blocks for that.*/
#define EXT4_GET_BLOCKS_METADATA_NOFAIL		0x0020
	/* Don't normalize allocation size (used for fallocate) */
#define EXT4_GET_BLOCKS_NO_NORMALIZE		0x0040
	/* Request will not result in inode size update (user for fallocate) */
#define EXT4_GET_BLOCKS_KEEP_SIZE		0x0080
	/* Do not take i_data_sem locking in ext4_map_blocks */
#define EXT4_GET_BLOCKS_NO_LOCK			0x0100
	/* Do not put hole in extent cache */
#define EXT4_GET_BLOCKS_NO_PUT_HOLE		0x0200
	/* Convert written extents to unwritten */
#define EXT4_GET_BLOCKS_CONVERT_UNWRITTEN	0x0400

/*
 * The bit position of these flags must not overlap with any of the
 * EXT4_GET_BLOCKS_*.  They are used by ext4_find_extent(),
 * read_extent_tree_block(), ext4_split_extent_at(),
 * ext4_ext_insert_extent(), and ext4_ext_create_new_leaf().
 * EXT4_EX_NOCACHE is used to indicate that the we shouldn't be
 * caching the extents when reading from the extent tree while a
 * truncate or punch hole operation is in progress.
 */
#define EXT4_EX_NOCACHE				0x40000000
#define EXT4_EX_FORCE_CACHE			0x20000000

/*
 * Flags used by ext4_free_blocks
 */
#define EXT4_FREE_BLOCKS_METADATA	0x0001
#define EXT4_FREE_BLOCKS_FORGET		0x0002
#define EXT4_FREE_BLOCKS_VALIDATED	0x0004
#define EXT4_FREE_BLOCKS_NO_QUOT_UPDATE	0x0008
#define EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER	0x0010
#define EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER	0x0020

/*
 * Flags used in mballoc's allocation_context flags field.
 *
 * Also used to show what's going on for debugging purposes when the
 * flag field is exported via the traceport interface
 */

/* prefer goal again. length */
#define EXT4_MB_HINT_MERGE		0x0001
/* blocks already reserved */
#define EXT4_MB_HINT_RESERVED		0x0002
/* metadata is being allocated */
#define EXT4_MB_HINT_METADATA		0x0004
/* first blocks in the file */
#define EXT4_MB_HINT_FIRST		0x0008
/* search for the best chunk */
#define EXT4_MB_HINT_BEST		0x0010
/* data is being allocated */
#define EXT4_MB_HINT_DATA		0x0020
/* don't preallocate (for tails) */
#define EXT4_MB_HINT_NOPREALLOC		0x0040
/* allocate for locality group */
#define EXT4_MB_HINT_GROUP_ALLOC	0x0080
/* allocate goal blocks or none */
#define EXT4_MB_HINT_GOAL_ONLY		0x0100
/* goal is meaningful */
#define EXT4_MB_HINT_TRY_GOAL		0x0200
/* blocks already pre-reserved by delayed allocation */
#define EXT4_MB_DELALLOC_RESERVED	0x0400
/* We are doing stream allocation */
#define EXT4_MB_STREAM_ALLOC		0x0800
/* Use reserved root blocks if needed */
#define EXT4_MB_USE_ROOT_BLOCKS		0x1000
/* Use blocks from reserved pool */
#define EXT4_MB_USE_RESERVED		0x2000

#define ext4_sb_info ext3_sb_info

static inline struct ext4_sb_info * EXT4_SB(struct super_block *sb)
{
    return sb->s_fs_info;
}
#define EXT4_I(i) (i)

#include <linux/ext4_jbd2.h>
#include <linux/ext4_ext.h>

#endif	/* _EXT4_H */

{'repo_name': 'reactos/reactos-deprecated-gitsvn-dont-use', 'stars': '307', 'repo_language': 'C', 'file_name': 'options.c', 'mime_type': 'text/x-c', 'hash': -673081784016789711, 'source_dataset': 'data'}


import {
    toLispBoolean
} from './header';
import {
    values1
} from './values';

class Structure {
    constructor(name, values) {
        this.name = name;
        this.values = values;
    }

    getValue(i) {
        return this.values[i];
    }

    setValue(i, value) {
        this.values[i] = value;
    }

    copy() {
        return new Structure(this.name, this.values);
    }
}

export function CL_makeStructure(name, ...args) {
    return values1(new Structure(name, args));
}

export function CL_copyStructure(x) {
    return values1(x.copy());
}

export function CL_structurep(x) {
    return values1(toLispBoolean(x instanceof Structure));
}

export function CL_structureName(structure) {
    return values1(structure.name);
}

export function CL_structureSlotCount(structure) {
    return values1(structure.values.length);
}

export function CL_structureRef(structure, i) {
    return values1(structure.getValue(i));
}

export function CL_structureSet(structure, i, value) {
    structure.setValue(i, value);
    return values1(value);
}

{'repo_name': 'cxxxr/valtan', 'stars': '171', 'repo_language': 'Common Lisp', 'file_name': 'webpack.config.js', 'mime_type': 'text/plain', 'hash': -98723007792393974, 'source_dataset': 'data'}


/* PropertyVetoException.java -- thrown to veto a proposed property change
   Copyright (C) 1998, 2000, 2002 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package java.beans;

/**
 * PropertyVetoException is thrown when a VetoableChangeListener doesn't
 * like the proposed change.
 *
 * @author John Keiser
 * @see VetoableChangeListener
 * @since 1.1
 * @status updated to 1.4
 */
public class PropertyVetoException extends Exception
{
  /**
   * Compatible with JDK 1.1+.
   */
  private static final long serialVersionUID = 129596057694162164L;

  /**
   * The vetoed change.
   *
   * @serial the event that was vetoed
   */
  private final PropertyChangeEvent evt;

  /**
   * Instantiate this exception with the given message and property change.
   *
   * @param msg the reason for the veto
   * @param changeEvent the PropertyChangeEvent that was thrown
   */
  public PropertyVetoException(String msg, PropertyChangeEvent changeEvent)
  {
    super(msg);
    evt = changeEvent;
  }

  /**
   * Get the PropertyChange event that was vetoed.
   *
   * @return the vetoed change
   */
  public PropertyChangeEvent getPropertyChangeEvent()
  {
    return evt;
  }
}

{'repo_name': 'jcmvbkbc/gcc-xtensa', 'stars': '121', 'repo_language': 'C', 'file_name': 'api.html', 'mime_type': 'text/xml', 'hash': -1833283594984813873, 'source_dataset': 'data'}