text
stringlengths 2
1.04M
| meta
dict |
---|---|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Android Open Source Project
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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_on_holo_light" />
<item android:state_checked="false" android:state_window_focused="false"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_off_holo_light" />
<item android:state_checked="true" android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_on_pressed_holo_light" />
<item android:state_checked="false" android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_off_pressed_holo_light" />
<item android:state_checked="true" android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_on_focused_holo_light" />
<item android:state_checked="false" android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_off_focused_holo_light" />
<item android:state_checked="false" android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_off_holo_light" />
<item android:state_checked="true" android:state_enabled="true"
android:drawable="@drawable/busitutheme_btn_radio_on_holo_light" />
<!-- Disabled states -->
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/busitutheme_btn_radio_on_disabled_holo_light" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/busitutheme_btn_radio_off_disabled_holo_light" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/busitutheme_btn_radio_on_disabled_focused_holo_light" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/busitutheme_btn_radio_off_disabled_focused_holo_light" />
<item android:state_checked="false" android:drawable="@drawable/busitutheme_btn_radio_off_disabled_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/busitutheme_btn_radio_on_disabled_holo_light" />
</selector>
| {
"content_hash": "dd2cbe17cab4e8db2ba9138cc5cebc5f",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 117,
"avg_line_length": 53.355932203389834,
"alnum_prop": 0.7061626429479034,
"repo_name": "marcocbarbieri/BusItu",
"id": "bd7232491cc6d5e33c68ad628ae508ec8a2dc674",
"size": "3148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BusItu/res/drawable/busitutheme_btn_radio_holo_light.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "66917"
}
],
"symlink_target": ""
} |
package io.github.greyp9.arwo.app.cache.servlet;
import io.github.greyp9.arwo.app.cache.handler.CacheHandlerGet;
import io.github.greyp9.arwo.app.core.servlet.ServletU;
import io.github.greyp9.arwo.app.core.state.AppState;
import io.github.greyp9.arwo.app.core.state.AppUserState;
import io.github.greyp9.arwo.core.app.App;
import io.github.greyp9.arwo.core.http.HttpResponse;
import io.github.greyp9.arwo.core.http.gz.HttpResponseGZipU;
import io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest;
import io.github.greyp9.arwo.core.naming.AppNaming;
import javax.naming.Context;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CacheServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = -1663049100286919080L;
private transient AppState appState;
@Override
public final void init(final ServletConfig config) throws ServletException {
super.init(config);
final Context context = AppNaming.lookupSubcontext(getServletContext().getContextPath());
synchronized (this) {
this.appState = (AppState) AppNaming.lookup(context, App.Naming.APP_STATE);
}
}
@Override
public final void destroy() {
synchronized (this) {
this.appState = null;
}
}
@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// get request context
final ServletHttpRequest httpRequest = ServletU.read(request);
// process request
AppUserState userState;
synchronized (this) {
userState = appState.getUserState(httpRequest.getPrincipal(), httpRequest.getDate());
}
final HttpResponse httpResponse = new CacheHandlerGet(httpRequest, userState).doGetSafe();
// send response
final HttpResponse httpResponseGZ = HttpResponseGZipU.toHttpResponseGZip(httpRequest, httpResponse);
ServletU.write(httpResponseGZ, response);
}
}
| {
"content_hash": "46536c3ed10b40fbb818a49a521acc74",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 108,
"avg_line_length": 39.42857142857143,
"alnum_prop": 0.7382246376811594,
"repo_name": "greyp9/arwo",
"id": "f83f64287c9d1e40805d0a624e25ca53b72177b8",
"size": "2208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/app/java/io/github/greyp9/arwo/app/cache/servlet/CacheServlet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7897"
},
{
"name": "HTML",
"bytes": "26765"
},
{
"name": "Java",
"bytes": "2570281"
},
{
"name": "XSLT",
"bytes": "25589"
}
],
"symlink_target": ""
} |
import argparse
import re
parser = argparse.ArgumentParser(
description='extracts the total xor differnces from an xor log')
parser.add_argument('--log_file', '-l',required=True,
help='log file')
parser.add_argument('--output', '-o', required=True,
help='output file to store results')
args = parser.parse_args()
log_file_name = args.log_file
out_file_name = args.output
string = "XOR differences:"
pattern = re.compile(r'\s*%s\s*([\d+]+)' % string)
tot_cnt = 0
with open(log_file_name, "r") as f:
for line in f:
m = pattern.match(line)
if m:
tot_cnt += int(m.group(1))
outFileOpener = open(out_file_name, "w")
outFileOpener.write("Total XOR differences = "+ str(tot_cnt))
outFileOpener.close()
| {
"content_hash": "8a64e23c9c1ad45065b9a2339c5edbba",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 68,
"avg_line_length": 27.75,
"alnum_prop": 0.6332046332046332,
"repo_name": "efabless/openlane",
"id": "842b484df83398a8a5e1cc490099d5f5c03e2a12",
"size": "1363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/parse_klayout_xor_log.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Coq",
"bytes": "128005"
},
{
"name": "Dockerfile",
"bytes": "52446"
},
{
"name": "HTML",
"bytes": "218625"
},
{
"name": "Logos",
"bytes": "26097"
},
{
"name": "Makefile",
"bytes": "2470"
},
{
"name": "Perl",
"bytes": "5589"
},
{
"name": "Python",
"bytes": "246219"
},
{
"name": "Shell",
"bytes": "21834"
},
{
"name": "Tcl",
"bytes": "168706"
},
{
"name": "Verilog",
"bytes": "4684813"
}
],
"symlink_target": ""
} |
using ColossalFramework;
using MetroOverhaul;
using MetroOverhaul.NEXT.Extensions;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace MetroOverhaul
{
class MOMMetroTrackBridgeAI : MetroTrackBridgeAI
{
public List<BridgePillarItem> pillarList { get; set; }
public ItemClass m_IntersectClass = null;
public bool NoPillarCollision { get; set; }
public PillarType pillarType { get; set; }
private static NetTool m_NetTool = Util.GetNetTool();
public override void GetNodeBuilding(ushort nodeID, ref NetNode data, out BuildingInfo building, out float heightOffset)
{
if ((data.m_flags & NetNode.Flags.Outside) == NetNode.Flags.None)
{
if (this.m_middlePillarInfo != null && (data.m_flags & NetNode.Flags.Double) != NetNode.Flags.None)
{
building = this.m_middlePillarInfo;
heightOffset = this.m_middlePillarOffset - 1f - this.m_middlePillarInfo.m_generatedInfo.m_size.y;
return;
}
}
if (this.m_bridgePillarInfo != null)
{
heightOffset = this.m_bridgePillarOffset - 1f - this.m_bridgePillarInfo.m_generatedInfo.m_size.y;
var position = data.m_position;
building = m_bridgePillarInfo;
if (pillarList != null && pillarList.Count > 0)
{
if (m_NetTool?.Prefab != null)
{
var elevation = m_NetTool.GetElevation();
var theList = pillarList.Where(d => d.HeightLimit == 0 || d.HeightLimit >= elevation).OrderBy(x => x.HeightLimit).ToList();
BridgePillarItem thePillarInfo = null;
if (theList == null || theList.Count == 0)
{
thePillarInfo = pillarList.LastOrDefault();
}
else
{
thePillarInfo = theList.FirstOrDefault();
}
BuildingInfo info = null;
BuildingInfo noColInfo = null;
if (m_NetTool.Prefab.name.Contains("Bridge"))
{
pillarType = PillarType.WideMedian;
}
switch (pillarType)
{
case PillarType.WideMedian:
info = thePillarInfo.WideMedianInfo;
noColInfo = thePillarInfo.WideMedianInfoNoCol;
break;
case PillarType.Wide:
info = thePillarInfo.WideInfo;
noColInfo = thePillarInfo.WideInfoNoCol;
break;
case PillarType.NarrowMedian:
info = thePillarInfo.NarrowMedianInfo;
noColInfo = thePillarInfo.NarrowMedianInfoNoCol;
break;
case PillarType.Narrow:
info = thePillarInfo.NarrowInfo;
noColInfo = thePillarInfo.NarrowInfoNoCol;
break;
}
var prefab = m_NetTool.Prefab;
if (NoPillarCollision && elevation >= 0)
{
building = noColInfo;
if (m_IntersectClass == null)
{
m_IntersectClass = prefab.m_intersectClass;
}
prefab.m_intersectClass = null;
}
else
{
building = info;
if (m_IntersectClass != null)
{
prefab.m_intersectClass = m_IntersectClass;
}
}
m_bridgePillarInfo = building;
if (thePillarInfo != null && info != null)
{
heightOffset = thePillarInfo.HeightOffset - 1f - info.m_generatedInfo.m_size.y;
if (data.m_building != 0)
{
Debug.Log("BuildingNode is " + data.m_building);
}
}
}
return;
}
}
base.GetNodeBuilding(nodeID, ref data, out building, out heightOffset);
}
public override void UpdateNodeFlags(ushort nodeID, ref NetNode data)
{
base.UpdateNodeFlags(nodeID, ref data);
NetNode.Flags flags = data.m_flags & ~(NetNode.Flags.Transition | NetNode.Flags.LevelCrossing | NetNode.Flags.TrafficLights);
int num = 0;
int num2 = 0;
uint num3 = 0u;
int num4 = 0;
NetManager instance = Singleton<NetManager>.instance;
for (int i = 0; i < 8; i++)
{
ushort segment = data.GetSegment(i);
if (segment != 0)
{
NetInfo info = instance.m_segments.m_buffer[(int)segment].Info;
if (info != null)
{
uint num8 = 1u << (int)info.m_class.m_level;
if ((num3 & num8) == 0u)
{
num3 |= num8;
num4++;
}
if (info.m_createPavement)
{
flags |= NetNode.Flags.Transition;
}
if (info.m_class.m_service == ItemClass.Service.Road)
{
num++;
}
else if (info.m_class.m_service == ItemClass.Service.PublicTransport)
{
num2++;
}
}
}
}
if (num2 >= 2 && num >= 1)
{
flags |= (NetNode.Flags.LevelCrossing | NetNode.Flags.TrafficLights);
}
if (num2 >= 2 && num4 >= 2)
{
flags |= NetNode.Flags.Transition;
}
else
{
flags &= ~NetNode.Flags.Transition;
}
data.m_flags = flags;
}
private void GetSegmentPillarProps(float elevation)
{
//if (pillarPropList != null && pillarList.Count > 0)
//{
// var thePropList = pillarPropList.Where(d => d.HeightLimit >= elevation).OrderBy(x => x.HeightLimit).ToList();
// BridgePillarPropItem thePillarPropInfo = null;
// if (thePropList == null || thePropList.Count == 0)
// {
// thePillarPropInfo = pillarPropList.LastOrDefault();
// }
// else
// {
// thePillarPropInfo = thePropList.FirstOrDefault();
// }
// if (thePillarPropInfo != null)
// {
// var prop = new NetLaneProps.Prop();
// m_ElevatedPillarPropInfo = thePillarPropInfo.Prop;
// prop.m_prop = m_ElevatedPillarPropInfo;
// prop.m_probability = 100;
// prop.m_repeatDistance = thePillarPropInfo.RepeatDistance;
// prop.m_segmentOffset = thePillarPropInfo.SegmentOffset;
// var prefab = FindObjectOfType<NetTool>().Prefab;
// var centerLane = prefab.m_lanes.FirstOrDefault(l => l != null && l.m_laneType == NetInfo.LaneType.None);
// if (centerLane == null)
// {
// centerLane = new NetInfo.Lane();
// centerLane.m_laneType = NetInfo.LaneType.None;
// centerLane.m_laneProps = ScriptableObject.CreateInstance<NetLaneProps>();
// }
// var laneProps = centerLane.m_laneProps.m_props.ToList();
// laneProps.Add(prop);
// centerLane.m_laneProps.m_props = laneProps.ToArray();
// var lanes = prefab.m_lanes.ToList();
// lanes.Add(centerLane);
// prefab.m_lanes = lanes.ToArray();
// }
//}
}
}
}
public class BridgePillarItem
{
public float HeightLimit { get; set; }
public float HeightOffset { get; set; }
public BuildingInfo WideMedianInfo { get; set; }
public BuildingInfo WideInfo { get; set; }
public BuildingInfo NarrowMedianInfo { get; set; }
public BuildingInfo NarrowInfo { get; set; }
public BuildingInfo WideMedianInfoNoCol { get; set; }
public BuildingInfo WideInfoNoCol { get; set; }
public BuildingInfo NarrowMedianInfoNoCol { get; set; }
public BuildingInfo NarrowInfoNoCol { get; set; }
public BridgePillarItem()
{
HeightLimit = 0;
HeightOffset = 0;
}
}
public class BridgePillarPropItem
{
public float HeightLimit { get; set; }
public PropInfo Prop { get; set; }
public Vector3 Position { get; set; }
public float SegmentOffset { get; set; }
public float RepeatDistance { get; set; }
public BridgePillarPropItem()
{
HeightLimit = 60;
Position = Vector3.zero;
SegmentOffset = 0;
RepeatDistance = 60;
Prop = null;
}
} | {
"content_hash": "17e21dec04df2cbf9c05c45973003290",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 147,
"avg_line_length": 42.69491525423729,
"alnum_prop": 0.4523620484319174,
"repo_name": "earalov/Skylines-ElevatedTrainStationTrack",
"id": "61b8f351ece5aa7df975710d10aa707a66765c5d",
"size": "10078",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MOMMetroTrackBridgeAI.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "20600"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "bcc2148694a54a4cf0e5f4349f409035",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "df6c65f8bf7cc9a0a79bdf428c39bbaa1b3b82ea",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Crepidiastrum linguifolium/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!--
Copyright (c) 2000-2022, Board of Trustees of Leland Stanford Jr. University
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-->
<map>
<entry>
<string>plugin_status</string>
<string>ready</string>
</entry>
<entry>
<string>plugin_identifier</string>
<string>org.lockss.plugin.archiveit.ArchiveItApiPlugin</string>
</entry>
<entry>
<string>au_def_pause_time</string>
<long>3000</long>
</entry>
<entry>
<string>plugin_version</string>
<string>8</string>
</entry>
<entry>
<string>au_name</string>
<string>"Archive-It Plugin, Base URL %s, Organization %s, Collection %s", base_url, organization, collection</string>
</entry>
<entry>
<string>plugin_name</string>
<string>Archive-It Plugin</string>
</entry>
<entry>
<string>plugin_feature_version_map</string>
<map>
<entry>
<string>Poll</string>
<string>1</string>
</entry>
<entry>
<string>Substance</string>
<string>1</string>
</entry>
<entry>
<string>Metadata</string>
<string>1</string>
</entry>
</map>
</entry>
<entry>
<string>au_def_new_content_crawl</string>
<long>1209600000</long>
</entry>
<entry>
<string>plugin_config_props</string>
<list>
<org.lockss.daemon.ConfigParamDescr>
<key>base_url</key>
<displayName>Base URL</displayName>
<description>Usually of the form http://<journal-name>.com/</description>
<type>3</type>
<size>40</size>
<definitional>true</definitional>
<defaultOnly>false</defaultOnly>
</org.lockss.daemon.ConfigParamDescr>
<org.lockss.daemon.ConfigParamDescr>
<key>collection</key>
<displayName>Collection</displayName>
<description>Collection identifier</description>
<type>1</type>
<size>20</size>
<definitional>true</definitional>
<defaultOnly>false</defaultOnly>
</org.lockss.daemon.ConfigParamDescr>
<org.lockss.daemon.ConfigParamDescr>
<key>organization</key>
<displayName>Organization</displayName>
<description>Organization identifier</description>
<type>1</type>
<size>20</size>
<definitional>true</definitional>
<defaultOnly>false</defaultOnly>
</org.lockss.daemon.ConfigParamDescr>
<org.lockss.daemon.ConfigParamDescr>
<key>user_pass</key>
<displayName>Username:Password</displayName>
<type>10</type>
<size>30</size>
<definitional>false</definitional>
<defaultOnly>false</defaultOnly>
</org.lockss.daemon.ConfigParamDescr>
</list>
</entry>
<entry>
<string>au_crawlrules</string>
<list>
<string>1,"^%s(webdatafile|wasapi)", base_url</string>
<string>1,"^https://warcs\.archive-it\.org/"</string>
<string>1,"^https://archive\.org/download/"</string>
<!-- synthetic url, if you want to update the pattern you must update it in all of these places
1. ArchiveItApiPlugin - crawl_rules
2. ArchiveItApiCrawlSeed.populateUrlList()
3. ArchiveItApiFeatureUrlHelperFactory.getSyntheticUrl()
-->
<string>1,"^%sorganization=", base_url</string>
<!-- redirects to subdomains with this pattern occur
ia903003.us.archive.org/31/items
-->
<string>1,".*\.us\.archive\.org/[0-9]*/items/"</string>
</list>
</entry>
<!-- crawlseed supersedes this, but leave in just in case. -->
<entry>
<string>au_start_url</string>
<!-- https://warcs.archive-it.org/wasapi/v1/webdata?collection=10181 -->
<string>"%swasapi/v1/webdata?collection=%s", base_url, collection</string>
</entry>
<entry>
<string>au_permission_url</string>
<string>https://partner.archive-it.org/static/LOCKSS</string>
</entry>
<entry>
<string>au_feature_urls</string>
<map>
<entry>
<!-- we don't want this to default to start_url because we need the synthetic url -->
<string>au_volume</string>
<string>org.lockss.plugin.archiveit.ArchiveItApiFeatureUrlHelperFactory</string>
</entry>
</map>
</entry>
<entry>
<string>plugin_access_url_factory</string>
<string>org.lockss.plugin.archiveit.ArchiveItApiFeatureUrlHelperFactory</string>
</entry>
<entry>
<string>required_daemon_version</string>
<string>1.75.8</string>
</entry>
<entry>
<string>plugin_cache_result_list</string>
<list>
<string>Retryable=org.lockss.util.urlconn.CacheException$RetryableNetworkException_5_30S</string>
</list>
</entry>
<entry>
<!-- Web Archiving Systems API (WASAPI) -->
<string>plugin_crawl_seed_factory</string>
<string>org.lockss.plugin.archiveit.ArchiveItApiCrawlSeedFactory</string>
</entry>
<entry>
<string>text/html_filter_factory</string>
<string>org.lockss.plugin.archiveit.ArchiveItHtmlFilterFactory</string>
</entry>
<entry>
<string>plugin_url_consumer_factory</string>
<string>org.lockss.plugin.archiveit.ArchiveItApiUrlConsumerFactory</string>
</entry>
<entry>
<string>au_permitted_host_pattern</string>
<list>
<!-- https://partner.archive-it.org/ -->
<string>"archive\.org"</string>
<string>"archive-it\.org"</string>
</list>
</entry>
<entry>
<!-- https://partner.archive-it.org/login?next=/ -->
<string>au_redirect_to_login_url_pattern</string>
<string>"archive-it\.org/login\?.*", </string>
</entry>
</map>
| {
"content_hash": "937c74d62d38428035f7666e511c9048",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 125,
"avg_line_length": 39.23979591836735,
"alnum_prop": 0.6059030035105968,
"repo_name": "lockss/lockss-daemon",
"id": "ac40c8ed5ff75dacf86d733897de366a6b622e15",
"size": "7691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/src/org/lockss/plugin/archiveit/ArchiveItApiPlugin.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ANTLR",
"bytes": "19051"
},
{
"name": "Awk",
"bytes": "14488"
},
{
"name": "Batchfile",
"bytes": "77"
},
{
"name": "C",
"bytes": "4376"
},
{
"name": "CSS",
"bytes": "8825"
},
{
"name": "HTML",
"bytes": "747906"
},
{
"name": "Java",
"bytes": "34571927"
},
{
"name": "JavaScript",
"bytes": "1093221"
},
{
"name": "Perl",
"bytes": "237235"
},
{
"name": "Python",
"bytes": "392081"
},
{
"name": "Shell",
"bytes": "198060"
},
{
"name": "mIRC Script",
"bytes": "12320"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
using System.Collections.Immutable;
/// <summary>
/// A builder for create an instance of <see cref="IMarkdownEngine"/>
/// </summary>
public class MarkdownEngineBuilder
{
public MarkdownEngineBuilder(Options options)
{
Options = options;
}
/// <summary>
/// The options.
/// </summary>
public Options Options { get; }
/// <summary>
/// The block rules.
/// </summary>
public ImmutableList<IMarkdownRule> BlockRules { get; set; } = ImmutableList<IMarkdownRule>.Empty;
/// <summary>
/// The inline rules.
/// </summary>
public ImmutableList<IMarkdownRule> InlineRules { get; set; } = ImmutableList<IMarkdownRule>.Empty;
/// <summary>
/// The markdown token rewriter.
/// </summary>
public IMarkdownTokenRewriter Rewriter { get; set; }
/// <summary>
/// The markdown token tree validator.
/// </summary>
public IMarkdownTokenTreeValidator TokenTreeValidator { get; set; }
public ImmutableList<IMarkdownTokenAggregator> TokenAggregators { get; set; } = ImmutableList<IMarkdownTokenAggregator>.Empty;
/// <summary>
/// Create markdown paring context.
/// </summary>
/// <returns>a instance of <see cref="IMarkdownContext"/></returns>
public virtual IMarkdownContext CreateParseContext()
{
return new MarkdownBlockContext(BlockRules, new MarkdownInlineContext(InlineRules));
}
/// <summary>
/// Create an instance of <see cref="IMarkdownEngine"/>
/// </summary>
/// <param name="renderer">the renderer.</param>
/// <returns>an instance of <see cref="IMarkdownEngine"/></returns>
public virtual IMarkdownEngine CreateEngine(object renderer)
{
return new MarkdownEngine(CreateParseContext(), Rewriter, renderer, Options)
{
TokenTreeValidator = TokenTreeValidator,
TokenAggregators = TokenAggregators,
};
}
}
}
| {
"content_hash": "e9f56e177d5b01bf2147ca426384851e",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 134,
"avg_line_length": 34.44117647058823,
"alnum_prop": 0.605465414175918,
"repo_name": "dotnet/docfx",
"id": "64647b35f1fd82aa6d57b7d1c271a464c8d68d20",
"size": "2344",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "src/Microsoft.DocAsCode.MarkdownLite/MarkdownEngineBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "236"
},
{
"name": "C#",
"bytes": "5468456"
},
{
"name": "CSS",
"bytes": "49441"
},
{
"name": "F#",
"bytes": "133425"
},
{
"name": "JavaScript",
"bytes": "97975"
},
{
"name": "Liquid",
"bytes": "5617"
},
{
"name": "PowerShell",
"bytes": "41840"
},
{
"name": "Roff",
"bytes": "980"
},
{
"name": "Shell",
"bytes": "297"
},
{
"name": "XSLT",
"bytes": "6912"
}
],
"symlink_target": ""
} |
package org.kuali.rice.kew.actions;
import org.junit.Test;
import org.kuali.rice.kew.actionrequest.ActionRequestValue;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.api.action.MovePoint;
import org.kuali.rice.kew.api.document.node.RouteNodeInstance;
import org.kuali.rice.kew.api.document.WorkflowDocumentService;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.*;
public class MoveDocumentTest extends KEWTestCase {
protected void loadTestData() throws Exception {
loadXmlFile("ActionsConfig.xml");
}
/**
* Tests that we can move a sequential document forward and backward.
*
*/
@Test public void testMoveDocumentSequential() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), SeqSetup.DOCUMENT_TYPE_NAME);
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("bmcgough"), document.getDocumentId());
assertTrue("Bmcgough should have an approve.", document.isApprovalRequested());
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Rkirkend should have an approve.", document.isApprovalRequested());
assertEquals("Should be at the WorkflowDocument Node.", SeqSetup.WORKFLOW_DOCUMENT_NODE, document.getNodeNames().iterator().next());
// move the document forward one node
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_NODE, 1), "");
List actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
assertEquals("Should be only 1 pending approve request to pmckown.", 1, actionRequests.size());
assertEquals("Should be at the WorkflowDocument2 Node.", SeqSetup.WORKFLOW_DOCUMENT_2_NODE, document.getNodeNames().iterator().next());
// after moving the document forward, bmcgough and rkirkend should no longer have requests, but phil should
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("bmcgough"), document.getDocumentId());
assertFalse("Bmcgough should NOT have an approve.", document.isApprovalRequested());
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertFalse("Rkirkend should NOT have an approve.", document.isApprovalRequested());
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("pmckown"), document.getDocumentId());
assertTrue("Pmckown should have an approve.", document.isApprovalRequested());
ActionRequestValue pmckownRequest = (ActionRequestValue)actionRequests.get(0);
// now try moving it to itself, effectively refreshing the node
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_2_NODE, 0), "");
assertTrue("Pmckown should still have an approve.", document.isApprovalRequested());
actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
assertEquals("Should be only 1 pending approve request to pmckown.", 1, actionRequests.size());
assertEquals("Should be at the WorkflowDocument2 Node.", SeqSetup.WORKFLOW_DOCUMENT_2_NODE, document.getNodeNames().iterator().next());
// since this should have invoked a refresh, let's ensure that the action request ids are different after the move
assertFalse("Action request ids should be different.", pmckownRequest.getActionRequestId().equals(((ActionRequestValue)actionRequests.get(0)).getActionRequestId()));
// now try moving it back
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_2_NODE, -1), "");
// document should now be back at the WorkflowDocumentNode with requests to rkirkend and brian
actionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId());
assertEquals("Should be 2 pending requests.", 2, actionRequests.size());
assertEquals("Should be at the WorkflowDocument Node.", SeqSetup.WORKFLOW_DOCUMENT_NODE, document.getNodeNames().iterator().next());
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("bmcgough"), document.getDocumentId());
assertTrue("Bmcgough should have an approve.", document.isApprovalRequested());
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Rkirkend should have an approve.", document.isApprovalRequested());
// Let's do a sanity check to make sure we're still ENROUTE and move the doc to an ack node, rendering it PROCESSED,
// also, we'll check that there are no permissions enforced on the move document action by moving as a random user
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("xqi"), document.getDocumentId());
assertTrue("Doc should be ENROUTE.", document.isEnroute());
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_NODE, 2), "");
assertTrue("Doc should be PROCESSED.", document.isProcessed());
}
/**
* This tests that we can invoke the move document command inside of a sub process.
*/
@Test public void testMoveDocumentInsideProcess() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "MoveInProcessTest");
document.route("");
// approve as bmcgough and rkirkend to move into process
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("bmcgough"), document.getDocumentId());
assertTrue("bmcgough should have approve", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have approve", document.isApprovalRequested());
document.approve("");
WorkflowDocumentService workflowDocumentService = KewApiServiceLocator.getWorkflowDocumentService();
List<RouteNodeInstance> activeNodeInstances = workflowDocumentService.getActiveRouteNodeInstances(document.getDocumentId());
assertEquals("Should be 1 active node instance.", 1, activeNodeInstances.size());
RouteNodeInstance node2 = activeNodeInstances.get(0);
assertEquals("Should be at the WorkflowDocument2 node.", SeqSetup.WORKFLOW_DOCUMENT_2_NODE, node2.getName());
assertTrue("Node should be in a process.", node2.getProcessId() != null);
// now try to move the document forward one which will keep us inside the subprocess
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_2_NODE, 1), "");
activeNodeInstances = workflowDocumentService.getActiveRouteNodeInstances(document.getDocumentId());
RouteNodeInstance node3 = activeNodeInstances.get(0);
assertEquals("Should be at the WorkflowDocument3 node.", SeqSetup.WORKFLOW_DOCUMENT_3_NODE, node3.getName());
assertTrue("Node should be in a process.", node3.getProcessId() != null);
assertEquals("Node 2 and 3 should be in the same process.", node2.getProcessId(), node3.getProcessId());
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_3_NODE, 0), "");
document.move(MovePoint.create(SeqSetup.WORKFLOW_DOCUMENT_3_NODE, -1), "");
}
@Test public void testMoveDocumentParallel() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), ParallelSetup.DOCUMENT_TYPE_NAME);
document.blanketApprove("", new String[] { ParallelSetup.WORKFLOW_DOCUMENT_2_B2_NODE, ParallelSetup.WORKFLOW_DOCUMENT_3_B1_NODE, ParallelSetup.WORKFLOW_DOCUMENT_4_B3_NODE });
Set nodeNames = TestUtilities.createNodeInstanceNameSet(KEWServiceLocator.getRouteNodeService().getActiveNodeInstances(document.getDocumentId()));
assertEquals("There should be 3 active nodes.", 3, nodeNames.size());
assertTrue("Should be at WorkflowDocument3-B1", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_3_B1_NODE));
assertTrue("Should be at WorkflowDocument2-B2", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_2_B2_NODE));
assertTrue("Should be at WorkflowDocument4-B3", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_4_B3_NODE));
// try to move the document from WorkflowDocument3-B1 to WorkflowDocument2-B1
document.move(MovePoint.create(ParallelSetup.WORKFLOW_DOCUMENT_3_B1_NODE, -1), "");
nodeNames = TestUtilities.createNodeInstanceNameSet(KEWServiceLocator.getRouteNodeService().getActiveNodeInstances(document.getDocumentId()));
assertEquals("There should be 3 active nodes.", 3, nodeNames.size());
assertTrue("Should be at WorkflowDocument2-B1", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_2_B1_NODE));
assertTrue("Should be at WorkflowDocument2-B2", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_2_B2_NODE));
assertTrue("Should be at WorkflowDocument4-B3", nodeNames.contains(ParallelSetup.WORKFLOW_DOCUMENT_4_B3_NODE));
}
private class SeqSetup {
public static final String DOCUMENT_TYPE_NAME = "MoveSequentialTest";
public static final String ADHOC_NODE = "AdHoc";
public static final String WORKFLOW_DOCUMENT_NODE = "WorkflowDocument";
public static final String WORKFLOW_DOCUMENT_2_NODE = "WorkflowDocument2";
public static final String WORKFLOW_DOCUMENT_3_NODE = "WorkflowDocument3";
public static final String ACKNOWLEDGE_1_NODE = "Acknowledge1";
public static final String ACKNOWLEDGE_2_NODE = "Acknowledge2";
}
private class ParallelSetup {
public static final String DOCUMENT_TYPE_NAME = "BlanketApproveParallelTest";
public static final String ADHOC_NODE = "AdHoc";
public static final String WORKFLOW_DOCUMENT_NODE = "WorkflowDocument";
public static final String WORKFLOW_DOCUMENT_2_B1_NODE = "WorkflowDocument2-B1";
public static final String WORKFLOW_DOCUMENT_2_B2_NODE = "WorkflowDocument2-B2";
public static final String WORKFLOW_DOCUMENT_3_B1_NODE = "WorkflowDocument3-B1";
public static final String WORKFLOW_DOCUMENT_3_B2_NODE = "WorkflowDocument3-B2";
public static final String WORKFLOW_DOCUMENT_4_B3_NODE = "WorkflowDocument4-B3";
public static final String ACKNOWLEDGE_1_NODE = "Acknowledge1";
public static final String ACKNOWLEDGE_2_NODE = "Acknowledge2";
public static final String JOIN_NODE = "Join";
public static final String SPLIT_NODE = "Split";
public static final String WORKFLOW_DOCUMENT_FINAL_NODE = "WorkflowDocumentFinal";
}
}
| {
"content_hash": "6568469b8a44c6d85bd2b68cfad3e459",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 179,
"avg_line_length": 65.11494252873563,
"alnum_prop": 0.7316857899382171,
"repo_name": "ua-eas/ua-rice-2.1.9",
"id": "c828d461755024de257d3e996bbcbdb1947ac069",
"size": "11951",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "it/kew/src/test/java/org/kuali/rice/kew/actions/MoveDocumentTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "430866"
},
{
"name": "Groovy",
"bytes": "2203909"
},
{
"name": "Java",
"bytes": "25128172"
},
{
"name": "JavaScript",
"bytes": "1613350"
},
{
"name": "PHP",
"bytes": "15766"
},
{
"name": "Shell",
"bytes": "1583"
},
{
"name": "XSLT",
"bytes": "107653"
}
],
"symlink_target": ""
} |
@interface AttachmentsViewController : UITableViewController
@property (nonatomic, retain) NSArray *attachments;
@end
| {
"content_hash": "738231740d7ae6ef4d513a6129cc13c5",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 60,
"avg_line_length": 29.75,
"alnum_prop": 0.8319327731092437,
"repo_name": "shengbinmeng/UniBBS",
"id": "0866998e4b3b57f10d31b914c8b8be554329fc5d",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UniBBS/AttachmentsViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "149657"
},
{
"name": "Ruby",
"bytes": "301"
}
],
"symlink_target": ""
} |
<?php
/**
* This is a PHP 5.2 compatible fallback implementation of the BlackfireSpan provided by the extension.
* The interfaces and behavior are the same, or as close as possible.
*
* A general rule of design is that this fallback (as the extension) does not generate any exception.
*/
class BlackfireSpan
{
private $id;
private $name;
private $category;
private $meta;
private $finished = false;
public function __construct($name = null, $category = null, array $meta = array())
{
$this->id = microtime(true).mt_rand(0, 9999);
$this->name = $name;
$this->category = $category;
$this->meta = $meta;
$this->addEntry(http_build_query(array_merge($meta, array(
'__type__' => 'start',
'__id__' => $this->id,
'__name__' => $name,
'__category__' => $category,
)), '', '&'));
}
public function __destruct()
{
if (!$this->finished) {
$this->stop();
}
}
public function stop(array $meta = array())
{
if ($this->finished) {
trigger_error('Attempt to stop an already stopped BlackfireSpan', E_USER_WARNING);
return;
}
$this->addEntry(http_build_query(array_merge($meta, array(
'__type__' => 'stop',
'__id__' => $this->id,
)), '', '&'));
$this->finished = true;
}
public function addEvent($description, array $meta = array())
{
$this->addEntry(http_build_query(array_merge($meta, array(
'__type__' => 'event',
'__description__' => $description,
'__id__' => $this->id,
)), '', '&'));
}
public function lap()
{
$this->stop();
return new self($this->name, $this->category, $this->meta);
}
private function addEntry($entry)
{
$entry = ''; // prevent OPcache optimization
}
}
| {
"content_hash": "2add55e829cb7f8b41af787ea6844154",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 103,
"avg_line_length": 25.776315789473685,
"alnum_prop": 0.5181214905564063,
"repo_name": "blackfireio/php-sdk",
"id": "998b00dd64c6a52b7670d0b17d7030b630f0199c",
"size": "2189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BlackfireSpan.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "206819"
}
],
"symlink_target": ""
} |
package com.seasonfif.matrix.proxy;
import android.content.Context;
import com.seasonfif.matrix.card.ICard;
import com.seasonfif.matrix.card.ICardFactory;
import com.seasonfif.matrix.helper.CardCache;
/**
* 创建时间:2017年05月18日18:05 <br>
* 作者:zhangqiang <br>
* 描述:工厂代理
*/
public class FactoryProxy implements ICardFactory {
private CardCache cardCache;
private ICardFactory factory;
public FactoryProxy(ICardFactory factory){
this.factory = factory;
cardCache = CardCache.getInstance();
}
@Override public ICard createCard(Context context, int type) {
/*ICard card = cardCache.get(type);
if (card == null){
card = factory.createCard(context, type);
cardCache.set(type, card);
}*/
ICard card = factory.createCard(context, type);
return card;
}
}
| {
"content_hash": "20b18c9b23bc7aa94cce45eb51d14984",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 64,
"avg_line_length": 22.38888888888889,
"alnum_prop": 0.7121588089330024,
"repo_name": "seasonfif/TheDemo",
"id": "731fabf6a6e13e0b9955cd1844dfc4f0d878b98e",
"size": "842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "matrix/src/main/java/com/seasonfif/matrix/proxy/FactoryProxy.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1112"
},
{
"name": "Java",
"bytes": "361852"
},
{
"name": "JavaScript",
"bytes": "1557"
},
{
"name": "Shell",
"bytes": "586"
}
],
"symlink_target": ""
} |
import { Meteor } from 'meteor/meteor';
Meteor.publish('userData', function() {
if (!this.userId) {
return this.ready();
}
return RocketChat.models.Users.find(this.userId, {
fields: {
name: 1,
username: 1,
status: 1,
statusDefault: 1,
statusConnection: 1,
avatarOrigin: 1,
utcOffset: 1,
language: 1,
settings: 1,
enableAutoAway: 1,
idleTimeLimit: 1,
roles: 1,
active: 1,
defaultRoom: 1,
customFields: 1,
'services.github': 1,
'services.gitlab': 1,
'services.tokenpass': 1,
'services.blockstack': 1,
requirePasswordChange: 1,
requirePasswordChangeReason: 1,
'services.password.bcrypt': 1,
'services.totp.enabled': 1,
statusLivechat: 1,
banners: 1,
},
});
});
| {
"content_hash": "f32f0ee6c09833efd83a064a99ce989e",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 51,
"avg_line_length": 20.135135135135137,
"alnum_prop": 0.636241610738255,
"repo_name": "pkgodara/Rocket.Chat",
"id": "3bd9f8a24c634ecb424943c43509334b46a26202",
"size": "745",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "server/publications/userData.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "549"
},
{
"name": "CSS",
"bytes": "396722"
},
{
"name": "Cap'n Proto",
"bytes": "3960"
},
{
"name": "CoffeeScript",
"bytes": "30843"
},
{
"name": "Dockerfile",
"bytes": "1874"
},
{
"name": "HTML",
"bytes": "435005"
},
{
"name": "JavaScript",
"bytes": "4302907"
},
{
"name": "Ruby",
"bytes": "4653"
},
{
"name": "Shell",
"bytes": "30169"
},
{
"name": "Standard ML",
"bytes": "1843"
}
],
"symlink_target": ""
} |
package com.aviary.android.feather.widget;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.CursorAdapter;
import android.text.Html;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.aviary.android.feather.R;
import com.aviary.android.feather.cds.AviaryCds;
import com.aviary.android.feather.cds.AviaryCds.ContentType;
import com.aviary.android.feather.cds.AviaryCds.PackType;
import com.aviary.android.feather.cds.AviaryCdsDownloaderFactory;
import com.aviary.android.feather.cds.AviaryCdsDownloaderFactory.Downloader;
import com.aviary.android.feather.cds.AviaryCdsValidatorFactory;
import com.aviary.android.feather.cds.AviaryCdsValidatorFactory.Validator;
import com.aviary.android.feather.cds.CdsUtils;
import com.aviary.android.feather.cds.CdsUtils.PackOption;
import com.aviary.android.feather.cds.CdsUtils.Resolution;
import com.aviary.android.feather.cds.IAPWrapper;
import com.aviary.android.feather.cds.PacksColumns;
import com.aviary.android.feather.cds.PacksColumns.PackCursorWrapper;
import com.aviary.android.feather.cds.PacksContentColumns;
import com.aviary.android.feather.cds.PacksItemsColumns;
import com.aviary.android.feather.cds.billing.util.IabHelper;
import com.aviary.android.feather.cds.billing.util.IabResult;
import com.aviary.android.feather.common.AviaryIntent;
import com.aviary.android.feather.common.log.LoggerFactory;
import com.aviary.android.feather.common.log.LoggerFactory.Logger;
import com.aviary.android.feather.common.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.common.utils.PackageManagerUtils;
import com.aviary.android.feather.common.utils.SystemUtils;
import com.aviary.android.feather.common.utils.os.AviaryAsyncTask;
import com.aviary.android.feather.graphics.CdsPreviewTransformer;
import com.aviary.android.feather.library.Constants;
import com.aviary.android.feather.library.services.BadgeService;
import com.aviary.android.feather.library.services.IAPService;
import com.aviary.android.feather.utils.PackIconCallable;
import com.aviary.android.feather.widget.AviaryWorkspace.OnPageChangeListener;
import com.aviary.android.feather.widget.CellLayout.CellInfo;
import com.aviary.android.feather.widget.IAPDialogMain.IAPUpdater;
import com.aviary.android.feather.widget.IAPDialogMain.PackOptionWithPrice;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
public class IAPDialogDetail extends LinearLayout implements OnPageChangeListener, OnClickListener {
// listen to pack purchase status change
ContentObserver mPackPurchasedContentObserver = new ContentObserver( new Handler() ) {
@Override
public void onChange( boolean selfChange ) {
onChange( selfChange, null );
}
@Override
public void onChange( boolean selfChange, Uri uri ) {
logger.info( "** mPackPurchasedContentObserver::onChange **" );
if ( !isValidContext() || null == mData || null == mPack || null == mPack.getContent() ) return;
if ( null != uri ) {
int purchased = Integer.parseInt( uri.getLastPathSegment() );
long packId = Integer.parseInt( uri.getPathSegments().get( uri.getPathSegments().size() - 2 ) );
logger.log( "purchased status changed(%d) for packId: %d", purchased, packId );
if ( null != mPriceMap ) {
mPriceMap.put( packId, new PackOptionWithPrice( purchased == 1 ? PackOption.OWNED : PackOption.ERROR ) );
}
}
determinePackOption( mPack, true );
};
};
ContentObserver mPackContentObserver = new ContentObserver( new Handler() ) {
@Override
public void onChange( boolean selfChange ) {
onChange( selfChange, null );
};
@Override
public void onChange( boolean selfChange, Uri uri ) {
logger.info( "** mPackContentObserver::onChange **" );
if ( !isValidContext() || null == mPack || null == mPack.getContent() ) return;
updatePlugin( true );
}
};
private IAPUpdater mData;
private PacksColumns.PackCursorWrapper mPack;
private IAPDialogMain mParent;
private HashMap<Long, PackOptionWithPrice> mPriceMap;
private int mMainLayoutResId = R.layout.aviary_iap_workspace_screen_stickers;
private int mCellResId = R.layout.aviary_iap_cell_item_effects;
private View mErrorView;
private TextView mErrorText;
private TextView mRetryButton;
private View mLoader;
private AviaryTextView mTitle, mDescription;
private IAPBuyButton mButtonContainer;
private AviaryWorkspace mWorkspace;
private AviaryWorkspaceIndicator mWorkspaceIndicator;
private ImageView mIcon;
private View mHeadView;
private IAPService mIapService;
private Picasso mPicassoLibrary;
private WorkspaceAdapter mWorkspaceAdapter;
private View mBannerView;
private boolean mDownloadOnDemand = true;
private boolean mAttached;
// workspace attributes
int mRows = 1;
int mCols = 1;
int mItemsPerPage;
private static Logger logger = LoggerFactory.getLogger( "iap-dialog-detail", LoggerType.ConsoleLoggerType );
public IAPDialogDetail ( Context context, AttributeSet attrs ) {
super( context, attrs );
mDownloadOnDemand = SystemUtils.getApplicationTotalMemory() < Constants.APP_MEMORY_LARGE;
}
public IAPUpdater getData() {
return mData;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
logger.info( "onAttachedFromWindow" );
mAttached = true;
mPicassoLibrary = Picasso.with( getContext() );
mIcon = (ImageView) findViewById( R.id.aviary_icon );
mButtonContainer = (IAPBuyButton) findViewById( R.id.aviary_buy_button );
mHeadView = findViewById( R.id.aviary_head );
mTitle = (AviaryTextView) findViewById( R.id.aviary_title );
mDescription = (AviaryTextView) findViewById( R.id.aviary_description );
mWorkspace = (AviaryWorkspace) findViewById( R.id.aviary_workspace );
mWorkspaceIndicator = (AviaryWorkspaceIndicator) findViewById( R.id.aviary_workspace_indicator );
mLoader = findViewById( R.id.aviary_progress );
mBannerView = findViewById( R.id.aviary_banner_view );
mErrorView = findViewById( R.id.aviary_error_message );
if ( null != mErrorView ) {
mErrorText = (TextView) mErrorView.findViewById( R.id.aviary_retry_text );
mRetryButton = (TextView) mErrorView.findViewById( R.id.aviary_retry_button );
if ( null != mRetryButton ) {
if ( !isInEditMode() ) mRetryButton
.setText( Html.fromHtml( String.format( getContext().getResources().getString( R.string.feather_try_again ) ) ) );
mRetryButton.setOnClickListener( this );
}
}
mButtonContainer.setOnClickListener( this );
if( PackageManagerUtils.isStandalone( getContext() ) ) {
mBannerView.setOnClickListener( this );
} else {
mBannerView.setVisibility( View.GONE );
}
mWorkspaceAdapter = new WorkspaceAdapter( getContext(), null, -1, null );
mWorkspace.setAdapter( mWorkspaceAdapter );
mWorkspace.setIndicator( mWorkspaceIndicator );
}
private void computeLayoutItems( Resources res, String packType ) {
if ( AviaryCds.PACKTYPE_EFFECT.equals( packType ) || AviaryCds.PACKTYPE_FRAME.equals( packType ) ) {
mMainLayoutResId = R.layout.aviary_iap_workspace_screen_effects;
mCols = res.getInteger( R.integer.aviary_iap_dialog_cols_effects );
mRows = res.getInteger( R.integer.aviary_iap_dialog_rows_effects );
mCellResId = R.layout.aviary_iap_cell_item_effects;
} else {
mMainLayoutResId = R.layout.aviary_iap_workspace_screen_stickers;
mCols = res.getInteger( R.integer.aviary_iap_dialog_cols_stickers );
mRows = res.getInteger( R.integer.aviary_iap_dialog_rows_stickers );
mCellResId = R.layout.aviary_iap_cell_item_stickers;
}
mItemsPerPage = mRows * mCols;
}
@Override
protected void onDetachedFromWindow() {
logger.info( "onDetachedFromWindow" );
super.onDetachedFromWindow();
// unregister content observer
unregisterContentObservers();
mButtonContainer.setOnClickListener( null );
mRetryButton.setOnClickListener( null );
mWorkspace.setTag( null );
mWorkspaceAdapter.changeCursor( null );
mWorkspace.setAdapter( null );
mWorkspace.setOnPageChangeListener( null );
mIapService = null;
mAttached = false;
}
@Override
public void onClick( View v ) {
final int id = v.getId();
if ( id == mBannerView.getId() ) {
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setComponent( AviaryIntent.getTutorialComponent( getContext() ) );
intent.setData( Uri.parse( "aviary://launch-activity/iap_tutorial" ) );
try {
getContext().startActivity( intent );
} catch ( ActivityNotFoundException e ) {
e.printStackTrace();
}
}
else if ( id == mRetryButton.getId() ) {
logger.info( "retry" );
update( getData(), mParent );
} else if ( id == mButtonContainer.getId() ) {
PackOptionWithPrice packOption = mButtonContainer.getPackOption();
if ( null != packOption ) {
switch ( packOption.option ) {
case PURCHASE:
if ( null != mPack && null != mPack.getContent() ) {
mParent.launchPackPurchaseFlow( mPack.getId(), mPack.getIdentifier(), mPack.getPackType(), "DetailView", packOption.price );
}
break;
case ERROR:
if ( null != mPriceMap ) mPriceMap.remove( mPack.getId() );
updatePlugin( false );
break;
case FREE:
case RESTORE:
IAPDialogMain.trackBeginPurchaseFlow( getContext(), mPack.getIdentifier(), mPack.getPackType(), "DetailView", packOption.price,
packOption.option == PackOption.RESTORE, packOption.option == PackOption.FREE );
case DOWNLOAD_ERROR:
PackOptionWithPrice newOption;
if( packOption.option == PackOption.FREE ) {
mParent.sendReceipt( mPack.getIdentifier(), true, false );
} else if( packOption.option == PackOption.RESTORE ){
mParent.sendReceipt( mPack.getIdentifier(), false, true );
}
try {
mParent.requestPackDownload( mPack.getId() );
Pair<PackOption, String> pair = CdsUtils.getPackOptionDownloadStatus( getContext(), mPack.getId() );
if( null != pair ) {
newOption = new PackOptionWithPrice( pair.first );
} else {
newOption = new PackOptionWithPrice( PackOption.DOWNLOADING );
}
} catch( Throwable t ) {
newOption = new PackOptionWithPrice( PackOption.DOWNLOAD_ERROR, null );
StringBuilder sb = new StringBuilder();
sb.append( getContext().getString( R.string.feather_download_start_failed ) );
sb.append( "." );
sb.append( "\n" );
sb.append( "Cause: " );
sb.append( t.getLocalizedMessage() );
new AlertDialog.Builder( getContext() )
.setTitle( R.string.feather_iap_download_failed )
.setMessage( sb.toString() )
.setPositiveButton( android.R.string.cancel, null )
.create()
.show();
}
onPackOptionUpdated( newOption, mPack );
break;
default:
break;
}
}
}
}
// TODO: implement this better!
void onDownloadStatusChanged( Uri uri ) {
if ( !isValidContext() || null == mPack || null == mData ) return;
logger.info( "** onDownloadStatusChanged: %s **", uri );
determinePackOption( mPack, false );
}
void onPurchaseSuccess( long packId, String identifier, String packType ) {
logger.info( "onPurchaseSuccess: %s - %s", identifier, packType );
updatePlugin( false );
}
private void initWorkspace( PacksColumns.PackCursorWrapper pack ) {
if ( null != pack && null != getContext() ) {
Long oldTag = (Long) mWorkspace.getTag();
if ( null != oldTag && oldTag == pack.getId() ) {
logger.warn( "ok, don't reload the workspace, same tag found" );
return;
}
Cursor cursor = getContext().getContentResolver().query(
PackageManagerUtils.getCDSProviderContentUri( getContext(), "pack/" + pack.getId() + "/item/list" ),
new String[] { PacksItemsColumns._ID + " as _id", PacksColumns.PACK_TYPE, PacksItemsColumns._ID, PacksItemsColumns.IDENTIFIER,
PacksItemsColumns.DISPLAY_NAME }, null, null, null );
mWorkspaceAdapter.setBaseDir( pack.getContent().getPreviewPath() );
mWorkspaceAdapter.setFileExt( AviaryCds.getPreviewItemExt( mData.getPackType() ) );
mWorkspaceAdapter.changeCursor( cursor );
mWorkspace.setOnPageChangeListener( this );
mWorkspace.setTag( Long.valueOf( pack.getId() ) );
mLoader.setVisibility( View.GONE );
if ( null == cursor || cursor.getCount() <= mItemsPerPage ) {
mWorkspaceIndicator.setVisibility( View.INVISIBLE );
} else {
mWorkspaceIndicator.setVisibility( View.VISIBLE );
}
} else {
logger.error( "invalid plugin" );
mWorkspaceAdapter.changeCursor( null );
mWorkspace.setTag( null );
mWorkspace.setOnPageChangeListener( null );
mWorkspaceIndicator.setVisibility( View.INVISIBLE );
}
}
public void update( IAPUpdater updater, IAPDialogMain parent ) {
if ( null == updater ) return;
boolean forceUpdate = true;
if ( updater.equals( mData ) ) {
forceUpdate = false;
}
logger.info( "update: %s, forceUpdate: %b", updater, forceUpdate );
mData = (IAPUpdater) updater.clone();
mParent = parent;
mPriceMap = mParent.getPriceMap( mData.getPackType() );
mPack = null;
if ( null != mParent.getController() ) {
mIapService = mParent.getController().getService( IAPService.class );
}
registerContentObserver( mData.getPackId() );
// initialize the display process
if ( forceUpdate ) {
processPlugin();
} else {
updatePlugin( true );
}
}
private void registerContentObserver( long pack_id ) {
logger.info( "registerContentObserver" );
if ( null != getContext() ) {
getContext().getContentResolver().registerContentObserver( PackageManagerUtils.getCDSProviderContentUri( getContext(), "pack/contentUpdated/" + pack_id ), false,
mPackContentObserver );
getContext().getContentResolver().registerContentObserver( PackageManagerUtils.getCDSProviderContentUri( getContext(), "pack/purchased/" + pack_id ), true,
mPackPurchasedContentObserver );
}
}
private void unregisterContentObservers() {
logger.info( "unregisterContentObservers" );
if ( null != getContext() ) {
getContext().getContentResolver().unregisterContentObserver( mPackContentObserver );
getContext().getContentResolver().unregisterContentObserver( mPackPurchasedContentObserver );
}
}
/**
* Error downloading plugin informations
*/
private void onDownloadError() {
logger.info( "onDownloadError" );
mErrorView.setVisibility( View.VISIBLE );
mLoader.setVisibility( View.GONE );
mButtonContainer.setVisibility( View.GONE );
mWorkspaceAdapter.changeCursor( null );
mWorkspace.setTag( null );
mTitle.setText( "" );
if ( null != mErrorText ) {
mErrorText.setText( R.string.feather_item_not_found );
}
}
private void onDownloadPreviewError( String message ) {
mErrorView.setVisibility( View.VISIBLE );
mLoader.setVisibility( View.GONE );
mWorkspaceAdapter.changeCursor( null );
mWorkspace.setTag( null );
if ( null != mErrorText ) {
mErrorText.setText( R.string.feather_iap_failed_download_previews );
}
}
private void updatePlugin( boolean update ) {
if ( !isValidContext() || null == mData ) return;
logger.info( "updatePlugin: " + update );
if ( update || mPack == null || null == mPack.getContent() ) {
mPack = CdsUtils.getPackFullInfoById( getContext(), mData.getPackId() );
if ( null == mPack || null == mPack.getContent() ) {
logger.error( "pack or content are null" );
onDownloadError();
return;
}
}
mButtonContainer.setVisibility( View.VISIBLE );
mWorkspaceIndicator.setVisibility( View.INVISIBLE );
mTitle.setText( mPack.getContent().getDisplayName() );
mTitle.setSelected( true );
mDescription.setText( mPack.getContent().getDisplayDescription() != null ? mPack.getContent().getDisplayDescription() : "" );
int delayTime = getResources().getInteger( android.R.integer.config_mediumAnimTime ) + 300;
Handler handler = getHandler();
if( null != handler ) {
// download the pack icon, if necessary
downloadPackIcon( mPack, mPack.getContent() );
handler.postDelayed( new Runnable() {
@Override
public void run() {
if( null != mPack && null != mPack.getContent() ) {
// update price button
determinePackOption( (PacksColumns.PackCursorWrapper) mPack.clone(), false );
// download the pack previews
downloadPackPreviews( mPack );
}
}
}, delayTime );
}
}
/**
* display and download informations
* about the selected pack
*/
private void processPlugin() {
logger.info( "processPlugin" );
if ( !isValidContext() || null == mData ) return;
// invalidate current UI
mIcon.setTag( null );
mIcon.setImageBitmap( null );
mButtonContainer.setPackOption( new PackOptionWithPrice( PackOption.PACK_OPTION_BEING_DETERMINED ), -1 );
mErrorView.setVisibility( View.GONE );
// invalidate the workspace
mWorkspace.setTag( null );
mWorkspaceAdapter.changeCursor( null );
// load the pack informations
mPack = CdsUtils.getPackFullInfoById( getContext(), mData.getPackId() );
if ( null == mPack || null == mPack.getContent() ) {
logger.error( "pack or content are null" );
onDownloadError();
return;
}
// mark pack as 'read'
if ( null != mParent.getController() ) {
BadgeService badgeService = mParent.getController().getService( BadgeService.class );
if ( null != badgeService ) {
badgeService.markAsRead( mPack.getIdentifier() );
}
}
// update workspace
computeLayoutItems( getContext().getResources(), mPack.getPackType() );
mWorkspaceAdapter.setContext( getContext() );
mWorkspaceAdapter.setResourceId( mMainLayoutResId );
mWorkspaceAdapter.setBaseDir( null );
// update plugin content
updatePlugin( false );
if ( null != mHeadView ) {
mHeadView.requestFocus();
mHeadView.requestFocusFromTouch();
}
}
/**
* Update the price button
*
* @param option
* @param pack
*/
private void onPackOptionUpdated( PackOptionWithPrice option, final PacksColumns.PackCursorWrapper pack ) {
if ( !isValidContext() || null == pack || null == pack.getContent() ) return;
if ( !pack.equals( mPack ) ) return;
logger.log( "onPackOptionUpdated: %s, packId: %d", option, pack.getId() );
mButtonContainer.setPackOption( option, pack.getId() );
}
private void determinePackOption( PacksColumns.PackCursorWrapper pack, boolean update ) {
logger.info( "determinePackOption: " + update );
if( null == pack ) {
logger.error( "pack is null" );
return;
}
Pair<PackOption, String> pair = CdsUtils.getPackOptionDownloadStatus( getContext(), pack.getId() );
PackOptionWithPrice downloadStatus = null;
if ( null != pair ) {
downloadStatus = new PackOptionWithPrice( pair.first );
onPackOptionUpdated( downloadStatus, pack );
if ( downloadStatus.option != PackOption.DOWNLOAD_COMPLETE ) {
return;
}
}
if ( update ) {
new DeterminePackOptionAsyncTask( update ).execute( pack );
} else {
PackOptionWithPrice newResult = mPriceMap.get( pack.getId() );
if( null != newResult ) {
if( null != downloadStatus ) {
if ( downloadStatus.option == PackOption.DOWNLOAD_COMPLETE
&& ( newResult.option == PackOption.RESTORE || newResult.option == PackOption.FREE ) ) {
// special case ( still installing )
newResult = downloadStatus;
}
}
onPackOptionUpdated( newResult, pack );
} else {
new DeterminePackOptionAsyncTask( update ).execute( pack );
}
}
}
/**
* Fetch the current pack icon
*
* @param plugin
*/
private void downloadPackIcon( PacksColumns.PackCursorWrapper pack, PacksContentColumns.ContentCursorWrapper plugin ) {
logger.info( "downloadPackIcon" );
if ( null != plugin ) {
if ( null != mIcon ) {
String iconPath = plugin.getIconPath();
String tag = (String) mIcon.getTag();
if ( null != tag ) {
if ( tag.equals( plugin.getIconURL() ) ) {
logger.warn( "icon already downloaded!" );
return;
}
}
mPicassoLibrary
.load( iconPath )
.error( R.drawable.aviary_ic_na )
.resizeDimen( R.dimen.aviary_iap_detail_icon_maxsize, R.dimen.aviary_iap_detail_icon_maxsize, true )
.transform( new PackIconCallable( getResources(), mData.getPackType(), iconPath ) )
.into( mIcon );
}
}
}
private void downloadPackPreviews( PacksColumns.PackCursorWrapper pack ) {
logger.info( "downloadPackPreviews" );
if ( null == getContext() ) return;
if ( null == pack || null == pack.getContent() ) return;
final String previewPath = pack.getContent().getPreviewPath();
if ( null != previewPath ) {
File file = new File( previewPath );
boolean preview_valid = false;
Validator validator = AviaryCdsValidatorFactory.create( ContentType.PREVIEW, PackType.fromString( pack.getPackType() ) );
try {
preview_valid = validator.validate( getContext(), pack.getContent().getId(), file, false );
} catch ( AssertionError e ) {
e.printStackTrace();
preview_valid = false;
}
if ( preview_valid ) {
initWorkspace( mPack );
return;
}
}
RemotePreviewDownloader task = new RemotePreviewDownloader( mPack );
task.execute( mPack.getId() );
}
class WorkspaceAdapter extends CursorAdapter {
LayoutInflater mLayoutInflater;
int mResId;
String mBaseDir;
String mFileExt;
int mTargetDensity;
int mInputDensity;
int columnIndexType;
int columnIndexDisplayName;
int columnIndexIdentifier;
public WorkspaceAdapter ( Context context, String baseDir, int resource, Cursor cursor ) {
super( context, cursor, false );
mResId = resource;
mLayoutInflater = LayoutInflater.from( getContext() );
mBaseDir = baseDir;
mTargetDensity = context.getResources().getDisplayMetrics().densityDpi;
Resolution resolution = CdsUtils.getResolution( context );
switch ( resolution ) {
case HIGH:
mInputDensity = DisplayMetrics.DENSITY_XHIGH;
break;
case LOW:
mInputDensity = DisplayMetrics.DENSITY_MEDIUM;
break;
}
initCursor( cursor );
}
@Override
public Cursor swapCursor( Cursor newCursor ) {
initCursor( newCursor );
recycleBitmaps();
return super.swapCursor( newCursor );
}
private void recycleBitmaps() {
logger.info( "recycleBitmaps" );
int count = mWorkspace.getChildCount();
for ( int i = 0; i < count; i++ ) {
CellLayout view = (CellLayout) mWorkspace.getChildAt( i );
int cells = view.getChildCount();
for ( int k = 0; k < cells; k++ ) {
ImageView imageView = (ImageView) view.getChildAt( k );
if ( null != imageView ) {
Drawable drawable = imageView.getDrawable();
if ( null != drawable && ( drawable instanceof BitmapDrawable ) ) {
imageView.setImageBitmap( null );
Bitmap bitmap = ( (BitmapDrawable) drawable ).getBitmap();
if ( null != bitmap && !bitmap.isRecycled() ) {
bitmap.recycle();
}
}
}
}
}
}
private void initCursor( Cursor cursor ) {
if ( null != cursor ) {
columnIndexDisplayName = cursor.getColumnIndex( PacksItemsColumns.DISPLAY_NAME );
columnIndexIdentifier = cursor.getColumnIndex( PacksItemsColumns.IDENTIFIER );
columnIndexType = cursor.getColumnIndex( PacksColumns.PACK_TYPE );
}
}
public void setContext( Context context ) {
mContext = context;
}
public void setResourceId( int resid ) {
mResId = resid;
}
public void setBaseDir( String dir ) {
mBaseDir = dir;
}
public String getBaseDir() {
return mBaseDir;
}
public void setFileExt( String file_ext ) {
mFileExt = file_ext;
}
@Override
public int getCount() {
return (int) Math.ceil( (double) super.getCount() / mItemsPerPage );
}
/**
* Gets the real num of items.
*
* @return the real count
*/
public int getRealCount() {
return super.getCount();
}
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mLayoutInflater.inflate( mResId, parent, false );
return view;
}
@Override
public void bindView( View view, Context context, Cursor cursor ) {
int page = cursor.getPosition();
int position = page * mItemsPerPage;
CellLayout cell = (CellLayout) view;
cell.setNumCols( mCols );
cell.setNumRows( mRows );
for ( int i = 0; i < mItemsPerPage; i++ ) {
View toolView;
CellInfo cellInfo = cell.findVacantCell();
if ( cellInfo == null ) {
toolView = cell.getChildAt( i );
} else {
toolView = mLayoutInflater.inflate( mCellResId, mWorkspace, false );
CellLayout.LayoutParams lp = new CellLayout.LayoutParams( cellInfo.cellX, cellInfo.cellY, cellInfo.spanH, cellInfo.spanV );
cell.addView( toolView, -1, lp );
}
final int index = position + i;
final ImageView imageView = (ImageView) toolView.findViewById( R.id.aviary_image );
int maxW = mWorkspace.getWidth() / mCols;
int maxH = mWorkspace.getHeight() / mRows;
if ( index < getRealCount() ) {
loadImage( i * 60, position + i, imageView, mDownloadOnDemand, maxW, maxH );
} else {
// else...
// imageView.setTag( null );
if( null != imageView ) {
imageView.setImageBitmap( null );
}
}
}
view.requestLayout();
}
public void loadImage( int delay, int position, final ImageView imageView, boolean onDemand, int maxW, int maxH ) {
Cursor cursor = (Cursor) getItem( position );
if ( null != cursor && !cursor.isAfterLast() && null != imageView ) {
String identifier = cursor.getString( columnIndexIdentifier );
String displayName = cursor.getString( columnIndexDisplayName );
String type = cursor.getString( columnIndexType );
File file = new File( getBaseDir(), identifier + ( mFileExt ) );
final String path = file.getAbsolutePath();
final int imageTag = path.hashCode();
final Integer tag = (Integer) imageView.getTag();
final boolean same = ( tag != null && tag.equals( imageTag ) );
if ( onDemand ) {
if ( !same ) {
imageView.setTag( null );
imageView.setImageBitmap( null );
}
} else {
if ( !same ) {
mPicassoLibrary.load( path )
.fit()
.centerInside()
.withDelay( delay )
// .skipMemoryCache() // don't use cache for previews
.error( R.drawable.aviary_ic_na )
.transform( new CdsPreviewTransformer( path, displayName, type ) ).into( imageView, new Callback() {
@Override
public void onSuccess() {
logger.log( "onSuccess: %d", imageTag );
imageView.setTag( Integer.valueOf( imageTag ) );
}
public void onError() {}
} );
}
}
}
}
}
@Override
public void onPageChanged( int which, int old ) {
logger.info( "onPageChanged: " + old + " >> " + which );
if ( !mDownloadOnDemand ) return;
if ( null == getContext() ) return;
if ( null != mWorkspace ) {
WorkspaceAdapter adapter = (WorkspaceAdapter) mWorkspace.getAdapter();
int index = which * mItemsPerPage;
int endIndex = index + mItemsPerPage;
int total = adapter.getRealCount();
for ( int i = index; i < endIndex; i++ ) {
CellLayout cellLayout = (CellLayout) mWorkspace.getScreenAt( which );
if( null == cellLayout ) continue;
ImageView toolView = (ImageView) cellLayout.getChildAt( i - index );
int maxW = mWorkspace.getWidth() / mCols;
int maxH = mWorkspace.getHeight() / mRows;
if ( i < total ) {
adapter.loadImage( i * 60, i, toolView, false, maxW, maxH );
}
}
// if download on demand, then cleanup the old page bitmaps
if ( mDownloadOnDemand && old != which ) {
CellLayout cellLayout = (CellLayout) mWorkspace.getScreenAt( old );
if ( null != cellLayout ) {
for ( int i = 0; i < cellLayout.getChildCount(); i++ ) {
View toolView = cellLayout.getChildAt( i );
ImageView imageView = (ImageView) toolView.findViewById( R.id.aviary_image );
if ( null != imageView ) {
imageView.setImageBitmap( null );
imageView.setTag( null );
}
}
}
}
}
}
/**
* Download the pack previews
* @author alessandro
*/
class RemotePreviewDownloader extends AviaryAsyncTask<Long, Void, String> {
private PacksColumns.PackCursorWrapper mCurrentPack;
private Throwable mError;
public RemotePreviewDownloader ( PacksColumns.PackCursorWrapper pack ) {
mCurrentPack = (PacksColumns.PackCursorWrapper) pack.clone();
}
@Override
protected void PostExecute( String result ) {
if ( isCancelled() ) return;
if ( !isValidContext() || null == mPack ) return;
if ( !mPack.equals( mCurrentPack ) ) {
logger.warn( "different pack!" );
return;
}
logger.info( "RemotePreviewDownloader::PostExecute: %s", result );
logger.error( "error: " + mError );
if ( null != result ) {
mLoader.setVisibility( View.GONE );
}
if ( null != mError && null != mError.getMessage() ) {
onDownloadPreviewError( mError.getMessage() );
}
}
@Override
protected void PreExecute() {
logger.info( "RemotePreviewDownloader::PreExecute" );
if ( null == getContext() || mPack == null ) return;
if ( !mPack.equals( mCurrentPack ) ) return;
mLoader.setVisibility( View.VISIBLE );
mErrorView.setVisibility( View.GONE );
}
@Override
protected String doInBackground( Long... params ) {
logger.info( "RemotePreviewDownloader::doInBackground" );
Downloader downloader = AviaryCdsDownloaderFactory.create( ContentType.PREVIEW );
String result = null;
try {
result = downloader.download( getContext(), params[0] );
} catch ( IOException e ) {
e.printStackTrace();
mError = e;
} catch ( AssertionError e ) {
e.printStackTrace();
mError = e;
}
return result;
}
}
class DeterminePackOptionAsyncTask extends AviaryAsyncTask<PacksColumns.PackCursorWrapper, PackOptionWithPrice, PackOptionWithPrice> {
IabResult mResult;
PacksColumns.PackCursorWrapper mPack;
boolean mForceUpdate;
IabResult mIabResult;
public DeterminePackOptionAsyncTask ( boolean update ) {
mForceUpdate = update;
}
@Override
protected void PreExecute() {}
@Override
protected PackOptionWithPrice doInBackground( PackCursorWrapper... params ) {
if ( !isValidContext() ) return null;
logger.info( "DeterminePackOptionAsyncTask::doInBackground" );
PacksColumns.PackCursorWrapper pack = params[0];
mPack = (PacksColumns.PackCursorWrapper) pack.clone();
PackOptionWithPrice result = null;
// 1. first check if it's in the download queue
Pair<PackOption, String> pair = CdsUtils.getPackOptionDownloadStatus( getContext(), pack.getId() );
if ( null != pair ) {
result = new PackOptionWithPrice( pair.first, null );
if ( result.option == PackOption.DOWNLOAD_COMPLETE ) {
publishProgress( result );
} else {
return result;
}
}
if ( null != result && result.option == PackOption.DOWNLOAD_COMPLETE ) {
SystemUtils.trySleep( 1200 );
}
// 2. check the cache
if ( !mForceUpdate ) {
result = mPriceMap.get( pack.getId() );
if ( null != result ) {
logger.log( "from the cache: %s", result );
return result;
}
}
// 3. check pack option status ( free/restore/owned )
result = new PackOptionWithPrice( CdsUtils.getPackOption( getContext(), pack ), null );
logger.log( "CdsUtils.getPackOption: %s", result );
if ( result.option == PackOption.PACK_OPTION_BEING_DETERMINED ) {
publishProgress( result );
// need to check the google play inventory
IAPWrapper wrapper = null;
if ( null != mIapService ) {
wrapper = mIapService.available();
}
if ( null != wrapper ) {
mIabResult = CdsUtils.waitForIAPSetupDone( wrapper );
}
if ( null != mIabResult && mIabResult.isSuccess() ) {
result = IAPDialogMain.getFromInventory( wrapper, pack.getIdentifier() );
} else {
result = new PackOptionWithPrice( PackOption.ERROR );
}
logger.log( "getFromInventory: %s", result );
}
// 4. check again the download status, but only if not already owned
if ( result.option != PackOption.OWNED ) {
pair = CdsUtils.getPackOptionDownloadStatus( getContext(), pack.getId() );
if ( null != pair ) {
result = new PackOptionWithPrice( pair.first, null );
return result;
}
}
if ( PackOption.isDetermined( result.option ) ) {
mPriceMap.put( pack.getId(), result );
}
return result;
}
@Override
protected void ProgressUpdate( PackOptionWithPrice... values ) {
if ( null != values ) {
PackOptionWithPrice option = values[0];
logger.info( "DeterminePackOptionAsyncTask::ProgressUpdate: %s - %s", mPack.getContent().getDisplayName(), option );
onPackOptionUpdated( option, mPack );
}
}
@Override
protected void PostExecute( PackOptionWithPrice result ) {
if ( !isValidContext() ) return;
if ( null == mPack ) return;
logger.info( "DeterminePackOptionAsyncTask::PostExecute: %s - %s", mPack.getContent().getDisplayName(), result );
if ( null != result ) {
onPackOptionUpdated( result, mPack );
} else {
onPackOptionUpdated( new PackOptionWithPrice( PackOption.ERROR, null ), mPack );
}
if ( null != mIabResult && mIabResult.isFailure() ) {
logger.warn( mIabResult.getMessage() );
if( mIabResult.getResponse() != IabHelper.IABHELPER_MISSING_SIGNATURE ) {
Toast.makeText( getContext(), mIabResult.getMessage(), Toast.LENGTH_SHORT ).show();
}
}
}
}
boolean isValidContext() {
return mAttached && null != getContext();
}
}
| {
"content_hash": "7e99423b42cef97d49be63d865ad6f6c",
"timestamp": "",
"source": "github",
"line_count": 1108,
"max_line_length": 164,
"avg_line_length": 31.0586642599278,
"alnum_prop": 0.6899718129776538,
"repo_name": "xiuzhuo/MyAndroidLib",
"id": "11b6cd8560c5cd68cfe35c70cd182a8b6679dfc8",
"size": "34413",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Aviary-Android-SDK/src/com/aviary/android/feather/widget/IAPDialogDetail.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1619391"
}
],
"symlink_target": ""
} |
#if !PocketPC || DesignTime
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
namespace DotSpatial.Positioning.Design
{
/// <summary>
/// Provides functionality to converting values to and from <strong>Azimuth</strong>
/// objects.
/// </summary>
/// <remarks>
/// <para>This class allows any <strong>Azimuth</strong> object to be converted between
/// other data types, such as <strong>Double</strong>, <strong>Integer</strong> and
/// <strong>String</strong>. This class is used primarily during the Windows Forms
/// designer to give detailed information about properties of type
/// <strong>Azimuth</strong>, and also allows developers to type in string values such
/// as "NNW" and have them converted to <strong>Azimuth</strong> objects automatically.
/// Finally, this class controls design-time serialization of <strong>Azimuth</strong>
/// object properties.</para>
/// <para>In most situations this class is used by the Visual Studio.NET IDE and is
/// rarely created at run-time.</para>
/// </remarks>
#if Framework20
public sealed class AzimuthConverter : GeoFrameworkNumericObjectConverter
{
protected override string HandledTypeName
{
get
{
return "GeoFramework.Azimuth";
}
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
// What is the destination type?
if (destinationType == typeof(string) && value == null)
{
return "0°";
}
else if (destinationType == typeof(InstanceDescriptor))
{
// Instance descriptor. Used during Windows Forms serialization.
// Get the type of the object (probably an Azimuth)
Type AzimuthType = value.GetType();
// Is the value null?
if (value == null)
{
// Yes. Return the "Empty" static value
return new InstanceDescriptor(AzimuthType.GetField("Empty"), null);
}
else
{
// Get the properties needed to generate a constructor
object[] ConstructorParameters = new object[] { AzimuthType.GetProperty("DecimalDegrees").GetValue(value, null) };
Type[] ConstructorTypes = new Type[] { typeof(double) };
// Now activate the constructor
ConstructorInfo Constructor = AzimuthType.GetConstructor(ConstructorTypes);
return new InstanceDescriptor(Constructor, ConstructorParameters);
}
}
// Defer to the base class
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(new string[] {
"North",
"NorthNortheast",
"Northeast",
"EastNortheast",
"East",
"EastSoutheast",
"Southeast",
"SouthSoutheast",
"South",
"SouthSouthwest",
"Southwest",
"WestSouthwest",
"West",
"WestNorthwest",
"Northwest",
"NorthNorthwest" });
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
}
#else
public sealed class AzimuthConverter : ExpandableObjectConverter
{
#region ConvertFrom: Converts an object to an Azimuth
// Indicates if the type can be converted
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType.Equals(typeof(string))
|| sourceType.Equals(typeof(double))
|| sourceType.Equals(typeof(InstanceDescriptor))
|| sourceType.Equals(typeof(Azimuth)))
return true;
// Defer to the base class
return base.CanConvertFrom(context, sourceType);
}
// Converts an object of one type to an Azimuth
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
Type ValueType = value.GetType();
if (ValueType.Equals(typeof(string)))
return Angle.Parse((string)value, culture);
else if (ValueType.Equals(typeof(double)))
return new Angle((double)value);
else if (ValueType.Equals(typeof(Azimuth)))
return value;
// Defer to the base class
return base.ConvertFrom(context, culture, value);
}
#endregion
#region ConvertTo: Converts an Azimuth to another type
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType.Equals(typeof(string))
|| destinationType.Equals(typeof(double))
|| destinationType.Equals(typeof(InstanceDescriptor))
|| destinationType.Equals(typeof(Azimuth)))
return true;
// Defer to the base class
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if(destinationType.Equals(value.GetType()))
return value;
else if (destinationType.Equals(typeof(string)))
return value.ToString();
else if (destinationType.Equals(typeof(double)))
return ((Azimuth)value).DecimalDegrees;
else if (destinationType.Equals(typeof(Azimuth)))
return value;
else if (destinationType.Equals(typeof(InstanceDescriptor)))
{
ConstructorInfo Constructor = typeof(Azimuth).GetConstructor(
new Type[] { typeof(double) });
Azimuth AzimuthValue = (Azimuth)value;
return new InstanceDescriptor(Constructor, new object[] { AzimuthValue.DecimalDegrees });
}
// Defer to the base class
return base.ConvertTo(context, culture, value, destinationType);
}
#endregion
}
#endif
}
#endif | {
"content_hash": "9f23e5200f880f51334cf049bd28b6eb",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 144,
"avg_line_length": 36.628571428571426,
"alnum_prop": 0.6427457098283932,
"repo_name": "DotSpatial/DotSpatial",
"id": "01a7cb6e7bfdd51d2a4a04ae4beff5b1cba772cf",
"size": "6413",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/Core/DotSpatial.Positioning.Compact/GeoSpatial/Type Converters/AzimuthConverter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "1639"
},
{
"name": "Batchfile",
"bytes": "4625"
},
{
"name": "C#",
"bytes": "15483649"
},
{
"name": "CSS",
"bytes": "490"
},
{
"name": "HTML",
"bytes": "8176"
},
{
"name": "JavaScript",
"bytes": "133570"
},
{
"name": "Smalltalk",
"bytes": "406360"
},
{
"name": "Visual Basic .NET",
"bytes": "451767"
}
],
"symlink_target": ""
} |
<?php
namespace BenAllfree\LaravelStaplerImages\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Carbon\Carbon;
use BenAllfree\LaravelStaplerImages\Image;
class ImageAdd extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'images:add';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Add an image.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$file = $this->argument('url');
$i = Image::from_url($file,true);
echo("Image ID is {$i->id}\n");
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('url', InputArgument::REQUIRED, 'An image URL or local file.'),
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
// array('force', null, InputOption::VALUE_OPTIONAL, 'Force reprocessing.', null),
);
}
}
| {
"content_hash": "60f7cbf513381d4c35384a5528525576",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 87,
"avg_line_length": 17.783783783783782,
"alnum_prop": 0.6155015197568389,
"repo_name": "benallfree/laravel-stapler-images",
"id": "04c6d15c1bbe0bd3600fb4713ade02e549983b96",
"size": "1316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/LaravelStaplerImages/Commands/ImageAdd.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "13750"
}
],
"symlink_target": ""
} |
class Lazy(object):
def __init__(self, lazy_init):
self._lazy_init = lazy_init
def __get__(self, instance, owner):
if not instance:
return None
val = self._lazy_init(instance)
setattr(instance, self._lazy_init.__name__, val)
return val
| {
"content_hash": "b8ce579407186a329a8883f911fce4ac",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 50,
"avg_line_length": 23,
"alnum_prop": 0.6561264822134387,
"repo_name": "nkming2/google-search-telegram-bot",
"id": "e9217989e34c054ccf152bcf2f1182352ca7aafb",
"size": "334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/lazy.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "20702"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="../../../" />
<script src="list.js"></script>
<script src="page.js"></script>
<link type="text/css" rel="stylesheet" href="page.css" />
</head>
<body>
<h1>Custom Blending Equation Constants</h1>
<p>
These work with all material types. First set the material's blending mode to THREE.CustomBlending, then set the desired Blending Equation, Source Factor and Destination Factor.
</p>
<h2>Code Example</h2>
<code>
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
material.blending = THREE.CustomBlending;
material.blendEquation = THREE.AddEquation; //default
material.blendSrc = THREE.SrcAlphaFactor; //default
material.blendDst = THREE.OneMinusSrcAlphaFactor; //default
</code>
<h2>Examples</h2>
<p>[example:webgl_materials_blending_custom materials / blending / custom ]</p>
<h2>Blending Equations</h2>
<code>
THREE.AddEquation
THREE.SubtractEquation
THREE.ReverseSubtractEquation
THREE.MinEquation
THREE.MaxEquation
</code>
<h2>Source Factors</h2>
<code>
THREE.ZeroFactor
THREE.OneFactor
THREE.SrcColorFactor
THREE.OneMinusSrcColorFactor
THREE.SrcAlphaFactor
THREE.OneMinusSrcAlphaFactor
THREE.DstAlphaFactor
THREE.OneMinusDstAlphaFactor
THREE.DstColorFactor
THREE.OneMinusDstColorFactor
THREE.SrcAlphaSaturateFactor
</code>
<h2>Destination Factors</h2>
<p>
All of the Source Factors are valid as Destination Factors, except for <code>THREE.SrcAlphaSaturateFactor</code>
</p>
<h2>Source</h2>
<p>
[link:https://github.com/mrdoob/three.js/blob/master/src/constants.js src/constants.js]
</p>
</body>
</html>
| {
"content_hash": "a03eaf04d0145403ea51f617e01159d3",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 180,
"avg_line_length": 26.338461538461537,
"alnum_prop": 0.7202102803738317,
"repo_name": "Samsy/three.js",
"id": "4f6abdc60f920c0f0ed8abcad69f178b82002652",
"size": "1712",
"binary": false,
"copies": "5",
"ref": "refs/heads/dev",
"path": "docs/api/en/constants/CustomBlendingEquations.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "139"
},
{
"name": "C",
"bytes": "80088"
},
{
"name": "C++",
"bytes": "116991"
},
{
"name": "CSS",
"bytes": "19067"
},
{
"name": "GLSL",
"bytes": "93456"
},
{
"name": "HTML",
"bytes": "39375"
},
{
"name": "JavaScript",
"bytes": "4675403"
},
{
"name": "MAXScript",
"bytes": "75494"
},
{
"name": "Python",
"bytes": "525838"
},
{
"name": "Shell",
"bytes": "9173"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\Action;
use Sylius\Component\Core\Model\AvatarImage;
use Sylius\Component\Core\Repository\AvatarImageRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
final class RemoveAvatarAction
{
/** @var AvatarImageRepositoryInterface */
private $avatarRepository;
/** @var EngineInterface */
private $templatingEngine;
/** @var RouterInterface */
private $router;
/** @var CsrfTokenManagerInterface */
private $csrfTokenManager;
public function __construct(
AvatarImageRepositoryInterface $avatarRepository,
EngineInterface $templatingEngine,
RouterInterface $router,
CsrfTokenManagerInterface $csrfTokenManager
) {
$this->avatarRepository = $avatarRepository;
$this->templatingEngine = $templatingEngine;
$this->router = $router;
$this->csrfTokenManager = $csrfTokenManager;
}
public function __invoke(Request $request): Response
{
$userId = $request->attributes->get('id');
if (!$this->csrfTokenManager->isTokenValid(new CsrfToken($userId, $request->query->get('_csrf_token')))) {
throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid csrf token.');
}
/** @var AvatarImage $avatar */
$avatar = $this->avatarRepository->findOneByOwnerId($userId);
if (null !== $avatar) {
$this->avatarRepository->remove($avatar);
}
return new RedirectResponse($this->router->generate('sylius_admin_admin_user_update', ['id' => $userId]));
}
}
| {
"content_hash": "7501d585a8ef3c42b452e2c243be14d6",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 114,
"avg_line_length": 31.88888888888889,
"alnum_prop": 0.7068193130910901,
"repo_name": "itinance/Sylius",
"id": "a132cdb36ff6dfa50d0b3d21d5a2e32563ff404d",
"size": "2220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Sylius/Bundle/AdminBundle/Action/RemoveAvatarAction.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14216"
},
{
"name": "Gherkin",
"bytes": "923409"
},
{
"name": "HTML",
"bytes": "350395"
},
{
"name": "JavaScript",
"bytes": "82507"
},
{
"name": "PHP",
"bytes": "5394431"
},
{
"name": "Shell",
"bytes": "29219"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.connectedvmware.generated;
import com.azure.core.util.Context;
/** Samples for Hosts Delete. */
public final class HostsDeleteSamples {
/*
* x-ms-original-file: specification/connectedvmware/resource-manager/Microsoft.ConnectedVMwarevSphere/preview/2022-01-10-preview/examples/DeleteHost.json
*/
/**
* Sample code: DeleteHost.
*
* @param manager Entry point to ConnectedVMwareManager.
*/
public static void deleteHost(com.azure.resourcemanager.connectedvmware.ConnectedVMwareManager manager) {
manager.hosts().delete("testrg", "HRHost", null, Context.NONE);
}
}
| {
"content_hash": "2346771b7944dd9dddc03839d1bc73fe",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 158,
"avg_line_length": 36.77272727272727,
"alnum_prop": 0.7342398022249691,
"repo_name": "Azure/azure-sdk-for-java",
"id": "084c644436be4a2fb0348b6ceb3ac2ca8e1fe23d",
"size": "809",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/connectedvmware/azure-resourcemanager-connectedvmware/src/samples/java/com/azure/resourcemanager/connectedvmware/generated/HostsDeleteSamples.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
/* */
"format cjs";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
exports.DoExpression = DoExpression;
exports.__esModule = true;
var t = _interopRequireWildcard(require("../../../types"));
var metadata = {
optional: true,
stage: 0
};
exports.metadata = metadata;
var check = t.isDoExpression;
exports.check = check;
function DoExpression(node) {
var body = node.body.body;
if (body.length) {
return body;
} else {
return t.identifier("undefined");
}
} | {
"content_hash": "90ec3c172fb7477db7a816b417bc148e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 106,
"avg_line_length": 19.137931034482758,
"alnum_prop": 0.6522522522522523,
"repo_name": "zartata/aurelia-reporter",
"id": "fe019298ab49392a405ac9cc44f123d5ace46895",
"size": "555",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "jspm_packages/npm/babel-core@5.1.13/lib/babel/transformation/transformers/es7/do-expressions.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "130"
},
{
"name": "CSS",
"bytes": "126639"
},
{
"name": "CoffeeScript",
"bytes": "2294"
},
{
"name": "HTML",
"bytes": "23342"
},
{
"name": "JavaScript",
"bytes": "3221299"
},
{
"name": "LiveScript",
"bytes": "5446"
},
{
"name": "Makefile",
"bytes": "880"
},
{
"name": "Shell",
"bytes": "3398"
}
],
"symlink_target": ""
} |
package com.thebluealliance.androidclient.auth.google;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.firebase.auth.AuthCredential;
import com.thebluealliance.androidclient.TbaLogger;
import com.thebluealliance.androidclient.accounts.AccountController;
import com.thebluealliance.androidclient.auth.AuthProvider;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable;
@Singleton
public class GoogleAuthProvider implements AuthProvider,
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks
{
private final Context mContext;
private final AccountController mAccountController;
private @Nullable GoogleApiClient mGoogleApiClient;
private @Nullable GoogleSignInUser mCurrentUser;
@Inject
public GoogleAuthProvider(Context context, AccountController accountController) {
mCurrentUser = null;
mAccountController = accountController;
mContext = context;
}
private void loadGoogleApiClient() {
String clientId = mAccountController.getWebClientId();
if (clientId.isEmpty()) {
// No client id set in tba.properties, can't continue
TbaLogger.w("Oauth client ID not set, can't enable myTBA. See https://goo.gl/Swp5PC "
+ "for config details");
mGoogleApiClient = null;
return;
}
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(clientId)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
public AuthCredential getAuthCredential(String idToken) {
return com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null);
}
@Override
public void onStart() {
if (mGoogleApiClient != null
&& !mGoogleApiClient.isConnecting()
&& !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
@Override
public void onStop() {
if (mGoogleApiClient != null
&& !mGoogleApiClient.isConnecting()
&& mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public boolean isUserSignedIn() {
return mCurrentUser != null;
}
@Nullable @Override
public GoogleSignInUser getCurrentUser() {
return mCurrentUser;
}
@Nullable @Override
public Intent buildSignInIntent() {
if (mGoogleApiClient == null) {
// Lazy load the API client, if needed
loadGoogleApiClient();
}
if (mGoogleApiClient != null) {
return Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
}
// If we still can't get the API client, just give up
return null;
}
@Override
public Observable<GoogleSignInUser> userFromSignInResult(int requestCode, int resultCode, Intent data) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
boolean success = result.isSuccess();
TbaLogger.d("Google Sign In Result: " + success);
if (success) {
mCurrentUser = new GoogleSignInUser(result.getSignInAccount());
}
return Observable.just(mCurrentUser);
}
@WorkerThread
public Observable<GoogleSignInUser> signInLegacyUser() {
if (mGoogleApiClient == null) {
TbaLogger.i("Lazy loading Google API Client for legacy sign in");
loadGoogleApiClient();
}
if (mGoogleApiClient == null) {
TbaLogger.i("Unable to get API Client for legacy sign in");
return Observable.empty();
}
onStart();
OptionalPendingResult<GoogleSignInResult> optionalResult = Auth.GoogleSignInApi
.silentSignIn(mGoogleApiClient);
GoogleSignInResult result = optionalResult.await();
onStop();
if (result.isSuccess()) {
return Observable.just(new GoogleSignInUser(result.getSignInAccount()));
} else {
TbaLogger.w("Unable to complete legacy sign in: " + result.getStatus().getStatusMessage());
}
return Observable.empty();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
TbaLogger.w("Google API client connection failed");
TbaLogger.w(connectionResult.getErrorMessage());
}
@Override
public void onConnected(@Nullable Bundle bundle) {
TbaLogger.d("Google API client connected");
}
@Override
public void onConnectionSuspended(int i) {
}
}
| {
"content_hash": "21d673ecaeac12b7c15887ff40e4b1ab",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 108,
"avg_line_length": 34.092592592592595,
"alnum_prop": 0.6606916530870903,
"repo_name": "the-blue-alliance/the-blue-alliance-android",
"id": "e8ff60a194aa8ca6ce6567cf29f3774e129bb410",
"size": "5523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/src/main/java/com/thebluealliance/androidclient/auth/google/GoogleAuthProvider.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2389864"
},
{
"name": "Python",
"bytes": "25030"
},
{
"name": "Shell",
"bytes": "12409"
}
],
"symlink_target": ""
} |
export default function Searchbar(selector = '.searchbar', callbacks = {}) {
const element = document.querySelector(selector);
if (element) {
// ermöglicht das Erweitern der Funktionalität
const keys = Object.keys(callbacks);
keys.forEach((key) => {
element.addEventListener(key, callbacks[key]);
});
}
const button = document.querySelector('.searchbar .button');
if (button) {
button.addEventListener('click', () => {
console.log('searchbar:', 'you clicked my button');
});
}
const input = document.querySelector('.searchbar input');
if (input) {
input.addEventListener('change', () => {
console.log('searchbar:', 'you changed my input');
});
}
// Atome können ebenfalls als Objekt initialisiert werden, wenn
// interne Logik vorhanden ist (bspw. video-player)
return this;
}
| {
"content_hash": "01f1b53b435d4fba736086b041714a9b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 76,
"avg_line_length": 29.482758620689655,
"alnum_prop": 0.6549707602339181,
"repo_name": "queoGmbH/ds-example",
"id": "427b0a358873a1435d21044462afbd38b477dfb4",
"size": "859",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/molecules/searchbar/searchbar.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6496"
},
{
"name": "HTML",
"bytes": "14179"
},
{
"name": "JavaScript",
"bytes": "17148"
}
],
"symlink_target": ""
} |
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 6.x Edition
BSD License, Use at your own risk
*/
#import <UIKit/UIKit.h>
#define IFPGA_NAMESTRING @"iFPGA"
#define IPHONE_1G_NAMESTRING @"iPhone 1G"
#define IPHONE_3G_NAMESTRING @"iPhone 3G"
#define IPHONE_3GS_NAMESTRING @"iPhone 3GS"
#define IPHONE_4_NAMESTRING @"iPhone 4"
#define IPHONE_4S_NAMESTRING @"iPhone 4S"
#define IPHONE_5_NAMESTRING @"iPhone 5"
#define IPHONE_UNKNOWN_NAMESTRING @"Unknown iPhone"
#define IPOD_1G_NAMESTRING @"iPod touch 1G"
#define IPOD_2G_NAMESTRING @"iPod touch 2G"
#define IPOD_3G_NAMESTRING @"iPod touch 3G"
#define IPOD_4G_NAMESTRING @"iPod touch 4G"
#define IPOD_UNKNOWN_NAMESTRING @"Unknown iPod"
#define IPAD_1G_NAMESTRING @"iPad 1G"
#define IPAD_2G_NAMESTRING @"iPad 2G"
#define IPAD_3G_NAMESTRING @"iPad 3G"
#define IPAD_4G_NAMESTRING @"iPad 4G"
#define IPAD_UNKNOWN_NAMESTRING @"Unknown iPad"
#define IPAD_MINI_1G_NAMESTRING @"iPad mini 1G"
#define APPLETV_2G_NAMESTRING @"Apple TV 2G"
#define APPLETV_3G_NAMESTRING @"Apple TV 3G"
#define APPLETV_4G_NAMESTRING @"Apple TV 4G"
#define APPLETV_UNKNOWN_NAMESTRING @"Unknown Apple TV"
#define IOS_FAMILY_UNKNOWN_DEVICE @"Unknown iOS device"
#define SIMULATOR_NAMESTRING @"iPhone Simulator"
#define SIMULATOR_IPHONE_NAMESTRING @"iPhone Simulator"
#define SIMULATOR_IPAD_NAMESTRING @"iPad Simulator"
#define SIMULATOR_APPLETV_NAMESTRING @"Apple TV Simulator"
typedef enum {
UIDeviceUnknown,
UIDeviceSimulator,
UIDeviceSimulatoriPhone,
UIDeviceSimulatoriPad,
UIDeviceSimulatorAppleTV,
UIDevice1GiPhone,
UIDevice3GiPhone,
UIDevice3GSiPhone,
UIDevice4iPhone,
UIDevice4SiPhone,
UIDevice5iPhone,
UIDevice1GiPod,
UIDevice2GiPod,
UIDevice3GiPod,
UIDevice4GiPod,
UIDevice1GiPad,
UIDevice2GiPad,
UIDevice3GiPad,
UIDevice4GiPad,
UIDevice1GiPadMini,
UIDeviceAppleTV2,
UIDeviceAppleTV3,
UIDeviceAppleTV4,
UIDeviceUnknowniPhone,
UIDeviceUnknowniPod,
UIDeviceUnknowniPad,
UIDeviceUnknownAppleTV,
UIDeviceIFPGA,
} UIDevicePlatform;
typedef enum {
UIDeviceFamilyiPhone,
UIDeviceFamilyiPod,
UIDeviceFamilyiPad,
UIDeviceFamilyAppleTV,
UIDeviceFamilyUnknown,
} UIDeviceFamily;
/**Extension to UIDevice class to provide more hardware related information, including hardware model, capability and also most importantly current device's orientation
*/
@interface UIDevice (SFHardware)
/**Platform for the Device*/
- (NSString *) platform;
/**Hardware model*/
- (NSString *) hwmodel;
/**Platform type
See `UIDevicePlatform`
*/
- (UIDevicePlatform) platformType;
/**Platform string
Valid values are defined above in the IPHONE_XX_NAMESTRING and IPAD_XXX_NAMESTRING
*/
- (NSString *) platformString;
/**CPU Frequency*/
- (NSUInteger) cpuFrequency;
/**Bus frequency*/
- (NSUInteger) busFrequency;
/**CPU Count*/
- (NSUInteger) cpuCount;
/**Total memory*/
- (NSUInteger) totalMemory;
/**User Memory*/
- (NSUInteger) userMemory;
/**Total disk space*/
- (NSNumber *) totalDiskSpace;
/**Total free space*/
- (NSNumber *) freeDiskSpace;
/**Mac address*/
- (NSString *) macaddress;
/**Returns whether the device has a retina display*/
- (BOOL) hasRetinaDisplay;
/**Device Family*/
- (UIDeviceFamily) deviceFamily;
/**Device's current orientation
This method will first try to retrieve orientation using UIDevice currentOrientation, if return value is an invalid orientation, it will try to use status bar orientation as fallback
*/
- (UIInterfaceOrientation)interfaceOrientation;
@end | {
"content_hash": "ac65184ec0ef9c352aa742ae4e4de9d2",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 183,
"avg_line_length": 26.026666666666667,
"alnum_prop": 0.6846823770491803,
"repo_name": "Pnayak156/SalesforceiOS",
"id": "d978ad81eb887c5420ba272a8edca45f894b7246",
"size": "3904",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SalesforceiOSUniversal/Dependencies/SalesforceCommonUtils/Headers/SalesforceCommonUtils/UIDevice+SFHardware.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1362038"
},
{
"name": "C++",
"bytes": "117767"
},
{
"name": "Objective-C",
"bytes": "741035"
}
],
"symlink_target": ""
} |
> Amy and Amir's Wedding Site -- Built Using Material Design for Vue.js
![Demo](demo.gif)
This is the client part for <a href="https://www.github.com/hellofornow/wedding-site-server">wedding-site-server</a>
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
```
## Dependecies
- vue-cli - https://github.com/vuejs/vue-cli
- Material design for Vue.js - https://vuematerial.github.io
| {
"content_hash": "661544f4742d74c6bb4a6c25a80a65c7",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 116,
"avg_line_length": 21.208333333333332,
"alnum_prop": 0.7328094302554028,
"repo_name": "hellofornow/wedding-site-client",
"id": "9ea04b0cb9fb3f660992a580924929801b6baaf3",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1584"
},
{
"name": "JavaScript",
"bytes": "17705"
},
{
"name": "Vue",
"bytes": "15874"
}
],
"symlink_target": ""
} |
package baseline;
import java.io.*;
import java.util.*;
import utils.*;
/**
* This is the basic algorithm which starts from the lowest k
* removes all vertices with degree k
* subtracts 1 from all adjVertices of these removed vertices
* iterates to collect additional vertices with degree k
* until no more can be found.
* This concludes one iteration of this basic algorithm.
*
* To accomodate processing of large files,
* the entire file is not loaded into ram, but it is broken into smaller files, each of them is scanned and processed at once.
*
* The scaling bottleneck is when the original subgraph for current value of k exceeds the available main memory.
*
* Program arguments:
* 1 - name of the input graph file
* 2 (optional) - max number of elements in each small file - that depends on the available main memory. Default: 100,000 elements.
* Each element represents a vertex, including parent nodes and the node ids in the adjacency lists.
* 3 (optional) - input delimiter. Default: tab
**/
public class BottomUpAlgorithm {
static long totalDiskReads = 0;
public static void main (String [] args)
{
int MAX_ELEMENTS = 100000;
if (args.length < 1)
{
System.out.println ("provide the name of the input graph file and "
+ "optionally the max number of elements in memory and a delimiter for each line in this file ");
System.exit(0);
}
BufferedReader reader = null;
String inputFileName = args[0];
if (args.length >1)
MAX_ELEMENTS = Integer.parseInt(args[1]);
String delimiter = String.valueOf('\t');
if (args.length >2)
delimiter = args[2];
long startTime = System.currentTimeMillis();
//first, rewrite the entire input as a set of vertices with adjacency lists
//and break the input into small files with at most MAX_ELEMENTS total vertices IDs
try
{
File file = new File(inputFileName);
reader = new BufferedReader(new FileReader(file));
}
catch (Exception ge)
{
System.out.println("Unexpected error when reading from File "+inputFileName +": "+ge.getMessage());
System.exit(1);
}
String line;
Vertex currentVertex =null;
int currentvertexID = -1;
List <Vertex> buffer = new ArrayList <Vertex>(); //buffer stores all graph nodes with adjacency lists, to be written to disk
int elementsCount =0;
int outputFileID = 0;
int totalOutputFiles=0;
int totalNodes = 0;
int lineID =0;
int maxDegree =0;
try
{
while ((line = reader.readLine()) != null)
{
String [] pair = line.split(delimiter);
int parentVertexID =0;
int childVertexID=0 ;
boolean validLine = true;
try
{
parentVertexID = Integer.parseInt(pair[0]);
childVertexID = Integer.parseInt(pair[1]);
}
catch (Exception e)
{
validLine = false;
}
if (validLine)
{
if (parentVertexID != currentvertexID) //change of vertices
{
if (currentVertex != null) //prev vertex is done, try to add it to the best bucket
{
buffer.add(currentVertex);
totalNodes++;
if (currentVertex.getDegree() > maxDegree)
maxDegree = currentVertex.getDegree();
elementsCount += (1+currentVertex.getDegree());
if (elementsCount >MAX_ELEMENTS)
{
flushResetBuffer (buffer, outputFileID++);
elementsCount=0;
totalOutputFiles++;
buffer = new ArrayList<Vertex>();
}
}
currentVertex = new Vertex(parentVertexID);
currentvertexID = parentVertexID;
}
currentVertex.addAdjVertex(childVertexID);
if (totalNodes >0 && totalNodes % 1000000 == 0)
System.out.println("Added vertex "+totalNodes);
lineID++;
if (lineID % 1000000 == 0)
System.out.println("Processed line "+lineID);
}
}
buffer.add(currentVertex);
totalNodes++;
flushResetBuffer (buffer, outputFileID++);
totalOutputFiles++;
}
catch (Exception ge)
{
System.out.println("Unexpected error when processing lines of input file: "+ge.getMessage());
System.exit(1);
}
System.out.println("Total output files = "+totalOutputFiles +"; total nodes in the graph="+totalNodes+"; max node degree is "+maxDegree);
System.out.println ("Total partitioning time = "+(System.currentTimeMillis() - startTime)+" ms.");
boolean done = false;
int k=1;
//now start going over files and collecting first nodes - with degree 1, and then all the rest - bottom up
while (!done)
{
done = iterate (totalOutputFiles, k++);
}
//
System.out.println ("Total time = "+(System.currentTimeMillis() - startTime)+" ms.");
System.out.println ("Total vertex disk reads="+totalDiskReads);
}
private static boolean iterate (int totalFiles,int k)
{
boolean allProcessed = true;
String inputFilePrefix = Utils.TEMP_FOLDER + System.getProperty("file.separator") + Utils.BLOCK_FILE_PREFIX;
BufferedReader reader = null;
BufferedWriter writer=null;
Map <Integer, Object> degreeKNodes = new HashMap <Integer, Object>(); //stores nodes identified as k-core so far
//1. Collect all nodes with degree k first
for (int i=0;i<totalFiles; i++)
{
boolean fileExists = true;
try
{
File file = new File(inputFilePrefix+i);
reader = new BufferedReader(new FileReader(file));
}
catch (Exception ge)
{
//file does not exist, do nothing, continue
fileExists =false;
}
if (fileExists) //read all k-degree nodes from it
{
String line=null;
int lineID = 0;
try
{
boolean done = false;
while ((line = reader.readLine()) != null && !done && !line.equals(""))
{
totalDiskReads++;
String [] fields = line.split(Utils.FIELD_SEPARATOR);
int degree =0;
if (fields.length == 3 && !fields [2].equals(""))
{
String [] adjNodes = fields [2].split(Utils.VALUE_SEPARATOR);
degree = adjNodes.length;
}
if (degree == k)
{
Vertex v = Vertex.constructFromString (line);
degreeKNodes.put(v.getID(), null);
}
else //the vertices are sorted ascending, so the next is bigger than the current k
done = true;
lineID++;
}
reader.close();
}
catch (Exception ge)
{
System.out.println("Unexpected error when reading from File "+(inputFilePrefix+i)
+" line number "+lineID +": "+ ge.getMessage());
ge.printStackTrace();
System.exit(1);
}
}
}
//now we need to iterate over input files again, and - remove all nodes with degree k, and remove all adjacent vertices that correspond to these nodes
//the remaining nodes are written into new files
boolean allRemoved = false;
while (!allRemoved)
{
allRemoved = true;
allProcessed = true;
for (int i=0;i<totalFiles; i++)
{
List <Vertex> remainingNodes = new ArrayList <Vertex>();
boolean fileExists = true;
try
{
File file = new File(inputFilePrefix+i);
reader = new BufferedReader(new FileReader(file));
}
catch (Exception ge)
{
//file does not exist, do nothing, continue
fileExists =false;
}
if (fileExists) //read all k-degree nodes from it
{
String line=null;
int lineID = 0;
try
{
while ((line = reader.readLine()) != null && !line.equals(""))
{
totalDiskReads++;
Vertex v = Vertex.constructFromString (line);
if (!degreeKNodes.containsKey(v.getID()))
{
List <Integer>newAdjNodes = new ArrayList <Integer>();
for (int a=0; a<v.getDegree(); a++)
{
Integer aID = v.getAdjvertexID(a);
if (!degreeKNodes.containsKey(aID))
{
newAdjNodes.add(aID);
}
else
allRemoved = false;
}
v.replaceAdjVertices( newAdjNodes);
if (v.getDegree() <= k)
degreeKNodes.put(v.getID(), null);
else
remainingNodes.add(v);
}
else
allRemoved = false;
lineID++;
}
reader.close();
}
catch (Exception ge)
{
System.out.println("Unexpected error when reading from File "+(inputFilePrefix+i)
+" line number "+lineID +": "+ ge.getMessage());
ge.printStackTrace();
System.exit(1);
}
//write remaining nodes back to the file
try
{
File outputfile = new File(inputFilePrefix+i);
FileWriter fileWriter = new FileWriter(outputfile);
writer = new BufferedWriter(fileWriter);
}
catch (Exception ge)
{
System.out.println("Unexpected error when opening file '"+(inputFilePrefix+i) +"' for writing: "+ge.getMessage());
System.exit(1);
}
if (remainingNodes.size()>0)
{
allProcessed = false;
//write them back to the same file
//now sort them ascending for the next bottom-up processing
Collections.sort(remainingNodes, new DegreeComparator(true)); //sorts in ascending order according to a new degree, after removing vertices
//System.out.println("--------------------");
//System.out.println (remainingNodes);
//System.out.println();
//write to file
try
{
for (int e=0; e<remainingNodes.size(); e++)
{
writer.write(remainingNodes.get(e).toString());
writer.newLine();
}
writer.flush();
writer.close();
}
catch (Exception ge)
{
System.out.println("Unexpected error when writing to file '"+(inputFilePrefix+i) +"': "+ge.getMessage());
System.exit(1);
}
}
}
}
}
//finally write current core class to the results folder
if (degreeKNodes.size()>0)
{
String fname = Utils.RESULT_FOLDER +System.getProperty("file.separator")+"core_class_"+k;
try
{
File outputfile = new File(fname);
FileWriter fileWriter = new FileWriter(outputfile);
writer = new BufferedWriter(fileWriter);
System.out.println("Total core-"+k +" nodes:"+degreeKNodes.keySet().size());
List <Integer>list = new LinkedList <Integer>(degreeKNodes.keySet());
Collections.sort(list);
writer.write(list.toString());
writer.flush();
writer.close();
}
catch (Exception ge)
{
System.out.println("Unexpected error when writing to file '"+fname +"' core class "+k+": "+ge.getMessage());
System.exit(1);
}
}
return allProcessed;
}
private static void flushResetBuffer (List <Vertex>buffer, int currentFileID)
{
String fileName = Utils.TEMP_FOLDER +System.getProperty("file.separator") + Utils.BLOCK_FILE_PREFIX + currentFileID;
Collections.sort(buffer, new DegreeComparator(true)); //sorts in ascending order of degrees - bottom-up computation
//System.out.println(buffer);
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(fileName));
for (int i=0; i<buffer.size(); i++)
{
writer.write(buffer.get(i).toString());
writer.newLine();
}
writer.flush();
writer.close();
}
catch (FileNotFoundException e)
{
System.out.println("Cannot write to File "+fileName +": "+e.getMessage());
e.printStackTrace();
System.exit(1);
}
catch (Exception ge)
{
System.out.println("Unexpected error when writing to File "+fileName +": "+ge.getMessage());
System.exit(1);
}
}
}
/*
* Test printout for amazon0302.txt -> test2.txt (complemented, sorted, duplicates removed)
Total output files = 21; total nodes in the graph=262111; max node degree is 420
Total core-1 nodes:6503
Total core-2 nodes:7451
Total core-3 nodes:11078
Total core-4 nodes:78421
Total core-5 nodes:158372
Total core-6 nodes:286
for input small.txt
Added vertex 0
Total output files = 5; total nodes in the graph=14; max node degree is 6
Total core-1 nodes:4
Total core-2 nodes:5
Total core-3 nodes:5
*/
| {
"content_hash": "25173695381f3544a3f016b25c0bfb63",
"timestamp": "",
"source": "github",
"line_count": 411,
"max_line_length": 153,
"avg_line_length": 29.253041362530414,
"alnum_prop": 0.6290443316975797,
"repo_name": "mgbarsky/emcore",
"id": "3d0130155325ea6e93d61fa3191e9d2f3d7eccb6",
"size": "12023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/baseline/BottomUpAlgorithm.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "93544"
}
],
"symlink_target": ""
} |
layout: post97
title: Replication Parameters
categories: XAP97
parent: replication.html
weight: 700
---
{% summary %} {% endsummary %}
# General Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `replication-mode` | Optional values: `sync`, `async`.{% wbr %}- The `async` mode replicates space operations to target space after the client receives the acknowledgment from the source space for the operation.{% wbr %}- The `sync` mode replicates space operations to target space before the client receives the acknowledgment from the source space for the operation. The client getting the acknowledgment for the operation only after all target spaces confirms the arrival of the replicated data.| `async` used with the async-replicated schema. {% wbr %} `sync` used with the sync-replicated, primary-backup and partitioned-sync2backup cluster schema|
| `policy-type` | Optional values:{% wbr %} full-replication - all objects are replicated. {% wbr %} partial-replication - Object that their @SpaceClass configured(replicate = false) will not be replicated. See the [POJO Metadata](./the-space-configuration.html) page for details. This allows you to control replication at a class base level. | partial-replication |
| `repl-find-timeout` | Timeout (in milliseconds) to wait for the lookup of a peer space. This parameter applies only when the space is searched in a Jini Lookup Service. | 5000 \[ms\] |
| `repl-full-take` | If set to `true` the entire object is replicated when take operations is called. If set to `false` only the ID, class information and primitive fields are replicated. This option is valid only when replicating data into a Mirror Service or a backup in non-central DB topology. | false |
| `replicate-notify-templates` | Boolean value. If set to true, the notify templates are replicated to the target space. | true |
| `trigger-notify-templates` | Boolean value. If set to true, the replicated operations will trigger the notify templates and send events to the registered listeners. | false |
| `on-conflicting-packets` | Enum value. If set to ignore, the conflicting operations are ignored. If set to override the newest operation will override the data in the target. | ignore |
{%note%}
Prefix the property with `cluster-config.groups.group.repl-policy.`
{%endnote%}
# Asynchronous Replication Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `repl-chunk-size` | Number of packets transmitted together on the network when the replication event is triggered. The maximum value you can assign for this property is `repl-interval-opers`. | 500 |
| `repl-interval-millis` | Time (in milliseconds) to wait between replication operations. | 3000 \[ms\] |
| `repl-interval-opers` | Number of destructive operations to wait before replicating. | 500 |
| `async-channel-shutdown-timeout` | Determines how long (in milliseconds) the primary space will wait for pending replication to be replicated to its targets before shutting down.| 300000 \[ms\] |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.async-replication.`
{%endinfo%}
{% refer %}For more info refer to [Asynchronous Replication](./asynchronous-replication.html){% endrefer %}
# Synchronous Replication Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `throttle-when-inactive` | Boolean value. Set to `true` if you want to throttle replicated operations when the channel is in-active (disconnection) | `true` in primary backup `false` in full sync replicated |
| `max-throttle-tp-when-inactive` | Integer value. If the above is true, this will specify the maximum operations per second the throttle will maintain when the channel is in-active (disconnection), if the last measured throughput when the channel was active was higher than that, the measured throughput will be used instead. | 50,000 operations/second |
| `min-throttle-tp-when-active` | Integer value. this specifies the minimum operations per second the throttle can reduce to when the channel is active (during asynchronous state), the throttling when the channel is active is always adapted to the current throughput and size of redolog in order to keep the redolog size decreasing. | 1,000 operations/second |
| `target-consume-timeout` | The timeout time in milliseconds that the target space waits for consuming replication packets. When the timeout expires, replication channel moves to asynchronous state. | 10000 \[ms\] |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.sync-replication.`
{%endinfo%}
{% refer %}For more info refer to [Synchronous Replication](./synchronous-replication.html){% endrefer %}
# Recovery Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `recovery-chunk-size` | Integer value. Defines how many operations are recovered is a single batch | 200 |
| `recovery-thread-pool-size` | Integer value. Defines how many threads are recovering the data during the snapshot process. | 4 |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.`
{%endinfo%}
{% refer %}For more info refer to [Space Instance Recovery](./space-instance-recovery.html){% endrefer %}
# Redo-log Parameters
{: .table .table-bordered}
|* `redo-log-capacity` | Specifies the total capacity of replication packets the redo log can hold for a standard replication target.|150000|
|* `redo-log-memory-capacity` | Specifies the maximum number of replication packets the redo log keeps in memory.|150000|
|* `redo-log-recovery-capacity` | Specifies the total capacity of replication packets the redo log can hold for a standard replication target while it is undergoing a recovery process.|5000000|
|* `on-redo-log-capacity-exceeded` | See the [Handling an Increasing Redo Log](./controlling-the-replication-redo-log.html#Handling an Increasing Redo Log) for details. | drop-oldest |
|* `on-missing-packets` | Options: ignore , recover. See the [Handling Dropped Replication Packets](./controlling-the-replication-redo-log.html#Handling Dropped Replication Packets) for details. | recover|
| `cluster-config.mirror-service.redo-log-capacity` | Specifies the total capacity of replication packets the redo log can hold for a mirror service replication target.|1000000|
| `cluster-config.mirror-service.on-redo-log-capacity-exceeded` | See the [Handling an Increasing Redo Log](./controlling-the-replication-redo-log.html#Handling an Increasing Redo Log) for details. | block-operations|
{%info%}
* Prefix the property with `cluster-config.groups.group.repl-policy.`
{%endinfo%}
The following parameters are low level configuration that relates to the swap redo log mechanism:
{: .table .table-bordered}
| Space Cluster Property | Description | Default Value|
|:-----------------------|:------------|:-------------|
| `flush-buffer-packet-count` | Specifies the number of packets buffer size that the swap redo log is using when flushing packets to the disk. | 500 |
| `swap-redo-log.segment-size` | Specifies the size in bytes of each swap redo log segment file. | 10MB |
| `fetch-buffer-packet-count` | Specifies the number of packets buffer size that the swap redo log is using when retrieving packets from the disk to the memory. | 500 |
| `max-scan-length` | Specifies the maximum allowed scan length in bytes in swap redo log file in order to locate a packet. | 50KB |
| `max-open-cursors` | Specifies the maximum number of open file descriptor that the swap redo log will use. | 10 |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.swap-redo-log.`
{%endinfo%}
{% refer %}For more info refer to [Controlling the Replication Redo Log](./controlling-the-replication-redo-log.html){% endrefer %}
# Mirror Service Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `url` | used to locate the Mirror Service. In case you change the name of the Mirror Service specified as part of the Mirror PU, you should modify this parameter value to facilitate the correct Mirror service URL. | jini://*/mirror-service_container/mirror-service |
| `bulk-size` | The amount of operations to be transmitted in one bulk (in quantity and not actual memory size) from an active IMDG primary to the Mirror Service. | 100 |
| `interval-millis` | The replication frequency - Replication will happen every `interval-millis` milliseconds | 2000 |
| `interval-opers` | The replication buffer size - Replication will happen every `interval-opers` operations. | 100 |
| `on-redo-log-capacity-exceeded` | Available options:{% wbr %}block-operations - all cluster operations that need to be replicated (write/update/take) are blocked until the redo log size decreases below the capacity. (Users get RedoLogCapacityExceededException exceptions while trying to execute these operations.){% wbr %}drop-oldest - the oldest packet in the redo log is dropped.{% wbr %}See the [Controlling the Replication Redo Log](./controlling-the-replication-redo-log.html) for details. | block-operations |
| `redo-log-capacity` | Specifies the total capacity of replication packets the redo log can hold for a mirror service replication target.
{%info%}
Prefix the property with `cluster-config.mirror-service.`
{%endinfo%}
See the [Controlling the Replication Redo Log](./controlling-the-replication-redo-log.html) for details. | 1000000 |
# Durable Notifications Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `redo-log-durable-notification-capacity` | Specifies the total capacity of replication packets the redo log can hold for a durable notification replication target | 150000 |
| `durable-notification-max-disconnection-time` | Specifies the maximum amount of time (in milliseconds) the space will wait for the durable notification replication target before it is considered disconnected, after which the target will be dropped. | 300000 |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.`
{%endinfo%}
# Local View Parameters
{: .table .table-bordered}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| `redo-log-local-view-capacity` | Specifies the total capacity of replication packets the redo log can hold for a local view replication target | 150000 |
| `redo-log-local-view-recovery-capacity` | Specifies the total capacity of replication packets the redo log can hold for a local view replication target while the local view is in recovery state (initial load process)| 1000000 |
| `local-view-max-disconnection-time` | Specifies the maximum amount of time (in milliseconds) the space will wait for the local view replication target before it is considered disconnected, after which the target will be dropped. | 300000 |
{%info%}
Prefix the property with `cluster-config.groups.group.repl-policy.`
{%endinfo%} | {
"content_hash": "922987be170fa9ae4addeeaf522d55ff",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 657,
"avg_line_length": 74.625,
"alnum_prop": 0.733756501807282,
"repo_name": "yuvaldori/gigaspaces-wiki-jekyll",
"id": "7178204c2ff6fe2d44a9c70d22e440bb49c5fa8a",
"size": "11348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xap97/replication-parameters.markdown",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.powa.loganalyzer.core.bean;
import java.util.StringTokenizer;
public class LogBeanBuilder {
/**
• ip: is like 30.212.19.124
• date: is in the epoch format like 1336129421
• action: can be SUCCESS or FAILURE
• username: is a String like Thomas.Davenport
*/
public static LogBean createLog(String line){
StringTokenizer token = new StringTokenizer(line,",");
int elePos = 1;
LogBean log = new LogBean();
while(token.hasMoreTokens()){
log = getLogObject(elePos, token.nextElement().toString(), log);
elePos++;
}
return log;
}
protected static LogBean getLogObject(int elePos,String ip,LogBean log){
try{
if(elePos == 1){
log.setIp(ip);
}
if(elePos == 2){
log.setLogTime(Long.valueOf(ip));
}
if(elePos == 3){
log.setAction(LogType.valueOf(ip));
}
if(elePos == 4){
log.setUserName(ip);
log.setSystemTime(System.currentTimeMillis());
}
} catch(Exception ex){
System.out.println("Unable to Build Log Object"+ex.getLocalizedMessage());
//TODO throw exception
}
return log;
}
} | {
"content_hash": "97548b2628aa2f8279f0624d824a1fe7",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 77,
"avg_line_length": 22.914893617021278,
"alnum_prop": 0.669452181987001,
"repo_name": "ranjanshailesh1985/powa",
"id": "caeff1d8ca94bc1cf8760ba35ef1054447af8902",
"size": "1085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/powa/loganalyzer/core/bean/LogBeanBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14434"
}
],
"symlink_target": ""
} |
<?php
// define the autoload function.
function glu_class_autoloader($c) {
include dirname(__FILE__). DIRECTORY_SEPARATOR . strtolower($c) . '.php';
}
// register the autoload function.
spl_autoload_register("glu_class_autoloader");
// EOF
| {
"content_hash": "61228e6884ea6bc5234bb3ba8dd6daac",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 77,
"avg_line_length": 24.6,
"alnum_prop": 0.6991869918699187,
"repo_name": "72squared/glu-php",
"id": "04c2c951dc1ef6a076a7da1aeabffa559bfd6bd7",
"size": "246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/07_scratchpad/class/__autoload.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "613"
},
{
"name": "PHP",
"bytes": "272372"
},
{
"name": "Perl",
"bytes": "28306"
},
{
"name": "Shell",
"bytes": "261"
}
],
"symlink_target": ""
} |
class Car < ActiveRecord::Base
validates :make_t, :model_t, :presence => true
translates :make, :model
end
| {
"content_hash": "a1d83a13adc5a596ffaa2e439b19a0b6",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 48,
"avg_line_length": 22.8,
"alnum_prop": 0.6842105263157895,
"repo_name": "mtgrosser/l10n",
"id": "a307ac5224a4421f566d0e536bf35829247c9134",
"size": "114",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/models/car.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1474"
},
{
"name": "Ruby",
"bytes": "38411"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Picla - jQuery plugin that converts Alt-texts into simple image labels</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:site_name" content="Picla - jQuery plugin that converts Alt-texts into simple image labels" />
<meta property="og:title" content="Picla" />
<meta property="og:image" content="img/logo.png" />
<meta property="og:description" content="jQuery plugin that converts Alt-texts into simple image labels" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<style>
.container {
text-align: center;
}
.label-class {
background-color: rgba(0,0,0,.75);
color: #fff;
padding: 10px;
text-align: center;
}
.wrapper-class {
border-radius: 20px;
box-shadow: 2px 2px 2px rgba(0,0,0,.35);
}
img {
margin-bottom: 10px;
}
h1 {
margin: 20px 0;
font-family: 'Pacifico', cursive;
font-size: 3em;
color: #DE535B;
text-shadow: 1px 1px 1px #C43730;
font-weight: 400;
}
.main-header {
margin-top: 40px;
font-size: 4.5em;
}
h3 {
margin-top: 40px;
color: #DE535B;
}
pre {
background-color: #ddd;
color: #444;
padding: 10px;
white-space: normal;
font-size: .9em;
width: 50%;
margin: 0 auto 20px;
white-space: nowrap;
}
p {
font-weight: 300;
color: #999;
font-size: 1.5em;
margin: 0 0 50px;
}
.text {
margin-bottom: 10px;
font-size: 1.15em;
}
p > span {
color: #DE535B;
font-weight: 400;
font-size: .95em;
}
h4 {
margin: 4px 0;
color: #50a4e2;
}
.example-label {
color: #777;
margin-bottom: 10px;
height: 40px;
}
.github-ribbon {
position: fixed;
z-index: 1000;
top: 0;
right: 0;
border: 0;
}
.main-text {
margin-bottom: 20px;
}
.license {
width: 50%;
margin: 0 auto;
}
@media screen and (max-width: 767px) {
pre, .license {
width: 90%;
}
}
@media screen and (max-width: 480px) {
pre, .license {
width: 100%;
}
}
.foot-text {
color: #DE535B;
margin-top: 30px;
}
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-78827504-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<a href="https://github.com/ArunMichaelDsouza/picla">
<img class="github-ribbon" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png">
</a>
<div class="container">
<div class="text-center">
<h1 class="main-header">Picla</h1>
<p class="main-text">
jQuery plugin that converts <span>Alt-texts</span> into simple image labels
</p>
<a class="version-badge npm-badge" href="https://badge.fury.io/js/picla">
<img src="https://badge.fury.io/js/picla.svg" alt="npm version"></a>
<a class="version-badge" href="https://www.npmjs.com/package/picla">
<img src="https://img.shields.io/npm/dm/picla.svg?style=flat-square" alt="NPM Downloads"></a>
<a class="version-badge" href="http://bower.io/search/?q=picla"><img src="https://img.shields.io/bower/v/picla.svg?style=flat-square" alt="Latest Stable Version">
</a>
</div>
<div class="row" style="margin-top: 40px;">
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" alt="Garden Design"/>
<div class="example-label">
Label with custom CSS
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla wrapper-class" data-label-class="label-class" alt="Garden Design"/>
<div class="example-label">
Label and image wrapper with custom CSS
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-slideUp alt="Garden Design"/>
<div class="example-label">
Slide up label on hover
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-slideUp=".7s" alt="Garden Design"/>
<div class="example-label">
Slide up label on hover with transition
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" alt="Garden Design. Read more <a target='_blank' href='https://en.wikipedia.org/wiki/Garden_design'>here</a>."/>
<div class="example-label">
Label with HTML
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-slideUp=".5s" alt="Garden Design. Read more <a target='_blank' href='https://en.wikipedia.org/wiki/Garden_design'>here</a>."/>
<div class="example-label">
Slide up label with HTML on hover
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-fadeIn alt="Garden Design"/>
<div class="example-label">
Fade in label on hover
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-fadeIn alt="Garden Design. Read more <a target='_blank' href='https://en.wikipedia.org/wiki/Garden_design'>here</a>."/>
<div class="example-label">
Fade in label with HTML on hover
</div>
</div>
<div class="col-md-3">
<img src="img/garden.jpg" class="img-responsive picla" data-label-class="label-class" data-label-slideUp=".5s" alt="I love my <em>Garden</em>. <h4>Oh Yeah!</h4>"/>
<div class="example-label">
More HTML on hover..
</div>
</div>
</div>
</div>
<div class="container">
<h1>Installation</h1>
<h3>CDN</h3>
<p class="text">
Use picla directly from jsdelivr CDN
</p>
<pre>
https://cdn.jsdelivr.net/jquery.picla/0.8.1/picla.min.js
</pre>
<h3>Bower</h3>
<p class="text">
You can install the package using bower. Make sure you have bower installed, then run :
</p>
<pre>
bower install picla
</pre>
<h3>Npm</h3>
<pre>
npm install picla
</pre>
<p class="text">
Or, <a href="https://github.com/ArunMichaelDsouza/picla/releases">download</a> the latest version and include <span>picla.min.js</span> to your project.
</p>
</div>
<div class="container">
<h1>Usage</h1>
<p class="text">
Just add the class <span>picla</span> to any image with descriptive <span>Alt text</span> in order to convert it into a label
</p>
<pre>
<img src="/path-to-image" class="picla" alt="Garden Design"/>
</pre>
<p class="text">
Picla wraps the image within a wrapper and does not add any styles to the created label out of the box.
<br/>
You can use the <span>data-label-class</span> option to add your custom styles
</p>
</div>
<div class="container">
<h1>Options</h1>
<h3>data-label-class</h3>
<p class="text">
Add a CSS class (custom styles) to the label
</p>
<pre>
<img src="/path-to-image" class="picla" data-label-class="image-label-black" alt="Garden Design"/>
</pre>
<h3>data-label-slideUp</h3>
<p class="text">
Make the label slide up from the bottom when the user hovers over the image wrapper
</p>
<pre>
<img src="/path-to-image" class="picla" data-label-slideUp data-label-class="image-label-black" alt="Garden Design"/>
</pre>
<p class="text">
You can also add some transition to this effect by passing in a duration. Default is <span>300ms</span>
</p>
<pre>
<img src="/path-to-image" class="picla" data-label-slideUp="2s" data-label-class="image-label-black" alt="Garden Design"/>
</pre>
<h3>data-label-fadeIn</h3>
<p class="text">
Make the label fade in when the user hovers over the image wrapper
</p>
<pre>
<img src="/path-to-image" class="picla" data-label-fadeIn data-label-class="image-label-black" alt="Garden Design"/>
</pre>
<p class="text">
You can add some transition to this effect as well by passing in a duration
</p>
<br/>
<p class="text">
picla also supports HTML within the alt text
</p>
<pre>
<img src="/path-to-image" class="picla" alt="More about Garden Design <a href='/link'>here</a>" data-label-class="image-label-black"/>
</pre>
</div>
<div class="container">
<h1>License</h1>
<h3>MIT Licensed</h3>
<p class="text license">
Copyright (c) 2016 Arun Michael Dsouza (<a href="mailto:amdsouza92@gmail.com">amdsouza92@gmail.com</a>)
<br/><br/>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
<br/><br/>
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
<br/><br/>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</p>
</div>
<p class="text text-center foot-text">
Project developed and maintained by <a href="https://github.com/ArunMichaelDsouza/">Arun Michael Dsouza</a>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="../build/picla.min.js"></script>
</body>
</html> | {
"content_hash": "41acccb3d14933ddf94a1baa19b0f1f8",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 463,
"avg_line_length": 36.38013698630137,
"alnum_prop": 0.6653487715334652,
"repo_name": "ArunMichaelDsouza/picla",
"id": "314fe0cdf4caca93d001618c4685f65b73dd1f27",
"size": "10623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7853"
}
],
"symlink_target": ""
} |
from django.core.management.base import BaseCommand
from candidates.models import Candidate
from django.contrib.auth import get_user_model
import json
import urllib2
import csv
def load_from_csv(filename):
csv_file = csv.reader(open(filename))
headings = csv_file.next()
User = get_user_model()
for row in csv_file:
record = dict(zip(headings, row))
try:
testrec = Candidate.objects.get(popit_id=record['id'])
print "Skipping: ", testrec.name
continue
except Candidate.DoesNotExist:
pass
user = User(username="candidate-" + record['id'])
user.save()
candidate = Candidate(
popit_id=record['id'],
user=user,
name=record['name'].decode('utf-8'),
contact_address=record['email'].decode('utf-8'),
constituency_id=record['mapit_id'],
constituency_name=record['constituency'].decode('utf-8'),
party=record['party'].decode('utf-8'))
candidate.save()
print u"Added: {} ({}, {})".format(candidate.name, candidate.party, candidate.constituency_name)
def load_from_api():
url = "http://yournextmp.popit.mysociety.org/api/v0.1/search/persons?q=_exists_:standing_in.2015.post_id&page=16"
while url:
print "Fetching url: ", url
fp = urllib2.urlopen(url)
data = json.load(fp)
fp.close()
for record in data['result']:
try:
testrec = Candidate.objects.get(popit_url=record['url'])
print "Skipping: ", testrec.name
continue
except Candidate.DoesNotExist:
pass
candidate = Candidate(
name=record['name'],
contact_address=record['email'],
popit_url=record['url'],
constituency_id=record['standing_in']['2015']['post_id'],
constituency_name=record['standing_in']['2015']['name'],
party=record['party_memberships']['2015']['name'])
candidate.save()
print u"Added: {} ({}, {})".format(candidate.name, candidate.party, candidate.constituency_name)
if 'next_url' not in data:
break
url = data['next_url']
class Command(BaseCommand):
def handle(self, *args, **options):
load_from_csv(args[0])
| {
"content_hash": "d219c0e5f12cc852024642e02efd976b",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 117,
"avg_line_length": 36.815384615384616,
"alnum_prop": 0.5725031341412453,
"repo_name": "DemocracyClub/candidate_questions",
"id": "107401a7a097cac865800876902f30214b41c186",
"size": "2393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "q_and_a/apps/candidates/management/commands/import_candidates.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "39"
},
{
"name": "Cucumber",
"bytes": "589"
},
{
"name": "HTML",
"bytes": "6848"
},
{
"name": "JavaScript",
"bytes": "45"
},
{
"name": "Python",
"bytes": "40306"
}
],
"symlink_target": ""
} |
define([
'materialnote/base/core/func',
'materialnote/base/core/list',
'materialnote/base/core/dom',
'materialnote/base/core/range',
'materialnote/base/core/key'
], function (func, list, dom, range, key) {
var AutoLink = function (context) {
var self = this;
var defaultScheme = 'http://';
var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/\/]?|mailto:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i;
this.events = {
'materialnote.keyup': function (we, e) {
if (!e.isDefaultPrevented()) {
self.handleKeyup(e);
}
},
'materialnote.keydown': function (we, e) {
self.handleKeydown(e);
}
};
this.initialize = function () {
this.lastWordRange = null;
};
this.destroy = function () {
this.lastWordRange = null;
};
this.replace = function () {
if (!this.lastWordRange) {
return;
}
var keyword = this.lastWordRange.toString();
var match = keyword.match(linkPattern);
if (match && (match[1] || match[2])) {
var link = match[1] ? keyword : defaultScheme + keyword;
var node = $('<a />').html(keyword).attr('href', link)[0];
this.lastWordRange.insertNode(node);
this.lastWordRange = null;
context.invoke('editor.focus');
}
};
this.handleKeydown = function (e) {
if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
var wordRange = context.invoke('editor.createRange').getWordRange();
this.lastWordRange = wordRange;
}
};
this.handleKeyup = function (e) {
if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
this.replace();
}
};
};
return AutoLink;
});
| {
"content_hash": "8268f6eca8014051930870c35368aa8e",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 98,
"avg_line_length": 26.363636363636363,
"alnum_prop": 0.5614942528735632,
"repo_name": "Cerealkillerway/materialNote",
"id": "bb4e8f0f293409bb33b50cf48d33ed2ebe174427",
"size": "1740",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/base/module/AutoLink.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "153"
},
{
"name": "CSS",
"bytes": "195761"
},
{
"name": "HTML",
"bytes": "5355"
},
{
"name": "JavaScript",
"bytes": "1622846"
},
{
"name": "Shell",
"bytes": "2881"
}
],
"symlink_target": ""
} |
// Copyright (C) 2011 The Android Open Source Project
//
// 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.
package com.google.gerrit.client.admin;
import static com.google.gerrit.common.data.GlobalCapability.CREATE_PROJECT;
import com.google.gerrit.client.Dispatcher;
import com.google.gerrit.client.ErrorDialog;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.NotFoundScreen;
import com.google.gerrit.client.account.AccountCapabilities;
import com.google.gerrit.client.projects.ProjectInfo;
import com.google.gerrit.client.projects.ProjectMap;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.HintTextBox;
import com.google.gerrit.client.ui.ProjectListPopup;
import com.google.gerrit.client.ui.ProjectNameSuggestOracle;
import com.google.gerrit.client.ui.ProjectsTable;
import com.google.gerrit.client.ui.Screen;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.ProjectUtil;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwtexpui.globalkey.client.NpTextBox;
import com.google.gwtjsonrpc.common.VoidResult;
public class CreateProjectScreen extends Screen {
private Grid grid;
private NpTextBox project;
private Button create;
private Button browse;
private HintTextBox parent;
private SuggestBox suggestParent;
private CheckBox emptyCommit;
private CheckBox permissionsOnly;
private ProjectsTable suggestedParentsTab;
private ProjectListPopup projectsPopup;
public CreateProjectScreen() {
super();
setRequiresSignIn(true);
}
@Override
protected void onLoad() {
super.onLoad();
AccountCapabilities.all(new GerritCallback<AccountCapabilities>() {
@Override
public void onSuccess(AccountCapabilities ac) {
if (ac.canPerform(CREATE_PROJECT)) {
display();
} else {
Gerrit.display(PageLinks.ADMIN_CREATE_PROJECT, new NotFoundScreen());
}
}
}, CREATE_PROJECT);
}
@Override
protected void onUnload() {
super.onUnload();
projectsPopup.closePopup();
}
@Override
protected void onInitUI() {
super.onInitUI();
setPageTitle(Util.C.createProjectTitle());
addCreateProjectPanel();
/* popup */
projectsPopup = new ProjectListPopup() {
@Override
protected void onMovePointerTo(String projectName) {
// prevent user input from being overwritten by simply poping up
if (!projectsPopup.isPoppingUp() || "".equals(suggestParent.getText())) {
suggestParent.setText(projectName);
}
}
};
projectsPopup.initPopup(Util.C.projects(), PageLinks.ADMIN_PROJECTS);
}
private void addCreateProjectPanel() {
final VerticalPanel fp = new VerticalPanel();
fp.setStyleName(Gerrit.RESOURCES.css().createProjectPanel());
initCreateTxt();
initCreateButton();
initParentBox();
addGrid(fp);
emptyCommit = new CheckBox(Util.C.checkBoxEmptyCommit());
permissionsOnly = new CheckBox(Util.C.checkBoxPermissionsOnly());
fp.add(emptyCommit);
fp.add(permissionsOnly);
fp.add(create);
VerticalPanel vp = new VerticalPanel();
vp.add(fp);
initSuggestedParents();
vp.add(suggestedParentsTab);
add(vp);
}
private void initCreateTxt() {
project = new NpTextBox();
project.setVisibleLength(50);
project.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
doCreateProject();
}
}
});
}
private void initCreateButton() {
create = new Button(Util.C.buttonCreateProject());
create.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doCreateProject();
}
});
browse = new Button(Util.C.buttonBrowseProjects());
browse.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
int top = grid.getAbsoluteTop() - 50; // under page header
// Try to place it to the right of everything else, but not
// right justified
int left =
5 + Math.max(
grid.getAbsoluteLeft() + grid.getOffsetWidth(),
suggestedParentsTab.getAbsoluteLeft()
+ suggestedParentsTab.getOffsetWidth());
projectsPopup.setPreferredCoordinates(top, left);
projectsPopup.displayPopup();
}
});
}
private void initParentBox() {
parent = new HintTextBox();
suggestParent =
new SuggestBox(new ProjectNameSuggestOracle(), parent);
parent.setVisibleLength(50);
}
private void initSuggestedParents() {
suggestedParentsTab = new ProjectsTable() {
{
table.setText(0, 1, Util.C.parentSuggestions());
}
@Override
protected void populate(final int row, final ProjectInfo k) {
final Anchor projectLink = new Anchor(k.name());
projectLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
suggestParent.setText(getRowItem(row).name());
}
});
table.setWidget(row, 1, projectLink);
table.setText(row, 2, k.description());
setRowItem(row, k);
}
};
suggestedParentsTab.setVisible(false);
ProjectMap.parentCandidates(new GerritCallback<ProjectMap>() {
@Override
public void onSuccess(ProjectMap list) {
if (!list.isEmpty()) {
suggestedParentsTab.setVisible(true);
suggestedParentsTab.display(list);
suggestedParentsTab.finishDisplay();
}
}
});
}
private void addGrid(final VerticalPanel fp) {
grid = new Grid(2, 3);
grid.setStyleName(Gerrit.RESOURCES.css().infoBlock());
grid.setText(0, 0, Util.C.columnProjectName() + ":");
grid.setWidget(0, 1, project);
grid.setText(1, 0, Util.C.headingParentProjectName() + ":");
grid.setWidget(1, 1, suggestParent);
grid.setWidget(1, 2, browse);
fp.add(grid);
}
private void doCreateProject() {
final String projectName = project.getText().trim();
final String parentName = suggestParent.getText().trim();
if ("".equals(projectName)) {
project.setFocus(true);
return;
}
enableForm(false);
Util.PROJECT_SVC.createNewProject(projectName, parentName,
emptyCommit.getValue(), permissionsOnly.getValue(),
new GerritCallback<VoidResult>() {
@Override
public void onSuccess(VoidResult result) {
String nameWithoutSuffix = ProjectUtil.stripGitSuffix(projectName);
History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey(
nameWithoutSuffix), ProjectScreen.INFO));
}
@Override
public void onFailure(Throwable caught) {
new ErrorDialog(caught.getMessage()).center();
enableForm(true);
}
});
}
private void enableForm(final boolean enabled) {
project.setEnabled(enabled);
create.setEnabled(enabled);
parent.setEnabled(enabled);
emptyCommit.setEnabled(enabled);
permissionsOnly.setEnabled(enabled);
}
}
| {
"content_hash": "bf1d7be1603f9f2910b549ec530e63e2",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 81,
"avg_line_length": 32.359073359073356,
"alnum_prop": 0.6891779023982818,
"repo_name": "teamblueridge/gerrit",
"id": "a6b0f17886410a21098496b67dbd201f93261963",
"size": "8381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/CreateProjectScreen.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5255192"
},
{
"name": "JavaScript",
"bytes": "1590"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "17501"
},
{
"name": "Python",
"bytes": "12182"
},
{
"name": "Shell",
"bytes": "36534"
}
],
"symlink_target": ""
} |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".RegisterAccount" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
| {
"content_hash": "6f4b01107dc828f3d43b1d886bfc5575",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 74,
"avg_line_length": 41.8125,
"alnum_prop": 0.7115097159940209,
"repo_name": "Rogerp009/Ikut",
"id": "32845f9ab7c9bed9952c9475095ab35a15f16b9d",
"size": "669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/activity_register_account.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "415565"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Evans.Demo.Api.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
}
| {
"content_hash": "37c528d803b6e8612077691a84e94734",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 44,
"avg_line_length": 18.444444444444443,
"alnum_prop": 0.6204819277108434,
"repo_name": "pevans1986/Demo",
"id": "bc69c0d6a740af02d6157002036d818e1cd41bb6",
"size": "334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Demo/Evans.Demo.Api/Controllers/HomeController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "201714"
},
{
"name": "CSS",
"bytes": "2626"
},
{
"name": "HTML",
"bytes": "5069"
},
{
"name": "JavaScript",
"bytes": "10918"
}
],
"symlink_target": ""
} |
namespace AutoResponse.WebApi2.IntegrationTests.Tests
{
using System;
using System.Threading.Tasks;
using AutoFixture.Xunit2;
using AutoResponse.Core.Exceptions;
using AutoResponse.Core.Logging;
using AutoResponse.Sample.Domain.Services;
using AutoResponse.WebApi2.IntegrationTests.Helpers;
using Moq;
using Xunit;
// ReSharper disable StyleCop.SA1600
#pragma warning disable SA1600
#pragma warning disable 1591
public class LoggerTests
{
[Theory]
[AutoData]
public async Task OwinExceptionShouldInvokeLogger(
SampleServerFactory serverFactory,
Mock<IExceptionService> exceptionService,
EntityValidationException exception,
Mock<IAutoResponseLogger> logger)
{
logger.Setup(l => l.LogException(It.IsAny<Exception>())).Returns(Task.FromResult(0));
exceptionService.Setup(s => s.Execute()).Throws(exception);
using (var server = serverFactory
.With<IExceptionService>(exceptionService.Object)
.With<IAutoResponseLogger>(logger.Object)
.Create())
{
await server.HttpClient.GetAsync("/");
logger.Verify(l => l.LogException(It.IsAny<Exception>()), Times.Once());
}
}
}
} | {
"content_hash": "b27b35dc96802a696b537f84d76f607a",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 97,
"avg_line_length": 33.875,
"alnum_prop": 0.6354243542435425,
"repo_name": "devdigital/AutoResponse",
"id": "6736cbe1e11b7f24b13a5a5a252a9cc82feb556a",
"size": "1480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/AutoResponse.WebApi2.IntegrationTests/Tests/LoggerTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "322393"
},
{
"name": "PowerShell",
"bytes": "7434"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Github::Client::Issues::Comments, '#create' do
let(:user) { 'peter-murach' }
let(:repo) { 'github' }
let(:number) { 1 }
let(:inputs) { { 'body' => 'a new comment' } }
let(:request_path) { "/repos/#{user}/#{repo}/issues/#{number}/comments" }
before {
stub_post(request_path).with(:body => inputs).
to_return(:body => body, :status => status,
:headers => {:content_type => "application/json; charset=utf-8"})
}
after { reset_authentication_for(subject) }
context "resouce created" do
let(:body) { fixture('issues/comment.json') }
let(:status) { 201 }
it "should fail to create resource if 'body' input is missing" do
expect {
subject.create user, repo, number, inputs.except('body')
}.to raise_error(Github::Error::RequiredParams)
end
it "should create resource successfully" do
subject.create user, repo, number, inputs
expect(a_post(request_path).with(body: inputs)).to have_been_made
end
it "should return the resource" do
comment = subject.create user, repo, number, inputs
expect(comment).to be_a Github::ResponseWrapper
end
it "should get the comment information" do
comment = subject.create user, repo, number, inputs
expect(comment.user.login).to eq 'octocat'
end
end
it_should_behave_like 'request failure' do
let(:requestable) { subject.create user, repo, number, inputs }
end
end # create
| {
"content_hash": "a09abec049474f5a54a02d28112fbe81",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 75,
"avg_line_length": 31.53191489361702,
"alnum_prop": 0.6464237516869096,
"repo_name": "peter-murach/github",
"id": "4a0a0dabccc819ce52923fbc3c14984fd92c3a8b",
"size": "1501",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/github/client/issues/comments/create_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Cucumber",
"bytes": "93919"
},
{
"name": "Ruby",
"bytes": "713494"
}
],
"symlink_target": ""
} |
import os
import sys
import pkg_resources
from datetime import datetime
# sys.path.insert(0, os.path.abspath('.'))
sys.path.append(os.path.abspath('_themes'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = '{{cookiecutter.project_name}}'
copyright = u'2015 - {0}, {{cookiecutter.full_name}}'.format(datetime.utcnow().year)
author = '{{cookiecutter.full_name}}'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
try:
release = pkg_resources.get_distribution('{{cookiecutter.project_slug}}').version
except pkg_resources.DistributionNotFound:
print('{{cookiecutter.project_name}} must be installed to build the documentation.')
print('Install from source using `pip install -e .` in a virtualenv.')
sys.exit(1)
if 'dev' in release:
release = ''.join(release.partition('dev')[:2])
version = '.'.join(release.split('.')[:2])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'gw'
if html_theme == 'gw':
# The gw theme can be found under: https://github.com/useblocks/gw-sphinx-themes
# The following codes tries to fetch the latest version before the build starts.
git_url = "https://github.com/useblocks/gw-sphinx-themes"
repo_dir = os.path.join(os.path.dirname(__file__), os.path.abspath("_themes"))
print("Getting latest version of groundwork sphinx theme")
try:
print(" Checking for gitpython library... ", end="")
from git import Repo
print("done")
print(" Checking for working internet connection... ", end="")
from urllib.request import urlopen
urlopen("http://google.com")
print("done")
except Exception:
if not os.path.exists(repo_dir) or os.listdir(repo_dir) == []:
print("Please install 'gitpython' to use the latest version of the groundwork"
"sphinx theme or save it by your own under '_themes' by executing "
"'git clone https://github.com/useblocks/gw-sphinx-themes")
sys.exit(1)
else:
print("gitpython is not installed, but _themes is no empty. So maybe there is"
"a working copy of the groundwork sphinx themes. Lets go one.")
print(" Getting latest theme updates... ", end="")
if not os.path.exists(repo_dir):
Repo.clone_from(git_url, repo_dir)
else:
repo = Repo(repo_dir)
origin = repo.remotes.origin
origin.pull()
print("done")
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
"contribute": True,
"github_fork": "{{cookiecutter.github_user}}/{{cookiecutter.github_project_name}}",
"github_ribbon_color": "white_ffffff",
"github_user": "{{cookiecutter.github_user}}",
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = '{{cookiecutter.project_name}} v0.1'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = "/_static/gw_logo.png"
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = '{{cookiecutter.project_name}}docs'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, '{{cookiecutter.project_name}}.tex', '{{cookiecutter.project_name}} Documentation',
'team useblocks', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, '{{cookiecutter.project_name}}', '{{cookiecutter.project_name}} Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, '{{cookiecutter.project_name}}', '{{cookiecutter.project_name}} Documentation',
author, '{{cookiecutter.project_name}}', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
| {
"content_hash": "7ee4fc86adf7b4894f591cc667fbfd58",
"timestamp": "",
"source": "github",
"line_count": 371,
"max_line_length": 100,
"avg_line_length": 31.18867924528302,
"alnum_prop": 0.6791979949874687,
"repo_name": "useblocks/groundwork",
"id": "be122f2061646f0d8e7523e3df1cdcabdc90b716",
"size": "12142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "groundwork/recipes/gw_package/{{cookiecutter.project_name}}/docs/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8590"
},
{
"name": "CSS",
"bytes": "5479"
},
{
"name": "Makefile",
"bytes": "8232"
},
{
"name": "Python",
"bytes": "215683"
}
],
"symlink_target": ""
} |
package me.beagle.userManagement;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserManagementApplicationTests {
@Test
public void contextLoads() {
}
}
| {
"content_hash": "7260ebbdb6d3c560f5023ff034a23672",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 60,
"avg_line_length": 21.8125,
"alnum_prop": 0.8166189111747851,
"repo_name": "beagle4ce/UserManagement",
"id": "1735f583564a382e1744ea87cfb2f7b4b72793c3",
"size": "349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/me/beagle/userManagement/UserManagementApplicationTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4994"
},
{
"name": "Java",
"bytes": "12521"
},
{
"name": "Shell",
"bytes": "6468"
}
],
"symlink_target": ""
} |
using namespace std;
class IrisMethod;
class IIrisClass;
class IIrisValues;
class IIrisContextEnvironment;
enum class CallerSide {
Inside = 0,
Outside,
};
#if IR_USE_MEM_POOL
class IrisObject : public IIrisObject, public IrisObjectMemoryPoolInterface<IrisObject, POOLID_IrisObject>
#else
class IrisObject : public IIrisObject
#endif
{
private:
typedef unordered_map<IrisInternString, IrisMethod*, IrisInternString::IrisInerStringHash> _MethodHash;
typedef pair<IrisInternString, IrisMethod*> _MethodPair;
typedef unordered_map<IrisInternString, IrisValue, IrisInternString::IrisInerStringHash> _VariableHash;
typedef pair<IrisInternString, IrisValue> _VariablePair;
private:
static unsigned int s_nMaxID;
private:
IIrisClass* m_pClass = nullptr;
_MethodHash m_mpInstanceMethods;
_VariableHash m_mpInstanceVariables;
void* m_pNativeObject = nullptr;
size_t m_nObjectID = 0;
bool m_bIsMaked = false;
bool m_bLiteralObject = false;
bool m_bLiteralObjectAssigned = false;
bool m_bHashed = false;
size_t m_nHash = 0;
size_t m_nUsedCount = 0;
size_t m_nFixCount = 0;
bool m_bPermanent = false;
recursive_mutex m_rmFixMutex;
IrisWLLock m_iwlInstanceValueWLLock;
IrisWLLock m_iwlInstanceMethodWLLock;
//bool m_bIsCreatedInNativeFunction = false;
public:
IrisObject();
#if IR_USE_STL_STRING
IrisValue CallInstanceFunction(const string& strFunctionName, IIrisContextEnvironment* pContextEnvironment, IIrisValues* ivsValues, CallerSide eSide);
#else
IrisValue CallInstanceFunction(const IrisInternString& strFunctionName, IIrisContextEnvironment* pContextEnvironment, IIrisValues* ivsValues, CallerSide eSide);
#endif
inline bool IsUsed() { return m_nUsedCount > 0; }
inline void Fix() { lock_guard<recursive_mutex> lgLock(m_rmFixMutex); ++m_nFixCount; }
inline void Unfix() { lock_guard<recursive_mutex> lgLock(m_rmFixMutex); --m_nFixCount; }
inline bool IsFixed() { return m_nFixCount > 0; }
//inline bool IsCreatedInNativeFunction() { return m_bIsCreatedInNativeFunction; }
//inline bool SetIsCreateInNativeFunction(bool bFlag) { m_bIsCreatedInNativeFunction = bFlag; }
inline void SetPermanent(bool bFlag) { m_bPermanent = bFlag; }
inline bool IsPermanent() { return m_bPermanent; }
inline void SetHash(size_t nHash) { m_bHashed = true; m_nHash = nHash; }
inline size_t GetHash() { return m_nHash; }
inline bool Hashed() { return m_bHashed; }
inline size_t GetObjectID() { return m_nObjectID; }
inline IIrisClass* GetClass() { return m_pClass; }
inline void SetClass(IIrisClass* pClass) { m_pClass = pClass; }
#if IR_USE_STL_STRING
const IrisValue & GetInstanceValue(const string & strInstanceValueName, bool & bResult);
IrisMethod* GetInstanceMethod(const string& strInstanceMethodName);
void AddInstanceValue(const string& strInstanceValueName, const IrisValue& ivValue);
#else
const IrisValue& GetInstanceValue(const IrisInternString& strInstanceValueName, bool& bResult);
IrisMethod* GetInstanceMethod(const IrisInternString& strInstanceMethodName);
void AddInstanceValue(const IrisInternString& strInstanceValueName, const IrisValue& ivValue);
#endif
void AddSingleInstanceMethod(IrisMethod* pMethod);
void Mark();
inline void ClearMark() { m_bIsMaked = false; }
inline void* GetNativeObject() { return m_pNativeObject; }
inline void SetNativeObject(void* pNativeObject) { m_pNativeObject = pNativeObject; }
~IrisObject();
friend class IrisGC;
friend class IrisClass;
friend class IrisModule;
};
#endif | {
"content_hash": "12e9733fb88aaf3fa5b7aec2a71770f2",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 161,
"avg_line_length": 31.423423423423422,
"alnum_prop": 0.7760894495412844,
"repo_name": "yuwenhuisama/Iris-Language",
"id": "c58c6deb4dcaff3a2c48ad491fdea701c3e4dfca",
"size": "3911",
"binary": false,
"copies": "1",
"ref": "refs/heads/iris_stable",
"path": "IrisLangLibrary/include/IrisInterpreter/IrisStructure/IrisObject.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "15495"
},
{
"name": "C++",
"bytes": "951924"
},
{
"name": "Objective-C",
"bytes": "1213"
}
],
"symlink_target": ""
} |
/**
* An abstract class for all services to store the configuration
*
* @module app/shared/config-storage.service
* @licence MIT 2017 https://github.com/jbouzekri/jbnote/blob/master/LICENSE
*/
import { EventEmitter } from '@angular/core';
import { ConfigFirebase } from './config-firebase.model';
/**
* Abstract class that all configuration store must extend
*
* Useful because we most probably will have different implementation
* - localStorage in web browser
* - something else in chrome extension or mobile app
*/
export abstract class ConfigStorageService {
confChanged = new EventEmitter<void>();
/**
* Return true if installation has been completed
*
* @returns {boolean}
*/
abstract isInstalled(): boolean;
/**
* Check if sync is enabled
*
* @returns {boolean}
*/
abstract isSyncEnabled(): boolean;
/**
* Enable/disable sync
*
* @param {boolean} syncEnabled
* @returns {ConfigLocalStorageService}
*/
abstract setSyncEnabled(syncEnabled: boolean): ConfigStorageService;
/**
* Check if sync is configured
*
* @returns {boolean}
*/
abstract hasConfig(): boolean;
/**
* Get sync configuration
*
* @returns {ConfigFirebase}
*/
abstract getConfig(): ConfigFirebase;
/**
* Save the sync configuration
*
* @param {ConfigFirebase} config
* @returns {ConfigLocalStorageService}
*/
abstract setConfig(config: ConfigFirebase): ConfigStorageService;
}
| {
"content_hash": "f5945f3d5d20b1002eee91e81864c0c9",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 76,
"avg_line_length": 22.630769230769232,
"alnum_prop": 0.6852481305234535,
"repo_name": "jbouzekri/jbnote",
"id": "9405124897cf0679afa3a6d19704e046ad7a315b",
"size": "1471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/shared/config-storage.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2054"
},
{
"name": "HTML",
"bytes": "15437"
},
{
"name": "JavaScript",
"bytes": "1871"
},
{
"name": "TypeScript",
"bytes": "125062"
}
],
"symlink_target": ""
} |
"use strict";
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
var morgan = require('morgan');
var noWWW = require('./lib/middlewares/no-www.js');
var app = module.exports = express();
app.enable('trust proxy');
require('./config/load-app.js')(app);
mongoose.connect(app.get('mongoUrl'));
// Redirect www to no www
app.use(noWWW);
app.use(morgan('dev'));
// view engine setup
app.set('views', path.join(__dirname, 'lib/views'));
app.set('view engine', 'jade');
app.locals.moment = require('moment');
app.use(favicon('public/favicon.ico'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(session({
secret: app.get('secret'),
proxy: false,
store: new MongoStore({
url: app.get('mongoUrl')
}, function() {}),
saveUninitialized: true,
resave: true
}));
require('./config/routes.js')(app);
app.use(express.static(path.join(__dirname, 'public')));
// error handler
app.use(function(err, req, res, next) {
console.error(err);
console.error(req.url);
var status = err.status || err.code || 500;
res.status(status);
res._body = err;
res.render('error', {
message: "Error: " + (err.message || err.error_description),
stacktrace: app.get('stacktraces') ? err.stack : null
});
next();
});
// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
if(res.headersSent) {
return next();
}
res.status(404).render('404', { status: 404, url: req.url });
});
| {
"content_hash": "d449afd7751d2ca72c3a4d5979c89b65",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 64,
"avg_line_length": 23.21917808219178,
"alnum_prop": 0.6589970501474927,
"repo_name": "saveman71/epitech-international",
"id": "814e8613a3096831ffeec9fb4ba2a1a63312b9d0",
"size": "1695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "388"
},
{
"name": "HTML",
"bytes": "6422"
},
{
"name": "JavaScript",
"bytes": "20734"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!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" xml:lang="en" lang="en">
<head>
<title>ActiveModel::Validations::HelperMethods</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />
<script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.0.0</span><br />
<h1>
<span class="type">Module</span>
ActiveModel::Validations::HelperMethods
</h1>
<ul class="files">
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/absence_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/absence.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/acceptance_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/acceptance.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/confirmation_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/confirmation.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/exclusion_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/exclusion.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/format_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/format.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/inclusion_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/inclusion.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/length_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/length.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/numericality_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/numericality.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/presence_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/presence.rb</a></li>
<li><a href="../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/activemodel-4_0_0/lib/active_model/validations/with_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/with.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>V</dt>
<dd>
<ul>
<li>
<a href="#method-i-validates_absence_of">validates_absence_of</a>,
</li>
<li>
<a href="#method-i-validates_acceptance_of">validates_acceptance_of</a>,
</li>
<li>
<a href="#method-i-validates_confirmation_of">validates_confirmation_of</a>,
</li>
<li>
<a href="#method-i-validates_exclusion_of">validates_exclusion_of</a>,
</li>
<li>
<a href="#method-i-validates_format_of">validates_format_of</a>,
</li>
<li>
<a href="#method-i-validates_inclusion_of">validates_inclusion_of</a>,
</li>
<li>
<a href="#method-i-validates_length_of">validates_length_of</a>,
</li>
<li>
<a href="#method-i-validates_numericality_of">validates_numericality_of</a>,
</li>
<li>
<a href="#method-i-validates_presence_of">validates_presence_of</a>,
</li>
<li>
<a href="#method-i-validates_size_of">validates_size_of</a>
</li>
</ul>
</dd>
</dl>
<!-- Methods -->
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-validates_absence_of">
<b>validates_absence_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_absence_of" name="method-i-validates_absence_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates that the specified attributes are blank (as defined by <a
href="../../Object.html#method-i-blank-3F">Object#blank?</a>). Happens by
default on save.</p>
<pre><code>class Person < ActiveRecord::Base
validates_absence_of :first_name
end
</code></pre>
<p>The first_name attribute must be in the object and it must be blank.</p>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “must be
blank”).</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_absence_of_source')" id="l_method-i-validates_absence_of_source">show</a>
</p>
<div id="method-i-validates_absence_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/absence.rb, line 26</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_absence_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">AbsenceValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_acceptance_of">
<b>validates_acceptance_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_acceptance_of" name="method-i-validates_acceptance_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Encapsulates the pattern of wanting to validate the acceptance of a terms
of service check box (or similar agreement).</p>
<pre><code>class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service
validates_acceptance_of :eula, message: 'must be abided'
end
</code></pre>
<p>If the database column does not exist, the <code>terms_of_service</code>
attribute is entirely virtual. This check is performed only if
<code>terms_of_service</code> is not <code>nil</code> and by default on
save.</p>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “must be
accepted”).</p>
</li><li>
<p><code>:allow_nil</code> - Skip validation if attribute is <code>nil</code>
(default is <code>true</code>).</p>
</li><li>
<p><code>:accept</code> - Specifies value that is considered accepted. The
default value is a string “1”, which makes it easy to relate to an <a
href="../../HTML.html">HTML</a> checkbox. This should be set to
<code>true</code> if you are validating a database column, since the
attribute is typecast from “1” to <code>true</code> before validation.</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_acceptance_of_source')" id="l_method-i-validates_acceptance_of_source">show</a>
</p>
<div id="method-i-validates_acceptance_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/acceptance.rb, line 50</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_acceptance_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">AcceptanceValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_confirmation_of">
<b>validates_confirmation_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_confirmation_of" name="method-i-validates_confirmation_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Encapsulates the pattern of wanting to validate a password or email address
field with a confirmation.</p>
<pre><code>Model:
class Person < ActiveRecord::Base
validates_confirmation_of :user_name, :password
validates_confirmation_of :email_address,
message: 'should match confirmation'
end
View:
<%= password_field "person", "password" %>
<%= password_field "person", "password_confirmation" %></code></pre>
<p>The added <code>password_confirmation</code> attribute is virtual; it
exists only as an in-memory attribute for validating the password. To
achieve this, the validation adds accessors to the model for the
confirmation attribute.</p>
<p>NOTE: This check is performed only if <code>password_confirmation</code> is
not <code>nil</code>. To require confirmation, make sure to add a presence
check for the confirmation attribute:</p>
<pre><code>validates_presence_of :password_confirmation, if: :password_changed?</code></pre>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “doesn't
match confirmation”).</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_confirmation_of_source')" id="l_method-i-validates_confirmation_of_source">show</a>
</p>
<div id="method-i-validates_confirmation_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/confirmation.rb, line 56</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_confirmation_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">ConfirmationValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_exclusion_of">
<b>validates_exclusion_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_exclusion_of" name="method-i-validates_exclusion_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates that the value of the specified attribute is not in a particular
enumerable object.</p>
<pre><code>class Person < ActiveRecord::Base
validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
message: 'should not be the same as your username or first name'
validates_exclusion_of :karma, in: :reserved_karmas
end
</code></pre>
<p>Configuration options:</p>
<ul><li>
<p><code>:in</code> - An enumerable object of items that the value
shouldn't be part of. This can be supplied as a proc, lambda or symbol
which returns an enumerable. If the enumerable is a range the test is
performed with</p>
</li><li>
<p><code>:within</code> - A synonym(or alias) for <code>:in</code>
<code>Range#cover?</code>, otherwise with <code>include?</code>.</p>
</li><li>
<p><code>:message</code> - Specifies a custom error message (default is: “is
reserved”).</p>
</li><li>
<p><code>:allow_nil</code> - If set to true, skips this validation if the
attribute is <code>nil</code> (default is <code>false</code>).</p>
</li><li>
<p><code>:allow_blank</code> - If set to true, skips this validation if the
attribute is blank(default is <code>false</code>).</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_exclusion_of_source')" id="l_method-i-validates_exclusion_of_source">show</a>
</p>
<div id="method-i-validates_exclusion_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/exclusion.rb, line 45</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_exclusion_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">ExclusionValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_format_of">
<b>validates_format_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_format_of" name="method-i-validates_format_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates whether the value of the specified attribute is of the correct
form, going by the regular expression provided.You can require that the
attribute matches the regular expression:</p>
<pre><code>class Person < ActiveRecord::Base
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
end
</code></pre>
<p>Alternatively, you can require that the specified attribute does
<em>not</em> match the regular expression:</p>
<pre><code>class Person < ActiveRecord::Base
validates_format_of :email, without: /NOSPAM/
end
</code></pre>
<p>You can also provide a proc or lambda which will determine the regular
expression that will be used to validate the attribute.</p>
<pre><code>class Person < ActiveRecord::Base
# Admin can have number as a first letter in their screen name
validates_format_of :screen_name,
with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
end
</code></pre>
<p>Note: use <code>\A</code> and <code>\Z</code> to match the start and end of
the string, <code>^</code> and <code>$</code> match the start/end of a
line.</p>
<p>Due to frequent misuse of <code>^</code> and <code>$</code>, you need to
pass the <code>multiline: true</code> option in case you use any of these
two anchors in the provided regular expression. In most cases, you should
be using <code>\A</code> and <code>\z</code>.</p>
<p>You must pass either <code>:with</code> or <code>:without</code> as an
option. In addition, both must be a regular expression or a proc or lambda,
or else an exception will be raised.</p>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “is invalid”).</p>
</li><li>
<p><code>:allow_nil</code> - If set to true, skips this validation if the
attribute is <code>nil</code> (default is <code>false</code>).</p>
</li><li>
<p><code>:allow_blank</code> - If set to true, skips this validation if the
attribute is blank (default is <code>false</code>).</p>
</li><li>
<p><code>:with</code> - Regular expression that if the attribute matches will
result in a successful validation. This can be provided as a proc or lambda
returning regular expression which will be called at runtime.</p>
</li><li>
<p><code>:without</code> - Regular expression that if the attribute does not
match will result in a successful validation. This can be provided as a
proc or lambda returning regular expression which will be called at
runtime.</p>
</li><li>
<p><code>:multiline</code> - Set to true if your regular expression contains
anchors that match the beginning or end of lines as opposed to the
beginning or end of the string. These anchors are <code>^</code> and
<code>$</code>.</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_format_of_source')" id="l_method-i-validates_format_of_source">show</a>
</p>
<div id="method-i-validates_format_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/format.rb, line 110</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_format_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">FormatValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_inclusion_of">
<b>validates_inclusion_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_inclusion_of" name="method-i-validates_inclusion_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates whether the value of the specified attribute is available in a
particular enumerable object.</p>
<pre><code>class Person < ActiveRecord::Base
validates_inclusion_of :gender, in: %w( m f )
validates_inclusion_of :age, in: 0..99
validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
validates_inclusion_of :karma, in: :available_karmas
end
</code></pre>
<p>Configuration options:</p>
<ul><li>
<p><code>:in</code> - An enumerable object of available items. This can be
supplied as a proc, lambda or symbol which returns an enumerable. If the
enumerable is a range the test is performed with <code>Range#cover?</code>,
otherwise with <code>include?</code>.</p>
</li><li>
<p><code>:within</code> - A synonym(or alias) for <code>:in</code></p>
</li><li>
<p><code>:message</code> - Specifies a custom error message (default is: “is
not included in the list”).</p>
</li><li>
<p><code>:allow_nil</code> - If set to <code>true</code>, skips this
validation if the attribute is <code>nil</code> (default is
<code>false</code>).</p>
</li><li>
<p><code>:allow_blank</code> - If set to <code>true</code>, skips this
validation if the attribute is blank (default is <code>false</code>).</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_inclusion_of_source')" id="l_method-i-validates_inclusion_of_source">show</a>
</p>
<div id="method-i-validates_inclusion_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/inclusion.rb, line 44</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_inclusion_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">InclusionValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_length_of">
<b>validates_length_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_length_of" name="method-i-validates_length_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates that the specified attribute matches the length restrictions
supplied. Only one option can be used at a time:</p>
<pre><code>class Person < ActiveRecord::Base
validates_length_of :first_name, maximum: 30
validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
validates_length_of :fax, in: 7..32, allow_nil: true
validates_length_of :phone, in: 7..32, allow_blank: true
validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
tokenizer: ->(str) { str.scan(/\w+/) }
end
</code></pre>
<p>Configuration options:</p>
<ul><li>
<p><code>:minimum</code> - The minimum size of the attribute.</p>
</li><li>
<p><code>:maximum</code> - The maximum size of the attribute. Allows
<code>nil</code> by default if not used with :minimum.</p>
</li><li>
<p><code>:is</code> - The exact size of the attribute.</p>
</li><li>
<p><code>:within</code> - A range specifying the minimum and maximum size of
the attribute.</p>
</li><li>
<p><code>:in</code> - A synonym (or alias) for <code>:within</code>.</p>
</li><li>
<p><code>:allow_nil</code> - Attribute may be <code>nil</code>; skip
validation.</p>
</li><li>
<p><code>:allow_blank</code> - Attribute may be blank; skip validation.</p>
</li><li>
<p><code>:too_long</code> - The error message if the attribute goes over the
maximum (default is: “is too long (maximum is %{count} characters)”).</p>
</li><li>
<p><code>:too_short</code> - The error message if the attribute goes under the
minimum (default is: “is too short (min is %{count} characters)”).</p>
</li><li>
<p><code>:wrong_length</code> - The error message if using the
<code>:is</code> method and the attribute is the wrong size (default is:
“is the wrong length (should be %{count} characters)”).</p>
</li><li>
<p><code>:message</code> - The error message to use for a
<code>:minimum</code>, <code>:maximum</code>, or <code>:is</code>
violation. An alias of the appropriate
<code>too_long</code>/<code>too_short</code>/<code>wrong_length</code>
message.</p>
</li><li>
<p><code>:tokenizer</code> - Specifies how to split up the attribute string.
(e.g. <code>tokenizer: ->(str) { str.scan(/\w+/) }</code> to count words
as in above example). Defaults to <code>->(value) { value.split(//)
}</code> which counts individual characters.</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="aka">
Also aliased as: <a href="HelperMethods.html#method-i-validates_size_of">validates_size_of</a>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_length_of_source')" id="l_method-i-validates_length_of_source">show</a>
</p>
<div id="method-i-validates_length_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/length.rb, line 119</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_length_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">LengthValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_numericality_of">
<b>validates_numericality_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_numericality_of" name="method-i-validates_numericality_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates whether the value of the specified attribute is numeric by trying
to convert it to a float with <a href="../../Kernel.html">Kernel</a>.Float
(if <code>only_integer</code> is <code>false</code>) or applying it to the
regular expression <code>/\A[+\-]?\d+\Z/</code> (if
<code>only_integer</code> is set to <code>true</code>).</p>
<pre><code>class Person < ActiveRecord::Base
validates_numericality_of :value, on: :create
end
</code></pre>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “is not a
number”).</p>
</li><li>
<p><code>:only_integer</code> - Specifies whether the value has to be an
integer, e.g. an integral value (default is <code>false</code>).</p>
</li><li>
<p><code>:allow_nil</code> - Skip validation if attribute is <code>nil</code>
(default is <code>false</code>). Notice that for fixnum and float columns
empty strings are converted to <code>nil</code>.</p>
</li><li>
<p><code>:greater_than</code> - Specifies the value must be greater than the
supplied value.</p>
</li><li>
<p><code>:greater_than_or_equal_to</code> - Specifies the value must be
greater than or equal the supplied value.</p>
</li><li>
<p><code>:equal_to</code> - Specifies the value must be equal to the supplied
value.</p>
</li><li>
<p><code>:less_than</code> - Specifies the value must be less than the
supplied value.</p>
</li><li>
<p><code>:less_than_or_equal_to</code> - Specifies the value must be less than
or equal the supplied value.</p>
</li><li>
<p><code>:other_than</code> - Specifies the value must be other than the
supplied value.</p>
</li><li>
<p><code>:odd</code> - Specifies the value must be an odd number.</p>
</li><li>
<p><code>:even</code> - Specifies the value must be an even number.</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code> . See <code>ActiveModel::Validation#validates</code>
for more information</p>
<p>The following checks can also be supplied with a proc or a symbol which
corresponds to a method:</p>
<ul><li>
<p><code>:greater_than</code></p>
</li><li>
<p><code>:greater_than_or_equal_to</code></p>
</li><li>
<p><code>:equal_to</code></p>
</li><li>
<p><code>:less_than</code></p>
</li><li>
<p><code>:less_than_or_equal_to</code></p>
</li></ul>
<p>For example:</p>
<pre><code>class Person < ActiveRecord::Base
validates_numericality_of :width, less_than: ->(person) { person.height }
validates_numericality_of :width, greater_than: :minimum_weight
end
</code></pre>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_numericality_of_source')" id="l_method-i-validates_numericality_of_source">show</a>
</p>
<div id="method-i-validates_numericality_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/numericality.rb, line 131</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_numericality_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">NumericalityValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_presence_of">
<b>validates_presence_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_presence_of" name="method-i-validates_presence_of" class="permalink">Link</a>
</div>
<div class="description">
<p>Validates that the specified attributes are not blank (as defined by <a
href="../../Object.html#method-i-blank-3F">Object#blank?</a>). Happens by
default on save.</p>
<pre><code>class Person < ActiveRecord::Base
validates_presence_of :first_name
end
</code></pre>
<p>The first_name attribute must be in the object and it cannot be blank.</p>
<p>If you want to validate the presence of a boolean field (where the real
values are <code>true</code> and <code>false</code>), you will want to use
<code>validates_inclusion_of :field_name, in: [true, false]</code>.</p>
<p>This is due to the way <a
href="../../Object.html#method-i-blank-3F">Object#blank?</a> handles
boolean values: <code>false.blank? # => true</code>.</p>
<p>Configuration options:</p>
<ul><li>
<p><code>:message</code> - A custom error message (default is: “can't be
blank”).</p>
</li></ul>
<p>There is also a list of default options supported by every validator:
<code>:if</code>, <code>:unless</code>, <code>:on</code> and
<code>:strict</code>. See <code>ActiveModel::Validation#validates</code>
for more information</p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-validates_presence_of_source')" id="l_method-i-validates_presence_of_source">show</a>
</p>
<div id="method-i-validates_presence_of_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.2/gems/activemodel-4.0.0/lib/active_model/validations/presence.rb, line 34</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">validates_presence_of</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">attr_names</span>)
<span class="ruby-identifier">validates_with</span> <span class="ruby-constant">PresenceValidator</span>, <span class="ruby-identifier">_merge_attributes</span>(<span class="ruby-identifier">attr_names</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-validates_size_of">
<b>validates_size_of</b>(*attr_names)
<a href="../../../classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_size_of" name="method-i-validates_size_of" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="aka">
Alias for: <a href="HelperMethods.html#method-i-validates_length_of">validates_length_of</a>
</div>
</div>
</div>
</div>
</body>
</html> | {
"content_hash": "96657ead7e4366b9d8eb8b8c4137f79a",
"timestamp": "",
"source": "github",
"line_count": 901,
"max_line_length": 250,
"avg_line_length": 42.25527192008879,
"alnum_prop": 0.6073754990544232,
"repo_name": "alombardo4/Agendue",
"id": "b39577e47931ec2c65c0e30607521acdd9fcd3e2",
"size": "38124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AgendueWeb/doc/api/classes/ActiveModel/Validations/HelperMethods.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "138782"
},
{
"name": "CoffeeScript",
"bytes": "3689"
},
{
"name": "HTML",
"bytes": "13251982"
},
{
"name": "Java",
"bytes": "308126"
},
{
"name": "JavaScript",
"bytes": "15185870"
},
{
"name": "Objective-C",
"bytes": "361506"
},
{
"name": "Perl",
"bytes": "1361"
},
{
"name": "Ruby",
"bytes": "150857"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Waterboy, The (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0120484">Waterboy, The (1998)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?James+Brundage">James Brundage</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>The Waterboy</PRE>
<PRE>As reviewed by James Brundage</PRE>
<P>There's a reason why there are more romantic comedies than slapstick movies:
they cost less, are easier to make, and are a more sound investment. After
all, we all want to fall in love, and what better place to do so that at the
movies? In nearly makes me shudder at the number of relationships that were
broken up last year by Adam Sandler's previous attempt at humor The Wedding
Singer, an exercise not in creative humor but uninspired dryness.</P>
<P>So he tried to make people fall in love; who can blame him? Well, I can,
but, as a critic, I have to not hold a grudge, or an opinion going in, or
any hold on reality inside of the theater because otherwise I'd have gone
insane long ago. So what has Sandler done now? He has atoned for his sins.</P>
<P>The Wedding Singer, well beyond sin and into blasphemy, which made me laugh
once, was perfectly counterbalanced by the slapstick comedy The Waterboy,
about a slow waterboy who decides to take his aggression out on the football
field. If it were a sports movie, it would be trite, but instead it is a
comedy, and we get to all enjoy ourselves.</P>
<P>At this point The Waterboy has a special place in my heart. Only a few
movies have tried to kill me with unexpected laughs. There's Something About
Mary almost did it with a kernel of popcorn that went down the wrong tube at
an unexpected second and this comedy, which I will never drink soda during
again. Make more like it Adam: your sins have been forgiven.</P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "6765bce7dbeffe55b0a9196696951b43",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 203,
"avg_line_length": 63.74418604651163,
"alnum_prop": 0.7486318861729296,
"repo_name": "xianjunzhengbackup/code",
"id": "0450521add5930cac17a2dbf264a59bc285ecbaf",
"size": "2741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/16437.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
io (deprecated)
====
example of input/output streams
| {
"content_hash": "cc84734fd4a30895d8035a032de7574f",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 31,
"avg_line_length": 13.5,
"alnum_prop": 0.7222222222222222,
"repo_name": "meatloaf/io-example.java",
"id": "45c2c93e1841146dd50205e018d842d5305793d9",
"size": "54",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "36013"
}
],
"symlink_target": ""
} |
package features
import org.scalatest.matchers.MustMatchers
import support.SeleniumUtils._
import org.scalatest.{FeatureSpec, GivenWhenThen}
import org.openqa.selenium.By
/**
* Created by IntelliJ IDEA.
* User: wfaler
* Date: 10/03/2011
* Time: 22:51
* To change this template use File | Settings | File Templates.
*/
class StartPageSpec extends FeatureSpec with GivenWhenThen with MustMatchers {
//evaluating { emptyStack.pop() } must produce [NoSuchElementException]
feature("The user uses the homepage") {
info("As a user")
info("I want to be able to navigate from the startpage")
info("So that I can navigate around the examples app")
scenario("browser looks at startpage") {
given("I am on the startpage")
browser.get("http://localhost:8080")
when("I look at the links")
then("I should see 4 links")
val ul = browser.findElement(By.id("links"))
val listItems = ul.findElements(By.tagName("li"))
listItems.size must be === 4
and("the first link should be for widgets")
val widgets = listItems.get(0).findElement(By.id("widgets"))
widgets must not be null
widgets.getText must be === "Check out our Widgets CRUD example with validation, JSON etc"
widgets.getAttribute("href") must be === "/widgets"
and("the second link should be a link to composable")
val composable = listItems.get(1).findElement(By.id("composable"))
composable must not be null
composable.getText must be === "Widget listing, but with a composed Layout instead of default layout"
composable.getAttribute("href") must be === "/composable/"
and("the second link should be a link to JPA Example with cars")
val cars = listItems.get(2).findElement(By.id("cars"))
cars must not be null
cars.getText must be === "CRUD example with JPA"
cars.getAttribute("href") must be === "/cars/"
and("the second link should be a link to Squeryl examples")
val squeryl = listItems.get(3).findElement(By.id("people"))
squeryl must not be null
squeryl.getText must be === "CRUD example with Squeryl"
squeryl.getAttribute("href") must be === "/people/"
}
}
} | {
"content_hash": "09c072d782db078eb4443345ae3ffd8b",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 107,
"avg_line_length": 35.725806451612904,
"alnum_prop": 0.6776523702031603,
"repo_name": "mrityunjay-kant/Bowler",
"id": "4c98429b1a8120226a04efffe047f3a4c10133ae",
"size": "2215",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "examples/src/test/scala/features/StartPageSpec.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Scala",
"bytes": "328318"
}
],
"symlink_target": ""
} |
import React from 'react';
import {Box, styled} from '@material-ui/core';
import {spacing} from "@material-ui/system";
export interface FormTextFieldHelpIconProps {
formTextField: React.ReactNode;
helpIconTooltip: React.ReactNode;
}
function FormTextFieldHelpIcon({formTextField, helpIconTooltip}: FormTextFieldHelpIconProps) {
return (
<div style={{display: 'flex', alignItems: 'center'}}>
{formTextField}
<Box pl={1}>
{helpIconTooltip}
</Box>
</div>
);
}
export default styled(FormTextFieldHelpIcon)(spacing);
| {
"content_hash": "9c450f9760fec05a4467b75f6c2bca6d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 94,
"avg_line_length": 27.095238095238095,
"alnum_prop": 0.6924428822495606,
"repo_name": "Clemens85/runningdinner",
"id": "3d127dd27645fec0ceff36a3b8021da635613f12",
"size": "569",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "runningdinner-client/packages/webapp/src/common/input/FormTextFieldHelpIcon.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9964"
},
{
"name": "HTML",
"bytes": "220884"
},
{
"name": "Java",
"bytes": "1059912"
},
{
"name": "JavaScript",
"bytes": "915942"
},
{
"name": "Less",
"bytes": "18959"
},
{
"name": "Shell",
"bytes": "3096"
},
{
"name": "TypeScript",
"bytes": "656882"
}
],
"symlink_target": ""
} |
module Blazer
module Adapters
class DruidAdapter < BaseAdapter
TIMESTAMP_REGEX = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\z/
def run_statement(statement, comment)
columns = []
rows = []
error = nil
header = {"Content-Type" => "application/json", "Accept" => "application/json"}
timeout = data_source.timeout ? data_source.timeout.to_i : 300
data = {
query: statement,
context: {
timeout: timeout * 1000
}
}
uri = URI.parse("#{settings["url"]}/druid/v2/sql/")
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = timeout
begin
response = JSON.parse(http.post(uri.request_uri, data.to_json, header).body)
if response.is_a?(Hash)
error = response["errorMessage"] || "Unknown error: #{response.inspect}"
if error.include?("timed out")
error = Blazer::TIMEOUT_MESSAGE
end
else
columns = (response.first || {}).keys
rows = response.map { |r| r.values }
# Druid doesn't return column types
# and no timestamp type in JSON
rows.each do |row|
row.each_with_index do |v, i|
if v.is_a?(String) && TIMESTAMP_REGEX.match(v)
row[i] = Time.parse(v)
end
end
end
end
rescue => e
error = e.message
end
[columns, rows, error]
end
def tables
result = data_source.run_statement("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA NOT IN ('INFORMATION_SCHEMA') ORDER BY TABLE_NAME")
result.rows.map(&:first)
end
def schema
result = data_source.run_statement("SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA NOT IN ('INFORMATION_SCHEMA') ORDER BY 1, 2")
result.rows.group_by { |r| [r[0], r[1]] }.map { |k, vs| {schema: k[0], table: k[1], columns: vs.sort_by { |v| v[2] }.map { |v| {name: v[2], data_type: v[3]} }} }
end
def preview_statement
"SELECT * FROM {table} LIMIT 10"
end
end
end
end
| {
"content_hash": "28e3fc293a0eb5ef7ae8891c1dc88edb",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 214,
"avg_line_length": 34.298507462686565,
"alnum_prop": 0.5400348128807659,
"repo_name": "strivedi183/blazer",
"id": "3b70b9235e075551a6d46eed87a959407e28cf40",
"size": "2298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/blazer/adapters/druid_adapter.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "38810"
},
{
"name": "R",
"bytes": "564"
},
{
"name": "Ruby",
"bytes": "71196"
}
],
"symlink_target": ""
} |
FROM balenalib/jetson-nano-emmc-alpine:3.14-build
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.7-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.7-openjdk/jre/bin:/usr/lib/jvm/java-1.7-openjdk/bin
RUN set -x \
&& apk add --no-cache \
openjdk7 \
&& [ "$JAVA_HOME" = "$(docker-java-home)" ]
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 [ ! -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: Alpine Linux 3.14 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v7-jdk \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/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "3ff276f1f86febf7583be29cdbe019f3",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 683,
"avg_line_length": 58.13333333333333,
"alnum_prop": 0.7001146788990825,
"repo_name": "resin-io-library/base-images",
"id": "31babe0a8204edef3a776448ad21b7fab8fd9d1a",
"size": "1765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/openjdk/jetson-nano-emmc/alpine/3.14/7-jdk/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
package ol.source;
import jsinterop.annotations.JsType;
/**
* Source for images from Mapguide servers.
* @author tlochmann
*/
@JsType(isNative = true)
public class ImageMapGuide extends Image {
}
| {
"content_hash": "1cf27829164a3e97b7b4f6176e4c9da5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 15.615384615384615,
"alnum_prop": 0.7389162561576355,
"repo_name": "amagge/gwt-ol3-playg",
"id": "24610da4500945e61bd45d0a464cce7700e7646f",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gwt-ol3-client/src/main/java/ol/source/ImageMapGuide.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1387"
},
{
"name": "HTML",
"bytes": "907"
},
{
"name": "Java",
"bytes": "362696"
}
],
"symlink_target": ""
} |
package alt.beanmapper.compile.field;
/**
*
* @author Albert Shift
*
*/
public class FieldSource {
protected int primitiveInt;
public Integer wrapperInt;
protected int boxingInt;
public Integer unboxingInt;
private int openAccessInt;
public int closeAccessInt;
private int openAccessIntBoxing;
public Integer closeAccessIntUnboxing;
public int getOpenAccessInt() {
return openAccessInt;
}
public void setOpenAccessInt(int i) {
this.openAccessInt = i;
}
public int getOpenAccessIntBoxing() {
return openAccessIntBoxing;
}
public void setOpenAccessIntBoxing(int openAccessIntBoxing) {
this.openAccessIntBoxing = openAccessIntBoxing;
}
}
| {
"content_hash": "7ae20ef76a46afaaa5eb81d8794205fd",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 62,
"avg_line_length": 17.307692307692307,
"alnum_prop": 0.7659259259259259,
"repo_name": "albertshift/beanmapper",
"id": "aea86cda4dfeec2a1abe7d2a6b316c313f9e1673",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/alt/beanmapper/compile/field/FieldSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "165745"
}
],
"symlink_target": ""
} |
package com.xinyu.mwp.activity.base;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jaeger.library.StatusBarUtil;
import com.xinyu.mwp.R;
import com.xinyu.mwp.application.MyApplication;
import com.xinyu.mwp.networkapi.NetworkAPIException;
import com.xinyu.mwp.swipeback.ScrollFinishListener;
import com.xinyu.mwp.swipeback.SwipeBackActivity;
import com.xinyu.mwp.swipeback.SwipeBackLayout;
import com.xinyu.mwp.util.LogUtil;
import com.xinyu.mwp.util.ToastUtils;
import com.xinyu.mwp.view.LoaderLayout;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
/**
* @author : Created by 180
* @version : 0.01
* @email : yaobanglin@163.com
* @created time : 2015-06-05 11:21
* @describe : BaseActivity
* @for your attention : none
* @revise : none
*/
public abstract class BaseActivity extends SwipeBackActivity {
@Nullable
@ViewInject(R.id.titleText)
protected TextView titleText;
@Nullable
@ViewInject(R.id.container)
protected View titleContainer;
@Nullable
@ViewInject(R.id.leftImage)
protected ImageButton leftImage;
@Nullable
@ViewInject(R.id.leftText)
protected TextView leftText;
@Nullable
@ViewInject(R.id.rightImage)
protected ImageButton rightImage;
@Nullable
@ViewInject(R.id.rightImage1)
protected ImageButton rightImage1;
@Nullable
@ViewInject(R.id.leftImageView)
protected ImageView leftImageView;
@Nullable
@ViewInject(R.id.rightText)
protected TextView rightText;
@Nullable
@ViewInject(R.id.container)
protected View container;
protected LoaderLayout loaderLayout;
protected View rootView;
protected Context context;
protected SwipeBackLayout mSwipeBackLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
rootView = LayoutInflater.from(this).inflate(getContentView(), null);
setContentView(rootView);
initStatusBar();
MyApplication.getApplication().register(this);
onInit();
initView();
initListener();
initData();
}
//设置标题栏颜色
public void initStatusBar() {
StatusBarUtil.setColor(this, getResources().getColor(R.color.default_main_color), 0);
}
@Override
public Resources getResources() {
Resources res = super.getResources();
Configuration config = new Configuration();
config.setToDefaults();
res.updateConfiguration(config, res.getDisplayMetrics());
return res;
}
protected void onInit() {
x.view().inject(this);
mSwipeBackLayout = getSwipeBackLayout();
mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
}
protected void onToastError(Throwable ex, String defError) {
try {
if (!isFinishing()) {
ToastUtils.show(MyApplication.getApplication(), NetworkAPIException.formatException(ex, defError), 2000);
}
LogUtil.showException((Exception) ex);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onToastError(Throwable ex) {
onToastError(ex, null);
closeLoader();
}
public void showLoader() {
showLoader(null);
}
public void showLoader(String msgContent) {
try {
if (loaderLayout == null) {
loaderLayout = new LoaderLayout(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
loaderLayout.setLayoutParams(params);
if (rootView != null) {
((FrameLayout) rootView.getParent()).addView(loaderLayout);
}
}
loaderLayout.setVisibility(View.VISIBLE);
if (msgContent != null) {
loaderLayout.setMsgContent(msgContent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void showLoader(int resId) {
showLoader(getString(resId));
}
public void closeLoader() {
if (loaderLayout != null)
loaderLayout.setVisibility(View.GONE);
}
protected abstract int getContentView();
/**
* 初始化view
*/
protected void initView() {
}
/**
* 初始化监听
*/
protected void initListener() {
mSwipeBackLayout.setScrollFinishListener(new ScrollFinishListener() {
@Override
public void scrollFinish() {
//退出之前的操作
beforeFinish();
}
});
}
/**
* 初始化数据
*/
protected void initData() {
}
/**
* 跳转到下一个Activity
*
* @param cls Activity class
*/
public void next(Class<? extends Activity> cls) {
startActivity(new Intent(this, cls));
}
/**
* 跳转到下一个Activity并finish当前Activity
*
* @param cls Activity class
*/
public void nextFinish(Class<? extends Activity> cls) {
next(cls);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
MyApplication.getApplication().unregister(this);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
@Override
public void setTitle(int resid) {
if (titleText != null)
titleText.setText(resid);
}
public void setTitle(String titleString) {
if (titleText != null)
titleText.setText(titleString);
}
@Event(value = R.id.leftImage)
private void clickLeftImage(View view) {
back();
}
public void back() {
scrollToFinishActivity();
}
@Override
public void onBackPressed() {
back();
}
/**
* 返回键,物理返回键,以及手势返回,统一在finish之前都会调用这个方法
*/
public void beforeFinish() {
LogUtil.e("beforeFinish");
}
public void showToast(@NonNull CharSequence content) {
Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
}
public View getRootView() {
return rootView;
}
public void showRightImage(int resId) {
if (rightImage != null) {
rightImage.setVisibility(View.VISIBLE);
if (resId != 0) {
rightImage.setImageResource(resId);
}
}
}
} | {
"content_hash": "c78c9c0affdb69b57d801081a6363e7e",
"timestamp": "",
"source": "github",
"line_count": 273,
"max_line_length": 153,
"avg_line_length": 25.67765567765568,
"alnum_prop": 0.6346647646219686,
"repo_name": "sll8192/wpan",
"id": "dcb26b4673fc64c8045258894886678c3e3eeab5",
"size": "7154",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/xinyu/mwp/activity/base/BaseActivity.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "41021"
},
{
"name": "Java",
"bytes": "1291707"
}
],
"symlink_target": ""
} |
package com.klisly.bookbox.ui.fragment;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import com.klisly.bookbox.BookBoxApplication;
import com.klisly.bookbox.Constants;
import com.klisly.bookbox.R;
import com.klisly.bookbox.model.BaseModel;
import com.klisly.bookbox.ui.base.BaseMainFragment;
import com.klisly.common.SharedPreferenceUtils;
import com.material.widget.Switch;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SettingFragment<T extends BaseModel> extends BaseMainFragment {
@Bind(R.id.morning_switch)
Switch mSwMorning;
@Bind(R.id.afternoon_switch)
Switch mSwAfternoon;
@Bind(R.id.novel_switch)
Switch mSwNovel;
@Bind(R.id.toolbar)
Toolbar mToolbar;
private SharedPreferenceUtils proferenceUtils = BookBoxApplication.getInstance().getPreferenceUtils();
public static SettingFragment newInstance() {
return new SettingFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_setting, container, false);
ButterKnife.bind(this, view);
initView(view);
initData();
return view;
}
private void initData() {
if(proferenceUtils.getValue(Constants.NOTIFICATION_MORNING, true)){
mSwMorning.setChecked(true);
} else {
mSwMorning.setChecked(false);
}
if(proferenceUtils.getValue(Constants.NOTIFICATION_AFTERNOON, true)){
mSwAfternoon.setChecked(true);
} else {
mSwAfternoon.setChecked(false);
}
if(proferenceUtils.getValue(Constants.NOTIFICATION_NOVEL, true)){
mSwNovel.setChecked(true);
} else {
mSwNovel.setChecked(false);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
private void initView(View view) {
mToolbar.setTitle(R.string.setting);
initToolbarNav(mToolbar, false);
mSwMorning.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
proferenceUtils.setValue(Constants.NOTIFICATION_MORNING, isChecked);
}
});
mSwAfternoon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
proferenceUtils.setValue(Constants.NOTIFICATION_AFTERNOON, isChecked);
}
});
mSwNovel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
proferenceUtils.setValue(Constants.NOTIFICATION_NOVEL, isChecked);
}
});
}
}
| {
"content_hash": "9ad298aca9f8993e668ab34b958872b3",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 106,
"avg_line_length": 33.06930693069307,
"alnum_prop": 0.6808383233532934,
"repo_name": "klisly/fingerpoetry",
"id": "a149b961b1438c0d8dcb2bcea192d4adb43f70ba",
"size": "3340",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/klisly/bookbox/ui/fragment/SettingFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "715399"
}
],
"symlink_target": ""
} |
/*---------------------------------------------------------------------------*/
kodi = require("kodi");
/*---------------------------------------------------------------------------*/
var movie_to_start = 493; // find it in your library
kodi.start_movie(movie_to_start, function(err, resp){
if (!err) {
console.log("start_movie OK! " + JSON.stringify(resp));
} else {
console.log("start_movie FAIL!");
}
});
/*---------------------------------------------------------------------------*/
| {
"content_hash": "c30310c186f263c55bcd513688134501",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 79,
"avg_line_length": 41.833333333333336,
"alnum_prop": 0.3286852589641434,
"repo_name": "msloth/kodi.js",
"id": "c234c621373bbc523fd899a99833f6c0dda96121",
"size": "502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/start-movie.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "24044"
}
],
"symlink_target": ""
} |
<!-- Copyright 2012-2017 Raytheon BBN Technologies Corp. All Rights Reserved. -->
<!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_20) on Wed Nov 15 19:26:01 EST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>adept.common (adept-api 2.7.4 API)</title>
<meta name="date" content="2017-11-15">
<meta name="keywords" content="adept.common package">
<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="adept.common (adept-api 2.7.4 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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 Package</li>
<li><a href="../../adept/data/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?adept/common/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All 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">
<h1 title="Package" class="title">Package adept.common</h1>
<div class="docSummary">
<div class="block">Provides common data structures for use in the ADEPT framework, including the input Document and its TokenStream containing every Token, and the output HltContentContainer containing multiple kinds of annotations, such as EntityMention and Relation, which are based on the Chunk class.</div>
</div>
<p>See: <a href="#package.description">Description</a></p>
</div>
<div class="contentContainer">
<map id="APIVIZ" name="APIVIZ">
<area shape="rect" id="node1" href="../data/AdeptDataException.html" title="«exception» AdeptDataException (adept.data)" alt="" coords="687,3205,836,3267"/>
<area shape="rect" id="node2" href="AdeptException.html" title="«exception» AdeptException" alt="" coords="416,3376,536,3421"/>
<area shape="rect" id="node3" href="../module/AdeptModuleException.html" title="«exception» AdeptModuleException (adept.module)" alt="" coords="679,3290,844,3353"/>
<area shape="rect" id="node4" title="«exception» Exception (java.lang)" alt="" coords="113,3367,212,3430"/>
<area shape="rect" id="node5" href="SpeechDocumentCreationException.html" title="«exception» SpeechDocumentCreationException" alt="" coords="640,3376,883,3421"/>
<area shape="rect" id="node6" href="TextDocumentCreationException.html" title="«exception» TextDocumentCreationException" alt="" coords="651,3445,872,3491"/>
<area shape="rect" id="node7" href="AnomalousText.html" title="AnomalousText" alt="" coords="971,6775,1085,6803"/>
<area shape="rect" id="node8" href="Argument.html" title="Argument" alt="" coords="988,6826,1068,6854"/>
<area shape="rect" id="node9" href="ArgumentTuple.html" title="ArgumentTuple" alt="" coords="971,4511,1085,4539"/>
<area shape="rect" id="node10" href="ArgumentTypeFactory.html" title="ArgumentTypeFactory" alt="" coords="85,3317,240,3345"/>
<area shape="rect" id="node11" title="ArrayList (java.util)" alt="" coords="124,8285,201,8331"/>
<area shape="rect" id="node12" href="Audio.html" title="Audio" alt="" coords="448,5509,504,5537"/>
<area shape="rect" id="node13" href="AudioOffset.html" title="AudioOffset" alt="" coords="429,5610,523,5638"/>
<area shape="rect" id="node14" href="AuthorshipTheory.html" title="AuthorshipTheory" alt="" coords="1175,6122,1303,6150"/>
<area shape="rect" id="node15" href="BeliefMention.Builder.html" title="BeliefMention.Builder" alt="" coords="401,3241,551,3269"/>
<area shape="rect" id="node16" href="BoundedList.html" title="BoundedList" alt="" coords="427,8314,525,8342"/>
<area shape="rect" id="node17" href="CharOffset.html" title="CharOffset" alt="" coords="433,5661,519,5689"/>
<area shape="rect" id="node18" href="Chunk.html" title="Chunk" alt="" coords="999,6218,1057,6246"/>
<area shape="rect" id="node19" href="CommittedBelief.html" title="CommittedBelief" alt="" coords="1177,6367,1300,6395"/>
<area shape="rect" id="node20" href="Conversation.html" title="Conversation" alt="" coords="977,4274,1079,4302"/>
<area shape="rect" id="node21" href="ConversationElement.html" title="ConversationElement" alt="" coords="952,8173,1104,8201"/>
<area shape="rect" id="node22" href="ConversationElementAttributesTypeFactory.html" title="ConversationElementAttributesTypeFactory" alt="" coords="20,3215,305,3243"/>
<area shape="rect" id="node23" href="ConversationElementEntityRelationTypeFactory.html" title="ConversationElementEntityRelationTypeFactory" alt="" coords="7,3165,319,3193"/>
<area shape="rect" id="node24" href="ConversationElementRelationTypeFactory.html" title="ConversationElementRelationTypeFactory" alt="" coords="24,3114,301,3142"/>
<area shape="rect" id="node25" href="ConversationElementTag.html" title="ConversationElementTag" alt="" coords="388,5863,564,5891"/>
<area shape="rect" id="node26" href="Coreference.html" title="Coreference" alt="" coords="980,6877,1076,6905"/>
<area shape="rect" id="node27" href="Corpus.html" title="Corpus" alt="" coords="443,5965,509,5993"/>
<area shape="rect" id="node28" href="DeceptionTheory.html" title="DeceptionTheory" alt="" coords="965,6041,1091,6069"/>
<area shape="rect" id="node29" href="Dependency.html" title="Dependency" alt="" coords="979,6117,1077,6145"/>
<area shape="rect" id="node30" href="DiscourseUnit.html" title="DiscourseUnit" alt="" coords="1185,6246,1292,6274"/>
<area shape="rect" id="node31" href="Document.html" title="Document" alt="" coords="720,4274,803,4302"/>
<area shape="rect" id="node32" href="DocumentBelief.Builder.html" title="DocumentBelief.Builder" alt="" coords="395,3038,557,3066"/>
<area shape="rect" id="node33" href="DocumentEvent.html" title="DocumentEvent" alt="" coords="969,7181,1087,7209"/>
<area shape="rect" id="node34" href="DocumentEvent.Builder.html" title="DocumentEvent.Builder" alt="" coords="81,3013,244,3041"/>
<area shape="rect" id="node35" href="DocumentEvent.Provenance.html" title="DocumentEvent.Provenance" alt="" coords="379,6066,573,6094"/>
<area shape="rect" id="node36" href="DocumentEventArgument.html" title="DocumentEventArgument" alt="" coords="940,7130,1116,7158"/>
<area shape="rect" id="node37" href="DocumentEventArgument.Builder.html" title="DocumentEventArgument.Builder" alt="" coords="52,2962,273,2990"/>
<area shape="rect" id="node38" href="DocumentEventArgument.Filler.html" title="DocumentEventArgument.Filler" alt="" coords="372,6269,580,6297"/>
<area shape="rect" id="node39" href="DocumentEventArgument.Provenance.html" title="DocumentEventArgument.Provenance" alt="" coords="349,6319,603,6347"/>
<area shape="rect" id="node40" href="DocumentList.html" title="DocumentList" alt="" coords="424,8365,528,8393"/>
<area shape="rect" id="node41" href="DocumentMentalStateArgument.html" title="DocumentMentalStateArgument" alt="" coords="920,7029,1136,7057"/>
<area shape="rect" id="node42" href="DocumentMentalStateArgument.Builder.html" title="DocumentMentalStateArgument.Builder" alt="" coords="32,2911,293,2939"/>
<area shape="rect" id="node43" href="DocumentMentalStateArgument.Filler.html" title="DocumentMentalStateArgument.Filler" alt="" coords="352,6421,600,6449"/>
<area shape="rect" id="node44" href="DocumentRelation.html" title="DocumentRelation" alt="" coords="961,7231,1095,7259"/>
<area shape="rect" id="node45" href="DocumentRelation.Builder.html" title="DocumentRelation.Builder" alt="" coords="73,2861,252,2889"/>
<area shape="rect" id="node46" href="DocumentRelationArgument.html" title="DocumentRelationArgument" alt="" coords="932,6978,1124,7006"/>
<area shape="rect" id="node47" href="DocumentRelationArgument.Builder.html" title="DocumentRelationArgument.Builder" alt="" coords="44,2810,281,2838"/>
<area shape="rect" id="node48" href="DocumentRelationArgument.Filler.html" title="DocumentRelationArgument.Filler" alt="" coords="364,6826,588,6854"/>
<area shape="rect" id="node49" href="DocumentSentiment.Builder.html" title="DocumentSentiment.Builder" alt="" coords="381,3089,571,3117"/>
<area shape="rect" id="node50" href="EmailAddress.html" title="EmailAddress" alt="" coords="109,2759,216,2787"/>
<area shape="rect" id="node51" href="Entailment.html" title="Entailment" alt="" coords="985,6167,1071,6195"/>
<area shape="rect" id="node52" href="Entity.html" title="Entity" alt="" coords="1000,7883,1056,7911"/>
<area shape="rect" id="node53" href="EntityAttributesTypeFactory.html" title="EntityAttributesTypeFactory" alt="" coords="68,2709,257,2737"/>
<area shape="rect" id="node54" href="EntityMention.html" title="EntityMention" alt="" coords="1187,6559,1291,6587"/>
<area shape="rect" id="node55" href="EntityTypeFactory.html" title="EntityTypeFactory" alt="" coords="97,2658,228,2686"/>
<area shape="rect" id="node56" href="Event.html" title="Event" alt="" coords="1211,4367,1267,4395"/>
<area shape="rect" id="node57" href="EventMention.html" title="EventMention" alt="" coords="976,7333,1080,7361"/>
<area shape="rect" id="node58" href="EventMention.Builder.html" title="EventMention.Builder" alt="" coords="88,2607,237,2635"/>
<area shape="rect" id="node59" href="EventMentionArgument.html" title="EventMentionArgument" alt="" coords="947,7079,1109,7107"/>
<area shape="rect" id="node60" href="EventMentionArgument.Builder.html" title="EventMentionArgument.Builder" alt="" coords="59,2557,267,2585"/>
<area shape="rect" id="node61" href="EventPhrase.html" title="EventPhrase" alt="" coords="1189,6893,1288,6921"/>
<area shape="rect" id="node62" href="EventRelations.html" title="EventRelations" alt="" coords="419,7909,533,7937"/>
<area shape="rect" id="node63" href="EventText.html" title="EventText" alt="" coords="987,6927,1069,6955"/>
<area shape="rect" id="node64" href="EventText.Builder.html" title="EventText.Builder" alt="" coords="99,2506,227,2534"/>
<area shape="rect" id="node65" href="EventTextSet.html" title="EventTextSet" alt="" coords="976,7282,1080,7310"/>
<area shape="rect" id="node66" href="EventTextSet.Builder.html" title="EventTextSet.Builder" alt="" coords="88,2455,237,2483"/>
<area shape="rect" id="node67" href="EventTypeFactory.html" title="EventTypeFactory" alt="" coords="96,2405,229,2433"/>
<area shape="rect" id="node68" href="GenderTypeFactory.html" title="GenderTypeFactory" alt="" coords="91,2354,235,2382"/>
<area shape="rect" id="node69" href="GenericThing.html" title="GenericThing" alt="" coords="711,5121,812,5149"/>
<area shape="rect" id="node70" href="HltContentContainer.html" title="HltContentContainer" alt="" coords="956,6269,1100,6297"/>
<area shape="rect" id="node71" href="HltContentContainerList.html" title="HltContentContainerList" alt="" coords="393,8263,559,8291"/>
<area shape="rect" id="node72" href="ID.html" title="ID" alt="" coords="459,3463,493,3491"/>
<area shape="rect" id="node73" href="InterPausalUnit.html" title="InterPausalUnit" alt="" coords="972,6319,1084,6347"/>
<area shape="rect" id="node74" href="JointRelationCoreference.html" title="JointRelationCoreference" alt="" coords="940,6370,1116,6398"/>
<area shape="rect" id="node75" href="../data/Justification.html" title="Justification (adept.data)" alt="" coords="712,4901,811,4947"/>
<area shape="rect" id="node76" href="KBID.html" title="KBID" alt="" coords="449,3565,503,3593"/>
<area shape="rect" id="node77" href="LanguageIdentification.html" title="LanguageIdentification" alt="" coords="949,6471,1107,6499"/>
<area shape="rect" id="node78" href="LatticeArc.html" title="LatticeArc" alt="" coords="435,3615,517,3643"/>
<area shape="rect" id="node79" href="LatticePath.html" title="LatticePath" alt="" coords="431,3767,521,3795"/>
<area shape="rect" id="node80" href="MentalStateMention.Filler.html" title="MentalStateMention.Filler" alt="" coords="388,3869,564,3897"/>
<area shape="rect" id="node81" href="MentionTypeFactory.html" title="MentionTypeFactory" alt="" coords="89,2303,236,2331"/>
<area shape="rect" id="node82" href="Morph.html" title="Morph" alt="" coords="447,3919,505,3947"/>
<area shape="rect" id="node83" href="Morph.Builder.html" title="Morph.Builder" alt="" coords="111,2253,215,2281"/>
<area shape="rect" id="node84" href="MorphFeature.html" title="MorphFeature" alt="" coords="423,3970,529,3998"/>
<area shape="rect" id="node85" href="MorphSentence.html" title="MorphSentence" alt="" coords="417,4071,535,4099"/>
<area shape="rect" id="node86" href="MorphSentence.Builder.html" title="MorphSentence.Builder" alt="" coords="81,2202,244,2230"/>
<area shape="rect" id="node87" href="MorphToken.html" title="MorphToken" alt="" coords="428,4122,524,4150"/>
<area shape="rect" id="node88" href="MorphToken.Builder.html" title="MorphToken.Builder" alt="" coords="92,2151,233,2179"/>
<area shape="rect" id="node89" href="MorphTokenSequence.html" title="MorphTokenSequence" alt="" coords="397,4546,555,4574"/>
<area shape="rect" id="node90" href="MorphTokenSequence.Builder.html" title="MorphTokenSequence.Builder" alt="" coords="61,2101,264,2129"/>
<area shape="rect" id="node91" href="MorphType.html" title="MorphType" alt="" coords="431,4597,521,4625"/>
<area shape="rect" id="node92" href="NativeLanguageTypeFactory.html" title="NativeLanguageTypeFactory" alt="" coords="64,2050,261,2078"/>
<area shape="rect" id="node93" href="NumberPhrase.html" title="NumberPhrase" alt="" coords="1183,7510,1295,7538"/>
<area shape="rect" id="node94" href="NumericValue.html" title="NumericValue" alt="" coords="709,4850,813,4878"/>
<area shape="rect" id="node95" href="OntType.html" title="OntType" alt="" coords="439,8061,513,8089"/>
<area shape="rect" id="node96" href="OntTypeFactory.html" title="OntTypeFactory" alt="" coords="416,1990,536,2018"/>
<area shape="rect" id="node97" href="Opinion.html" title="Opinion" alt="" coords="1204,7609,1273,7637"/>
<area shape="rect" id="node98" href="Pair.html" title="Pair" alt="" coords="453,4647,499,4675"/>
<area shape="rect" id="node99" href="Paraphrase.html" title="Paraphrase" alt="" coords="981,5949,1075,5977"/>
<area shape="rect" id="node100" href="PartOfSpeech.html" title="PartOfSpeech" alt="" coords="1185,7683,1292,7711"/>
<area shape="rect" id="node101" href="PartOfSpeechTagFactory.html" title="PartOfSpeechTagFactory" alt="" coords="75,1930,251,1958"/>
<area shape="rect" id="node102" href="Passage.html" title="Passage" alt="" coords="1200,7746,1277,7774"/>
<area shape="rect" id="node103" href="ProsodicPhrase.html" title="ProsodicPhrase" alt="" coords="1180,7802,1297,7830"/>
<area shape="rect" id="node104" href="QuantifiedChunk.html" title="QuantifiedChunk" alt="" coords="1177,7943,1300,7971"/>
<area shape="rect" id="node105" href="QuantifiedChunkAttributesTypeFactory.html" title="QuantifiedChunkAttributesTypeFactory" alt="" coords="35,1879,291,1907"/>
<area shape="rect" id="node106" href="Relation.html" title="Relation" alt="" coords="1203,4630,1275,4658"/>
<area shape="rect" id="node107" href="RelationMention.html" title="RelationMention" alt="" coords="968,6623,1088,6651"/>
<area shape="rect" id="node108" href="RelationMention.Builder.html" title="RelationMention.Builder" alt="" coords="80,1829,245,1857"/>
<area shape="rect" id="node109" href="RelationMention.Filler.html" title="RelationMention.Filler" alt="" coords="400,4698,552,4726"/>
<area shape="rect" id="node110" href="RelationTypeFactory.html" title="RelationTypeFactory" alt="" coords="89,1778,236,1806"/>
<area shape="rect" id="node111" href="Sarcasm.html" title="Sarcasm" alt="" coords="1201,5327,1276,5355"/>
<area shape="rect" id="node112" href="Script.html" title="Script" alt="" coords="1000,6522,1056,6550"/>
<area shape="rect" id="node113" href="ScriptEvent.html" title="ScriptEvent" alt="" coords="431,4799,521,4827"/>
<area shape="rect" id="node114" href="ScriptEventArgument.html" title="ScriptEventArgument" alt="" coords="88,1727,237,1755"/>
<area shape="rect" id="node115" href="ScriptLink.html" title="ScriptLink" alt="" coords="436,4951,516,4979"/>
<area shape="rect" id="node116" href="ScriptVariable.html" title="ScriptVariable" alt="" coords="975,6573,1081,6601"/>
<area shape="rect" id="node117" href="ScriptVariableBinaryConstraint.html" title="ScriptVariableBinaryConstraint" alt="" coords="925,6421,1131,6449"/>
<area shape="rect" id="node118" href="Sentence.html" title="Sentence" alt="" coords="1199,5451,1279,5479"/>
<area shape="rect" id="node119" href="SentenceSimilarity.html" title="SentenceSimilarity" alt="" coords="961,6674,1095,6702"/>
<area shape="rect" id="node120" href="SentimentMention.Builder.html" title="SentimentMention.Builder" alt="" coords="388,3291,564,3319"/>
<area shape="rect" id="node121" href="Session.html" title="Session" alt="" coords="1204,5526,1273,5554"/>
<area shape="rect" id="node122" href="Slot.html" title="Slot" alt="" coords="453,8111,499,8139"/>
<area shape="rect" id="node123" href="Story.html" title="Story" alt="" coords="1212,6195,1265,6223"/>
<area shape="rect" id="node124" href="SyntacticChunk.html" title="SyntacticChunk" alt="" coords="1181,5623,1296,5651"/>
<area shape="rect" id="node125" href="SyntacticTagFactory.html" title="SyntacticTagFactory" alt="" coords="89,1677,236,1705"/>
<area shape="rect" id="node126" href="TACKBP2014EAOutput.html" title="TACKBP2014EAOutput" alt="" coords="81,1626,244,1654"/>
<area shape="rect" id="node127" href="TACKBP2014EventArgument.html" title="TACKBP2014EventArgument" alt="" coords="64,1575,261,1603"/>
<area shape="rect" id="node128" href="TaggedChunk.html" title="TaggedChunk" alt="" coords="1185,5698,1292,5726"/>
<area shape="rect" id="node129" href="TemporalResolution.html" title="TemporalResolution" alt="" coords="405,5002,547,5030"/>
<area shape="rect" id="node130" href="TemporalResolution.Builder.html" title="TemporalResolution.Builder" alt="" coords="69,1525,256,1553"/>
<area shape="rect" id="node131" href="TemporalSpan.html" title="TemporalSpan" alt="" coords="973,6725,1083,6753"/>
<area shape="rect" id="node132" href="TemporalSpan.Builder.html" title="TemporalSpan.Builder" alt="" coords="85,1474,240,1502"/>
<area shape="rect" id="node133" href="TimePhrase.html" title="TimePhrase" alt="" coords="1192,5889,1285,5917"/>
<area shape="rect" id="node134" href="TimexValue.html" title="TimexValue" alt="" coords="715,4495,808,4523"/>
<area shape="rect" id="node135" href="Token.html" title="Token" alt="" coords="732,5003,791,5031"/>
<area shape="rect" id="node136" href="TokenLattice.html" title="TokenLattice" alt="" coords="427,5053,525,5081"/>
<area shape="rect" id="node137" href="TokenOffset.html" title="TokenOffset" alt="" coords="429,5205,523,5233"/>
<area shape="rect" id="node138" href="TokenStream.html" title="TokenStream" alt="" coords="425,8213,527,8241"/>
<area shape="rect" id="node139" href="Topic.html" title="Topic" alt="" coords="136,1423,189,1451"/>
<area shape="rect" id="node140" href="Translation.html" title="Translation" alt="" coords="119,1373,207,1401"/>
<area shape="rect" id="node141" href="Triple.html" title="Triple" alt="" coords="448,5306,504,5334"/>
<area shape="rect" id="node142" href="Type.html" title="Type" alt="" coords="451,8010,501,8038"/>
<area shape="rect" id="node143" href="Utterance.html" title="Utterance" alt="" coords="1199,5983,1279,6011"/>
<area shape="rect" id="node144" href="Value.html" title="Value" alt="" coords="448,8162,504,8190"/>
<area shape="rect" id="node145" href="Viewpoint.html" title="Viewpoint" alt="" coords="121,1322,204,1350"/>
<area shape="rect" id="node146" href="XSDDate.html" title="XSDDate" alt="" coords="721,4435,801,4463"/>
<area shape="rect" id="node147" href="DocumentMentalState.html" title="DocumentMentalState" alt="" coords="952,3666,1104,3694"/>
<area shape="rect" id="node148" href="DocumentMentalState.Builder.html" title="DocumentMentalState.Builder" alt="" coords="65,3063,260,3091"/>
<area shape="rect" id="node149" href="HltContent.html" title="HltContent" alt="" coords="719,6573,804,6601"/>
<area shape="rect" id="node150" href="Item.html" title="Item" alt="" coords="452,4901,500,4929"/>
<area shape="rect" id="node151" href="MentalStateMention.html" title="MentalStateMention" alt="" coords="959,4062,1097,4090"/>
<area shape="rect" id="node152" href="MentalStateMention.Builder.html" title="MentalStateMention.Builder" alt="" coords="72,3266,253,3294"/>
<area shape="rect" id="node153" title="«interface» Comparable (java.lang)" alt="" coords="712,5863,811,5926"/>
<area shape="rect" id="node154" href="HasChunkAttributes.html" title="«interface» HasChunkAttributes" alt="" coords="957,7935,1099,7980"/>
<area shape="rect" id="node155" href="HasConversationElementTagAttributes.html" title="«interface» HasConversationElementTagAttributes" alt="" coords="632,8133,891,8179"/>
<area shape="rect" id="node156" href="HasFreeTextAttributes.html" title="«interface» HasFreeTextAttributes" alt="" coords="683,8064,840,8109"/>
<area shape="rect" id="node157" href="HasOntologizedAttributes.html" title="«interface» HasOntologizedAttributes" alt="" coords="672,7995,851,8040"/>
<area shape="rect" id="node158" href="HasScoredUnaryAttributes.html" title="«interface» HasScoredUnaryAttributes" alt="" coords="671,7131,852,7176"/>
<area shape="rect" id="node159" href="IConversationElementEntityRelation.html" title="«interface» IConversationElementEntityRelation" alt="" coords="641,8323,881,8368"/>
<area shape="rect" id="node160" href="IConversationElementRelation.html" title="«interface» IConversationElementRelation" alt="" coords="659,8253,864,8299"/>
<area shape="rect" id="node161" href="../data/IEntity.html" title="«interface» IEntity (adept.data)" alt="" coords="712,7909,811,7971"/>
<area shape="rect" id="node162" href="../data/ISlot.html" title="«interface» ISlot (adept.data)" alt="" coords="113,8089,212,8151"/>
<area shape="rect" id="node163" href="IType.html" title="«interface» IType" alt="" coords="117,8008,208,8053"/>
<area shape="rect" id="node164" href="ITypeFactory.html" title="«interface» ITypeFactory" alt="" coords="112,1981,213,2027"/>
<area shape="rect" id="node165" href="../data/IValue.html" title="«interface» IValue (adept.data)" alt="" coords="113,8174,212,8237"/>
<area shape="rect" id="node166" title="«interface» Serializable (java.io)" alt="" coords="116,5821,209,5883"/>
<area shape="rect" id="node167" href="TemporalValue.html" title="«interface» TemporalValue" alt="" coords="420,4427,532,4472"/>
<area shape="rect" id="node168" href="BeliefMention.html" title="«static» BeliefMention" alt="" coords="1187,3932,1291,3977"/>
<area shape="rect" id="node169" href="DocumentBelief.html" title="«static» DocumentBelief" alt="" coords="1180,3547,1297,3592"/>
<area shape="rect" id="node170" href="DocumentSentiment.html" title="«static» DocumentSentiment" alt="" coords="1167,3683,1311,3728"/>
<area shape="rect" id="node171" href="SentimentMention.html" title="«static» SentimentMention" alt="" coords="1173,4109,1304,4155"/>
<area shape="rect" id="node172" href="AsrName.html" title="«enum» AsrName" alt="" coords="124,1253,201,1299"/>
<area shape="rect" id="node173" href="AudioFileType.html" title="«enum» AudioFileType" alt="" coords="108,1184,217,1229"/>
<area shape="rect" id="node174" href="ChannelName.html" title="«enum» ChannelName" alt="" coords="109,1115,216,1160"/>
<area shape="rect" id="node175" href="ContentType.html" title="«enum» ContentType" alt="" coords="113,1045,212,1091"/>
<area shape="rect" id="node176" href="ConversationType.html" title="«enum» ConversationType" alt="" coords="96,976,229,1021"/>
<area shape="rect" id="node177" href="Entailment.Judgment.html" title="«enum» Entailment.Judgment" alt="" coords="88,907,237,952"/>
<area shape="rect" id="node178" href="MentalStateType.html" title="«enum» MentalStateType" alt="" coords="100,837,225,883"/>
<area shape="rect" id="node179" href="Modality.html" title="«enum» Modality" alt="" coords="125,768,200,813"/>
<area shape="rect" id="node180" href="Polarity.html" title="«enum» Polarity" alt="" coords="128,699,197,744"/>
<area shape="rect" id="node181" href="Sarcasm.Judgment.html" title="«enum» Sarcasm.Judgment" alt="" coords="93,629,232,675"/>
<area shape="rect" id="node182" href="SentenceType.html" title="«enum» SentenceType" alt="" coords="108,560,217,605"/>
<area shape="rect" id="node183" href="SpeechUnit.html" title="«enum» SpeechUnit" alt="" coords="117,491,208,536"/>
<area shape="rect" id="node184" href="Subjectivity.html" title="«enum» Subjectivity" alt="" coords="117,421,208,467"/>
<area shape="rect" id="node185" href="TACKBP2014EventArgument.Realis.html" title="«enum» TACKBP2014EventArgument.Realis" alt="" coords="44,352,281,397"/>
<area shape="rect" id="node186" href="TokenType.html" title="«enum» TokenType" alt="" coords="119,283,207,328"/>
<area shape="rect" id="node187" href="TokenizerType.html" title="«enum» TokenizerType" alt="" coords="108,213,217,259"/>
<area shape="rect" id="node188" href="Topic.Polarity.html" title="«enum» Topic.Polarity" alt="" coords="111,144,215,189"/>
<area shape="rect" id="node189" href="TranscriptType.html" title="«enum» TranscriptType" alt="" coords="107,75,219,120"/>
<area shape="rect" id="node190" href="TranslatorName.html" title="«enum» TranslatorName" alt="" coords="104,5,221,51"/>
</map>
<div id="apivizContainer" style="text-align: center;margin-bottom: 1em;"><img src="package-summary.png" usemap="#APIVIZ" border="0"></div>
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/HasChunkAttributes.html" title="interface in adept.common">HasChunkAttributes</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type Chunk.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/HasConversationElementTagAttributes.html" title="interface in adept.common">HasConversationElementTagAttributes</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type ConversationElementTag.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/HasFreeTextAttributes.html" title="interface in adept.common">HasFreeTextAttributes</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type String.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/HasOntologizedAttributes.html" title="interface in adept.common">HasOntologizedAttributes</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/HasScoredUnaryAttributes.html" title="interface in adept.common">HasScoredUnaryAttributes</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry float-valued flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/IConversationElementEntityRelation.html" title="interface in adept.common">IConversationElementEntityRelation</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type List<Entity>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/IConversationElementRelation.html" title="interface in adept.common">IConversationElementRelation</a></td>
<td class="colLast">
<div class="block">Indicates a class can carry flags of type <a href="../../adept/common/IType.html" title="interface in adept.common"><code>IType</code></a> mapping to values of type List<ConversationElement>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/IType.html" title="interface in adept.common">IType</a></td>
<td class="colLast">
<div class="block">The interface IType for recording Ontology type.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ITypeFactory.html" title="interface in adept.common">ITypeFactory</a></td>
<td class="colLast">
<div class="block">The Class Type.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TemporalValue.html" title="interface in adept.common">TemporalValue</a></td>
<td class="colLast">
<div class="block">Represents a temporal value, abstracted from its particular realization in text.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/AnomalousText.html" title="class in adept.common">AnomalousText</a></td>
<td class="colLast">
<div class="block">The Class AnomalousText.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Argument.html" title="class in adept.common">Argument</a></td>
<td class="colLast">
<div class="block">The Class Argument, which contains one or more Chunk objects along with their associated probabilities.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ArgumentTuple.html" title="class in adept.common">ArgumentTuple</a></td>
<td class="colLast">
<div class="block">The Class Relation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ArgumentTypeFactory.html" title="class in adept.common">ArgumentTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating ArgumentType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Audio.html" title="class in adept.common">Audio</a></td>
<td class="colLast">
<div class="block">The Class Audio.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/AudioOffset.html" title="class in adept.common">AudioOffset</a></td>
<td class="colLast">
<div class="block">Captures the begin and end time of an audio span.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/AuthorshipTheory.html" title="class in adept.common">AuthorshipTheory</a></td>
<td class="colLast">
<div class="block">The Class AuthorshipTheory.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/BeliefMention.html" title="class in adept.common">BeliefMention</a></td>
<td class="colLast">
<div class="block">Represents a textual belief.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/BeliefMention.Builder.html" title="class in adept.common">BeliefMention.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/BoundedList.html" title="class in adept.common">BoundedList</a><E></td>
<td class="colLast">
<div class="block">An extension class of ArrayList which has a fixed size/capacity.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/CharOffset.html" title="class in adept.common">CharOffset</a></td>
<td class="colLast">
<div class="block">Captures the begin and end integer positions of character spans.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Chunk.html" title="class in adept.common">Chunk</a></td>
<td class="colLast">
<div class="block">The Class Chunk, which is a sequence of tokens that comprise
a phrase or other syntactic unit within a sentence.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/CommittedBelief.html" title="class in adept.common">CommittedBelief</a></td>
<td class="colLast">
<div class="block">The Class CommittedBelief.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Conversation.html" title="class in adept.common">Conversation</a></td>
<td class="colLast">
<div class="block">Represents a thread where the messages are successive chunks of text,
including the authors who are participants in the thread.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ConversationElement.html" title="class in adept.common">ConversationElement</a></td>
<td class="colLast">
<div class="block">The Class ConversationElement, which represents the
units of Conversation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ConversationElementAttributesTypeFactory.html" title="class in adept.common">ConversationElementAttributesTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating ConversationElementAttributesType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ConversationElementEntityRelationTypeFactory.html" title="class in adept.common">ConversationElementEntityRelationTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating ConversationElementEntityRelationsType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ConversationElementRelationTypeFactory.html" title="class in adept.common">ConversationElementRelationTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating ConversationElementRelationType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ConversationElementTag.html" title="class in adept.common">ConversationElementTag</a></td>
<td class="colLast">
<div class="block">The Class ConversationElementTag, which represents an SGML tag within a structured document.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Coreference.html" title="class in adept.common">Coreference</a></td>
<td class="colLast">
<div class="block">The Class Coreference, which is a relationship between two or more words
or phrases in which both refer to the same entity and one stands as a
linguistic antecedent of the other.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Corpus.html" title="class in adept.common">Corpus</a></td>
<td class="colLast">
<div class="block">The Class Corpus.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DeceptionTheory.html" title="class in adept.common">DeceptionTheory</a></td>
<td class="colLast">
<div class="block">The Class DeceptionTheory.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Dependency.html" title="class in adept.common">Dependency</a></td>
<td class="colLast">
<div class="block">The Class Dependency.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DiscourseUnit.html" title="class in adept.common">DiscourseUnit</a></td>
<td class="colLast">
<div class="block">The Class DiscourseUnit.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Document.html" title="class in adept.common">Document</a></td>
<td class="colLast">
<div class="block">The Class Document, which represents a piece of written,
printed, or electronic matter that provides information
or evidence or that serves as an official record.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentBelief.html" title="class in adept.common">DocumentBelief</a></td>
<td class="colLast">
<div class="block">Represents a belief at the level of participating document-level entities, relations, and arguments,
rather than strings of text.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentBelief.Builder.html" title="class in adept.common">DocumentBelief.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentEvent.html" title="class in adept.common">DocumentEvent</a></td>
<td class="colLast">
<div class="block">Represents an event at the level of participating document-level entities,
rather than strings of text.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentEvent.Builder.html" title="class in adept.common">DocumentEvent.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentEvent.Provenance.html" title="class in adept.common">DocumentEvent.Provenance</a></td>
<td class="colLast">
<div class="block">Represents evidence for the existence of an event.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentEventArgument.html" title="class in adept.common">DocumentEventArgument</a></td>
<td class="colLast">
<div class="block">Represents the argument of an event.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentEventArgument.Builder.html" title="class in adept.common">DocumentEventArgument.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentEventArgument.Filler.html" title="class in adept.common">DocumentEventArgument.Filler</a></td>
<td class="colLast">
<div class="block">A filler for a role in a document-level event.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentEventArgument.Provenance.html" title="class in adept.common">DocumentEventArgument.Provenance</a></td>
<td class="colLast">
<div class="block">Represents the source of an event argument.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentList.html" title="class in adept.common">DocumentList</a></td>
<td class="colLast">
<div class="block">The Class DocumentList.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentMentalState.html" title="class in adept.common">DocumentMentalState</a><T extends <a href="../../adept/common/MentalStateMention.html" title="class in adept.common">MentalStateMention</a>></td>
<td class="colLast">
<div class="block">Internal abstract class representing the commonality between
DocumentSentiment and DocumentBelief.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentMentalState.Builder.html" title="class in adept.common">DocumentMentalState.Builder</a><BuilderType extends <a href="../../adept/common/DocumentMentalState.Builder.html" title="class in adept.common">DocumentMentalState.Builder</a><BuilderType,MentionType>,MentionType extends <a href="../../adept/common/MentalStateMention.html" title="class in adept.common">MentalStateMention</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentMentalStateArgument.html" title="class in adept.common">DocumentMentalStateArgument</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentMentalStateArgument.Builder.html" title="class in adept.common">DocumentMentalStateArgument.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentMentalStateArgument.Filler.html" title="class in adept.common">DocumentMentalStateArgument.Filler</a></td>
<td class="colLast">
<div class="block">A filler for a role in a document-level mental state.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentRelation.html" title="class in adept.common">DocumentRelation</a></td>
<td class="colLast">
<div class="block">Represents a relation at the level of participating document-level entities
and the like, rather than strings of text.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentRelation.Builder.html" title="class in adept.common">DocumentRelation.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentRelationArgument.html" title="class in adept.common">DocumentRelationArgument</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentRelationArgument.Builder.html" title="class in adept.common">DocumentRelationArgument.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentRelationArgument.Filler.html" title="class in adept.common">DocumentRelationArgument.Filler</a></td>
<td class="colLast">
<div class="block">A filler for a role in a document-level relation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/DocumentSentiment.html" title="class in adept.common">DocumentSentiment</a></td>
<td class="colLast">
<div class="block">Represents a sentiment at the level of participating document-level entities, relations, and arguments,
rather than strings of text.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/DocumentSentiment.Builder.html" title="class in adept.common">DocumentSentiment.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EmailAddress.html" title="class in adept.common">EmailAddress</a></td>
<td class="colLast">
<div class="block">The Class EmailAddress.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Entailment.html" title="class in adept.common">Entailment</a></td>
<td class="colLast">
<div class="block">The Class Entailment.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Entity.html" title="class in adept.common">Entity</a></td>
<td class="colLast">
<div class="block">The Class Entity, which is a thing in concrete or abstract reality
that can be identified by its distinct properties, for example persons,
organizations, locations, expressions of times, quantities and
monetary values.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EntityAttributesTypeFactory.html" title="class in adept.common">EntityAttributesTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating EntityAttributesType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EntityMention.html" title="class in adept.common">EntityMention</a></td>
<td class="colLast">
<div class="block">The Class EntityMention, which is a sequence of tokens
that refer to an Entity with mention type that is drawn
from an ontology</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EntityTypeFactory.html" title="class in adept.common">EntityTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating EntityType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Event.html" title="class in adept.common">Event</a></td>
<td class="colLast">
<div class="block">The Class Event, which represents something
that happens or is regarded as happening;
an occurrence, especially one of some importance.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventMention.html" title="class in adept.common">EventMention</a></td>
<td class="colLast">
<div class="block">Represents an event where the arguments are particular
chunks of text which may or may not be further resolved.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EventMention.Builder.html" title="class in adept.common">EventMention.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventMentionArgument.html" title="class in adept.common">EventMentionArgument</a></td>
<td class="colLast">
<div class="block">Represents that a particular span of text plays a role in an event.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EventMentionArgument.Builder.html" title="class in adept.common">EventMentionArgument.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventPhrase.html" title="class in adept.common">EventPhrase</a></td>
<td class="colLast">Deprecated</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EventRelations.html" title="class in adept.common">EventRelations</a></td>
<td class="colLast">Deprecated</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventText.html" title="class in adept.common">EventText</a></td>
<td class="colLast">
<div class="block">Represents some textual evidence that an event occurred.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EventText.Builder.html" title="class in adept.common">EventText.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventTextSet.html" title="class in adept.common">EventTextSet</a></td>
<td class="colLast">
<div class="block">Represents a set of event occurrence.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/EventTextSet.Builder.html" title="class in adept.common">EventTextSet.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/EventTypeFactory.html" title="class in adept.common">EventTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating EventType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/GenderTypeFactory.html" title="class in adept.common">GenderTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating GenderType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/GenericThing.html" title="class in adept.common">GenericThing</a></td>
<td class="colLast">
<div class="block">Represents a generic thing, abstracted from its particular realization in text.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/HltContent.html" title="class in adept.common">HltContent</a></td>
<td class="colLast">
<div class="block">The Class HltContent is an abstract class that represents all the HLT content
generated by DEFT algorithms.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/HltContentContainer.html" title="class in adept.common">HltContentContainer</a></td>
<td class="colLast">
<div class="block">The Class HltContentContainer, which contains the
full annotation of an input Document, including
objects such as Coreference, EntityMention, Event,
Passage, Relation and Sentence.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/HltContentContainerList.html" title="class in adept.common">HltContentContainerList</a></td>
<td class="colLast">
<div class="block">The Class HltContentContainerList.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ID.html" title="class in adept.common">ID</a></td>
<td class="colLast">
<div class="block">The Class ID defines an identifier for all instances of objects used in the
ADEPT framework.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/InterPausalUnit.html" title="class in adept.common">InterPausalUnit</a></td>
<td class="colLast">
<div class="block">The Class InterPausalUnit.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Item.html" title="class in adept.common">Item</a></td>
<td class="colLast">
<div class="block">An abstract definition of an item, which is composed of an id and a value.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/JointRelationCoreference.html" title="class in adept.common">JointRelationCoreference</a></td>
<td class="colLast">
<div class="block">The Class JointRelationCoreference represents the container for the output of
the algorithm that processes both coreference resolution and relation
extraction simultaneously.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/KBID.html" title="class in adept.common">KBID</a></td>
<td class="colLast">
<div class="block">Represents a generic KB ID.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/LanguageIdentification.html" title="class in adept.common">LanguageIdentification</a></td>
<td class="colLast">
<div class="block">The Class LanguageIdentification.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/LatticeArc.html" title="class in adept.common">LatticeArc</a></td>
<td class="colLast">
<div class="block">The Class LatticeArc.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/LatticePath.html" title="class in adept.common">LatticePath</a></td>
<td class="colLast">
<div class="block">The Class LatticePath.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MentalStateMention.html" title="class in adept.common">MentalStateMention</a></td>
<td class="colLast">
<div class="block">Internal abstract class representing the commonality between
SentimentMention and BeliefMention.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MentalStateMention.Builder.html" title="class in adept.common">MentalStateMention.Builder</a><BuilderType extends <a href="../../adept/common/MentalStateMention.Builder.html" title="class in adept.common">MentalStateMention.Builder</a><BuilderType>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MentalStateMention.Filler.html" title="class in adept.common">MentalStateMention.Filler</a></td>
<td class="colLast">
<div class="block">A filler for a role in a textual MentalState mention.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MentionTypeFactory.html" title="class in adept.common">MentionTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating MentionType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Morph.html" title="class in adept.common">Morph</a></td>
<td class="colLast">
<div class="block">Represents a morph.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Morph.Builder.html" title="class in adept.common">Morph.Builder</a></td>
<td class="colLast">
<div class="block">Builds <a href="../../adept/common/Morph.html" title="class in adept.common"><code>Morph</code></a> instances.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MorphFeature.html" title="class in adept.common">MorphFeature</a></td>
<td class="colLast">
<div class="block">Represents a morphological feature.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MorphSentence.html" title="class in adept.common">MorphSentence</a></td>
<td class="colLast">
<div class="block">Represents the morphological information for a sentence.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MorphSentence.Builder.html" title="class in adept.common">MorphSentence.Builder</a></td>
<td class="colLast">
<div class="block">Builds <a href="../../adept/common/MorphSentence.html" title="class in adept.common"><code>MorphSentence</code></a> objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MorphToken.html" title="class in adept.common">MorphToken</a></td>
<td class="colLast">
<div class="block">Represents a morphological token.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MorphToken.Builder.html" title="class in adept.common">MorphToken.Builder</a></td>
<td class="colLast">
<div class="block">Builds <a href="../../adept/common/MorphToken.html" title="class in adept.common"><code>MorphToken</code></a> instances.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MorphTokenSequence.html" title="class in adept.common">MorphTokenSequence</a></td>
<td class="colLast">
<div class="block">Represents a sequence of morphological tokens.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MorphTokenSequence.Builder.html" title="class in adept.common">MorphTokenSequence.Builder</a></td>
<td class="colLast">
<div class="block">Builds <a href="../../adept/common/MorphTokenSequence.html" title="class in adept.common"><code>MorphTokenSequence</code></a> objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/MorphType.html" title="class in adept.common">MorphType</a></td>
<td class="colLast">
<div class="block">Represents the types of morphs.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/NativeLanguageTypeFactory.html" title="class in adept.common">NativeLanguageTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating NativeLanguageType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/NumberPhrase.html" title="class in adept.common">NumberPhrase</a></td>
<td class="colLast">
<div class="block">The Class NumberPhrase.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/NumericValue.html" title="class in adept.common">NumericValue</a></td>
<td class="colLast">
<div class="block">Represents a numeric value, abstracted from its particular realization in text.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/OntType.html" title="class in adept.common">OntType</a></td>
<td class="colLast">
<div class="block">The Class OntType, which represents one concept
from an ontology, where the ontology formally
represents knowledge as a set of concepts within
a domain using a shared vocabulary.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/OntTypeFactory.html" title="class in adept.common">OntTypeFactory</a></td>
<td class="colLast">
<div class="block">The Class Type.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Opinion.html" title="class in adept.common">Opinion</a></td>
<td class="colLast">
<div class="block">The Class Opinion.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Pair.html" title="class in adept.common">Pair</a><L,R></td>
<td class="colLast">
<div class="block">A generic, simple pair class for storing key-value or pair data.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Paraphrase.html" title="class in adept.common">Paraphrase</a></td>
<td class="colLast">
<div class="block">Holds a value for a paraphrase of a string or a <a href="../../adept/common/Chunk.html" title="class in adept.common"><code>Chunk</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/PartOfSpeech.html" title="class in adept.common">PartOfSpeech</a></td>
<td class="colLast">
<div class="block">The Class PartOfSpeech.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/PartOfSpeechTagFactory.html" title="class in adept.common">PartOfSpeechTagFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating PartOfSpeechTag objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Passage.html" title="class in adept.common">Passage</a></td>
<td class="colLast">
<div class="block">The Class Passage, which represents a section of text
which has been extracted from a document, particularly
a section of medium length.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ProsodicPhrase.html" title="class in adept.common">ProsodicPhrase</a></td>
<td class="colLast">
<div class="block">The Class ProsodicPhrase.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/QuantifiedChunk.html" title="class in adept.common">QuantifiedChunk</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/QuantifiedChunkAttributesTypeFactory.html" title="class in adept.common">QuantifiedChunkAttributesTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating QuantifiedChunkAttributesType objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Relation.html" title="class in adept.common">Relation</a></td>
<td class="colLast">
<div class="block">The Class Relation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/RelationMention.html" title="class in adept.common">RelationMention</a></td>
<td class="colLast">
<div class="block">Represents a textual relation.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/RelationMention.Builder.html" title="class in adept.common">RelationMention.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/RelationMention.Filler.html" title="class in adept.common">RelationMention.Filler</a></td>
<td class="colLast">
<div class="block">A filler for a role in a textual relation mention.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/RelationTypeFactory.html" title="class in adept.common">RelationTypeFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating RelationType objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Sarcasm.html" title="class in adept.common">Sarcasm</a></td>
<td class="colLast">
<div class="block">The Class Sarcasm.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Script.html" title="class in adept.common">Script</a></td>
<td class="colLast">
<div class="block">Represents a generic pattern of events with some relation to one another.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ScriptEvent.html" title="class in adept.common">ScriptEvent</a></td>
<td class="colLast">
<div class="block">An event in a <a href="../../adept/common/Script.html" title="class in adept.common"><code>Script</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ScriptEventArgument.html" title="class in adept.common">ScriptEventArgument</a></td>
<td class="colLast">
<div class="block">Represents an event argument in a <a href="../../adept/common/Script.html" title="class in adept.common"><code>Script</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ScriptLink.html" title="class in adept.common">ScriptLink</a></td>
<td class="colLast">
<div class="block">Represents a link between two script events.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ScriptVariable.html" title="class in adept.common">ScriptVariable</a></td>
<td class="colLast">
<div class="block">A variable in an event script.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ScriptVariableBinaryConstraint.html" title="class in adept.common">ScriptVariableBinaryConstraint</a></td>
<td class="colLast">
<div class="block">A constraint which holds between two variables in an event script.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Sentence.html" title="class in adept.common">Sentence</a></td>
<td class="colLast">
<div class="block">The Sentence class extends Chunk and represents the output from sentence
boundary detection algorithm.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/SentenceSimilarity.html" title="class in adept.common">SentenceSimilarity</a></td>
<td class="colLast">
<div class="block">The Class SentenceSimilarity.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/SentimentMention.html" title="class in adept.common">SentimentMention</a></td>
<td class="colLast">
<div class="block">Represents a textual sentiment.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/SentimentMention.Builder.html" title="class in adept.common">SentimentMention.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Session.html" title="class in adept.common">Session</a></td>
<td class="colLast">
<div class="block">The Class Session.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Slot.html" title="class in adept.common">Slot</a></td>
<td class="colLast">
<div class="block">The Class Slot.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Story.html" title="class in adept.common">Story</a></td>
<td class="colLast">
<div class="block">The Class Story.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/SyntacticChunk.html" title="class in adept.common">SyntacticChunk</a></td>
<td class="colLast">
<div class="block">The Class SyntacticChunk.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/SyntacticTagFactory.html" title="class in adept.common">SyntacticTagFactory</a></td>
<td class="colLast">
<div class="block">A factory for creating SyntacticTag objects.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TACKBP2014EAOutput.html" title="class in adept.common">TACKBP2014EAOutput</a></td>
<td class="colLast">
<div class="block">Represents the output of a a 2014 TAC KBP event argument system on a document.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TACKBP2014EventArgument.html" title="class in adept.common">TACKBP2014EventArgument</a></td>
<td class="colLast">
<div class="block">This represents event arguments produced by a TAC KBP 2014 Event Argument
evaluation system.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TaggedChunk.html" title="class in adept.common">TaggedChunk</a></td>
<td class="colLast">
<div class="block">The Class TaggedChunk.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TemporalResolution.html" title="class in adept.common">TemporalResolution</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TemporalResolution.Builder.html" title="class in adept.common">TemporalResolution.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TemporalSpan.html" title="class in adept.common">TemporalSpan</a></td>
<td class="colLast">
<div class="block">Represents a TemporalSpan, or a span between a begin date and an end date.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TemporalSpan.Builder.html" title="class in adept.common">TemporalSpan.Builder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TimePhrase.html" title="class in adept.common">TimePhrase</a></td>
<td class="colLast">
<div class="block">The Class TimePhrase.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TimexValue.html" title="class in adept.common">TimexValue</a></td>
<td class="colLast">
<div class="block">Represents a TIMEX temporal value.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Token.html" title="class in adept.common">Token</a></td>
<td class="colLast">
<div class="block">The Class Token, which is a single word or
other lexically-defined character sequence
within a document.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TokenLattice.html" title="class in adept.common">TokenLattice</a></td>
<td class="colLast">
<div class="block">The Class TokenLattice.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TokenOffset.html" title="class in adept.common">TokenOffset</a></td>
<td class="colLast">
<div class="block">Captures the begin and end integer positions of token spans.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TokenStream.html" title="class in adept.common">TokenStream</a></td>
<td class="colLast">
<div class="block">The Class TokenStream, which is a list of tokens
and represents the tokenized form of a entire document.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Topic.html" title="class in adept.common">Topic</a></td>
<td class="colLast">
<div class="block">The Class Topic.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Translation.html" title="class in adept.common">Translation</a></td>
<td class="colLast">
<div class="block">The Class Translation.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Triple.html" title="class in adept.common">Triple</a></td>
<td class="colLast">
<div class="block">The Class Triple.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Type.html" title="class in adept.common">Type</a></td>
<td class="colLast">
<div class="block">The Class Type.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Utterance.html" title="class in adept.common">Utterance</a></td>
<td class="colLast">
<div class="block">The Class Utterance.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Value.html" title="class in adept.common">Value</a></td>
<td class="colLast">
<div class="block">The Class Value.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Viewpoint.html" title="class in adept.common">Viewpoint</a></td>
<td class="colLast">
<div class="block">The Class Viewpoint.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/XSDDate.html" title="class in adept.common">XSDDate</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/AsrName.html" title="enum in adept.common">AsrName</a></td>
<td class="colLast">
<div class="block">The Enum AsrName.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/AudioFileType.html" title="enum in adept.common">AudioFileType</a></td>
<td class="colLast">
<div class="block">The Enum AudioFileType.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ChannelName.html" title="enum in adept.common">ChannelName</a></td>
<td class="colLast">
<div class="block">The Enum ChannelName.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/ContentType.html" title="enum in adept.common">ContentType</a></td>
<td class="colLast">
<div class="block">The Enum ContentType.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/ConversationType.html" title="enum in adept.common">ConversationType</a></td>
<td class="colLast">
<div class="block">The Enum ConversationType.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Entailment.Judgment.html" title="enum in adept.common">Entailment.Judgment</a></td>
<td class="colLast">
<div class="block">The Enum Judgment.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/MentalStateType.html" title="enum in adept.common">MentalStateType</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Modality.html" title="enum in adept.common">Modality</a></td>
<td class="colLast">
<div class="block">The Enum Modality.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Polarity.html" title="enum in adept.common">Polarity</a></td>
<td class="colLast">
<div class="block">The Enum Polarity.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/Sarcasm.Judgment.html" title="enum in adept.common">Sarcasm.Judgment</a></td>
<td class="colLast">
<div class="block">The Enum Judgment.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/SentenceType.html" title="enum in adept.common">SentenceType</a></td>
<td class="colLast">
<div class="block">The Enum SentenceType.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/SpeechUnit.html" title="enum in adept.common">SpeechUnit</a></td>
<td class="colLast">
<div class="block">The Enum SpeechUnit.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Subjectivity.html" title="enum in adept.common">Subjectivity</a></td>
<td class="colLast">
<div class="block">The Enum Subjectivity.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TACKBP2014EventArgument.Realis.html" title="enum in adept.common">TACKBP2014EventArgument.Realis</a></td>
<td class="colLast">
<div class="block">This represents the realis distinctions from the 2014 TAC KBP
event argument evaluation.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TokenizerType.html" title="enum in adept.common">TokenizerType</a></td>
<td class="colLast">
<div class="block">The Enum TokenizerType.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TokenType.html" title="enum in adept.common">TokenType</a></td>
<td class="colLast">
<div class="block">The Enum TokenType.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/Topic.Polarity.html" title="enum in adept.common">Topic.Polarity</a></td>
<td class="colLast">
<div class="block">The Enum Polarity.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/TranscriptType.html" title="enum in adept.common">TranscriptType</a></td>
<td class="colLast">
<div class="block">The Enum ContentType.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TranslatorName.html" title="enum in adept.common">TranslatorName</a></td>
<td class="colLast">
<div class="block">The Enum TranslatorName.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Exception Summary table, listing exceptions, and an explanation">
<caption><span>Exception Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Exception</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/AdeptException.html" title="class in adept.common">AdeptException</a></td>
<td class="colLast">
<div class="block">The Class AdeptException.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../adept/common/SpeechDocumentCreationException.html" title="class in adept.common">SpeechDocumentCreationException</a></td>
<td class="colLast">
<div class="block">SpeechDocumentCreationException e is thrown when a SpeechDocument cannot be
created.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../adept/common/TextDocumentCreationException.html" title="class in adept.common">TextDocumentCreationException</a></td>
<td class="colLast">
<div class="block">TextDocumentCreationException is thrown when a text document cannot be
created.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package.description">
<!-- -->
</a>
<h2 title="Package adept.common Description">Package adept.common Description</h2>
<div class="block">Provides common data structures for use in the ADEPT framework, including the input Document and its TokenStream containing every Token, and the output HltContentContainer containing multiple kinds of annotations, such as EntityMention and Relation, which are based on the Chunk class.</div>
</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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 Package</li>
<li><a href="../../adept/data/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?adept/common/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All 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 © 2012–2017 Raytheon BBN Technologies. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "5be04657f6264fe8d802b88722ab24d2",
"timestamp": "",
"source": "github",
"line_count": 1447,
"max_line_length": 457,
"avg_line_length": 54.09260539046303,
"alnum_prop": 0.7107522485690924,
"repo_name": "BBN-E/Adept",
"id": "212fc21f487d66503915e49c15db271265cb7dc5",
"size": "78272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadocs/adept-api/adept/common/package-summary.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25616"
},
{
"name": "HTML",
"bytes": "15089709"
},
{
"name": "Java",
"bytes": "2467577"
},
{
"name": "JavaScript",
"bytes": "1654"
},
{
"name": "Python",
"bytes": "7958"
},
{
"name": "Scheme",
"bytes": "255519"
},
{
"name": "XSLT",
"bytes": "489564"
}
],
"symlink_target": ""
} |
// Template Source: BaseEntityCollectionRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.RbacApplication;
import com.microsoft.graph.models.UnifiedRoleAssignmentSchedule;
import com.microsoft.graph.models.RoleAssignmentScheduleFilterByCurrentUserOptions;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.UnifiedRoleAssignmentScheduleCollectionRequestBuilder;
import com.microsoft.graph.requests.UnifiedRoleAssignmentScheduleRequestBuilder;
import com.microsoft.graph.requests.UnifiedRoleAssignmentScheduleCollectionRequest;
import com.microsoft.graph.requests.UnifiedRoleAssignmentScheduleFilterByCurrentUserCollectionRequestBuilder;
import com.microsoft.graph.http.BaseCollectionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.PrimitiveRequestBuilder;
import com.microsoft.graph.models.UnifiedRoleAssignmentScheduleFilterByCurrentUserParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Unified Role Assignment Schedule Collection Request Builder.
*/
public class UnifiedRoleAssignmentScheduleCollectionRequestBuilder extends BaseCollectionRequestBuilder<UnifiedRoleAssignmentSchedule, UnifiedRoleAssignmentScheduleRequestBuilder, UnifiedRoleAssignmentScheduleCollectionResponse, UnifiedRoleAssignmentScheduleCollectionPage, UnifiedRoleAssignmentScheduleCollectionRequest> {
/**
* The request builder for this collection of RbacApplication
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public UnifiedRoleAssignmentScheduleCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, UnifiedRoleAssignmentScheduleRequestBuilder.class, UnifiedRoleAssignmentScheduleCollectionRequest.class);
}
/**
* Gets a builder to execute the method
* @return the request builder collection
* @param parameters the parameters for the service method
*/
@Nonnull
public UnifiedRoleAssignmentScheduleFilterByCurrentUserCollectionRequestBuilder filterByCurrentUser(@Nonnull final UnifiedRoleAssignmentScheduleFilterByCurrentUserParameterSet parameters) {
return new UnifiedRoleAssignmentScheduleFilterByCurrentUserCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.filterByCurrentUser"), getClient(), null, parameters);
}
/**
* Gets the raw count request for the collection
* @return The raw count request for the collection
*/
@Nonnull
public PrimitiveRequestBuilder<Long> count() {
return new PrimitiveRequestBuilder<Long>(getRequestUrlWithAdditionalSegment("$count"), getClient(), null, Long.class);
}
}
| {
"content_hash": "8042ea0f1c519a39ccac6b16cef7398d",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 323,
"avg_line_length": 54.765625,
"alnum_prop": 0.7800285306704707,
"repo_name": "microsoftgraph/msgraph-sdk-java",
"id": "1d3eae312565caaa4a6bc2b30eb2d99835612f0d",
"size": "3505",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/main/java/com/microsoft/graph/requests/UnifiedRoleAssignmentScheduleCollectionRequestBuilder.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27286837"
},
{
"name": "PowerShell",
"bytes": "5635"
}
],
"symlink_target": ""
} |
<!-- Copyright (C) 2013-2014 Computer Sciences Corporation
*
* 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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>ezbake.training</groupId>
<artifactId>ezbake-training-pipelines-parent</artifactId>
<version>2.1</version>
</parent>
<artifactId>tweet-word-divide</artifactId>
<dependencies>
<!-- Third-Party dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- EzBake dependencies -->
<dependency>
<groupId>ezbake</groupId>
<artifactId>frack</artifactId>
</dependency>
<dependency>
<groupId>ezbake.data</groupId>
<artifactId>common-utils</artifactId>
</dependency>
<!-- Internal dependencies -->
<dependency>
<groupId>ezbake.training</groupId>
<artifactId>ezbake-training-common-thrift</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>ezbake.training.TweetWordBuilder</mainClass>
</transformer>
</transformers>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "1936f57f085598b27256fe10ea4fbc2c",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 117,
"avg_line_length": 36.794117647058826,
"alnum_prop": 0.6007194244604317,
"repo_name": "infochimps-forks/ezbake-training",
"id": "7b1ecbe64d3407112be1d07acc0ad71c7b4b0f1a",
"size": "2502",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pipelines/tweet-word-divide/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "107169"
},
{
"name": "Thrift",
"bytes": "2492"
}
],
"symlink_target": ""
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/**
* Supported keybindings:
* Too many to list. Refer to defaultKeyMap below.
*
* Supported Ex commands:
* Refer to defaultExCommandMap below.
*
* Registers: unnamed, -, a-z, A-Z, 0-9
* (Does not respect the special case for number registers when delete
* operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
* TODO: Implement the remaining registers.
*
* Marks: a-z, A-Z, and 0-9
* TODO: Implement the remaining special marks. They have more complex
* behavior.
*
* Events:
* 'vim-mode-change' - raised on the editor anytime the current mode changes,
* Event object: {mode: "visual", subMode: "linewise"}
*
* Code structure:
* 1. Default keymap
* 2. Variable declarations and short basic helpers
* 3. Instance (External API) implementation
* 4. Internal state tracking objects (input state, counter) implementation
* and instanstiation
* 5. Key handler (the main command dispatcher) implementation
* 6. Motion, operator, and action implementations
* 7. Helper functions for the key handler, motions, operators, and actions
* 8. Set up Vim to work as a keymap for CodeMirror.
* 9. Ex command implementations.
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
'use strict';
var defaultKeymap = [
// Key to key mapping. This goes first to make it possible to override
// existing mappings.
{ keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
{ keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
{ keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
{ keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
{ keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
{ keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
{ keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
{ keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
{ keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
{ keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
{ keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
{ keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
{ keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
{ keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
{ keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
{ keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
{ keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
{ keys: 's', type: 'keyToKey', toKeys: 'xi', context: 'visual'},
{ keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
{ keys: 'S', type: 'keyToKey', toKeys: 'dcc', context: 'visual' },
{ keys: '<Home>', type: 'keyToKey', toKeys: '0' },
{ keys: '<End>', type: 'keyToKey', toKeys: '$' },
{ keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
{ keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
{ keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
// Motions
{ keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
{ keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
{ keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
{ keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
{ keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
{ keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
{ keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
{ keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
{ keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
{ keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
{ keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
{ keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
{ keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
{ keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
{ keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
{ keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
{ keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
{ keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
{ keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
{ keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
{ keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
{ keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
{ keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
{ keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
{ keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
{ keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
{ keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
{ keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
{ keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
{ keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
{ keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
{ keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
{ keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
{ keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
{ keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
{ keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
{ keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
{ keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
{ keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
{ keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
// the next two aren't motions but must come before more general motion declarations
{ keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
{ keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
{ keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
{ keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
{ keys: '|', type: 'motion', motion: 'moveToColumn'},
{ keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
{ keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
// Operators
{ keys: 'd', type: 'operator', operator: 'delete' },
{ keys: 'y', type: 'operator', operator: 'yank' },
{ keys: 'c', type: 'operator', operator: 'change' },
{ keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
{ keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
{ keys: 'g~', type: 'operator', operator: 'changeCase' },
{ keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
{ keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
{ keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
{ keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
// Operator-Motion dual commands
{ keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
{ keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
{ keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
{ keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
{ keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
{ keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
{ keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
{ keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
// Actions
{ keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
{ keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
{ keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
{ keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
{ keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
{ keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
{ keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
{ keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
{ keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
{ keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
{ keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
{ keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
{ keys: 'v', type: 'action', action: 'toggleVisualMode' },
{ keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
{ keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
{ keys: 'gv', type: 'action', action: 'reselectLastSelection' },
{ keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
{ keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
{ keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
{ keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
{ keys: '@<character>', type: 'action', action: 'replayMacro' },
{ keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
// Handle Replace-mode as a special case of insert mode.
{ keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
{ keys: 'u', type: 'action', action: 'undo', context: 'normal' },
{ keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
{ keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
{ keys: '<C-r>', type: 'action', action: 'redo' },
{ keys: 'm<character>', type: 'action', action: 'setMark' },
{ keys: '"<character>', type: 'action', action: 'setRegister' },
{ keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
{ keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
{ keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
{ keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: '.', type: 'action', action: 'repeatLastEdit' },
{ keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
{ keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
// Text object motions
{ keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
{ keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
{ keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
{ keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
{ keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
{ keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
// Ex command
{ keys: ':', type: 'ex' }
];
/**
* Ex commands
* Care must be taken when adding to the default Ex command map. For any
* pair of commands that have a shared prefix, at least one of their
* shortNames must not match the prefix of the other command.
*/
var defaultExCommandMap = [
{ name: 'colorscheme', shortName: 'colo' },
{ name: 'map' },
{ name: 'imap', shortName: 'im' },
{ name: 'nmap', shortName: 'nm' },
{ name: 'vmap', shortName: 'vm' },
{ name: 'unmap' },
{ name: 'write', shortName: 'w' },
{ name: 'undo', shortName: 'u' },
{ name: 'redo', shortName: 'red' },
{ name: 'set', shortName: 'se' },
{ name: 'set', shortName: 'se' },
{ name: 'setlocal', shortName: 'setl' },
{ name: 'setglobal', shortName: 'setg' },
{ name: 'sort', shortName: 'sor' },
{ name: 'substitute', shortName: 's', possiblyAsync: true },
{ name: 'nohlsearch', shortName: 'noh' },
{ name: 'delmarks', shortName: 'delm' },
{ name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
{ name: 'global', shortName: 'g' }
];
var Pos = CodeMirror.Pos;
var Vim = function() {
function enterVimMode(cm) {
cm.setOption('disableInput', true);
cm.setOption('showCursorWhenSelecting', false);
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
cm.on('cursorActivity', onCursorActivity);
maybeInitVimState(cm);
CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
}
function leaveVimMode(cm) {
cm.setOption('disableInput', false);
cm.off('cursorActivity', onCursorActivity);
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
cm.state.vim = null;
}
function detachVimMap(cm, next) {
if (this == CodeMirror.keyMap.vim)
CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
if (!next || next.attach != attachVimMap)
leaveVimMode(cm, false);
}
function attachVimMap(cm, prev) {
if (this == CodeMirror.keyMap.vim)
CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
if (!prev || prev.attach != attachVimMap)
enterVimMode(cm);
}
// Deprecated, simply setting the keymap works again.
CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
if (val && cm.getOption("keyMap") != "vim")
cm.setOption("keyMap", "vim");
else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
cm.setOption("keyMap", "default");
});
function cmKey(key, cm) {
if (!cm) { return undefined; }
var vimKey = cmKeyToVimKey(key);
if (!vimKey) {
return false;
}
var cmd = CodeMirror.Vim.findKey(cm, vimKey);
if (typeof cmd == 'function') {
CodeMirror.signal(cm, 'vim-keypress', vimKey);
}
return cmd;
}
var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'};
function cmKeyToVimKey(key) {
if (key.charAt(0) == '\'') {
// Keypress character binding of format "'a'"
return key.charAt(1);
}
var pieces = key.split('-');
if (/-$/.test(key)) {
// If the - key was typed, split will result in 2 extra empty strings
// in the array. Replace them with 1 '-'.
pieces.splice(-2, 2, '-');
}
var lastPiece = pieces[pieces.length - 1];
if (pieces.length == 1 && pieces[0].length == 1) {
// No-modifier bindings use literal character bindings above. Skip.
return false;
} else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
// Ignore Shift+char bindings as they should be handled by literal character.
return false;
}
var hasCharacter = false;
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i];
if (piece in modifiers) { pieces[i] = modifiers[piece]; }
else { hasCharacter = true; }
if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
}
if (!hasCharacter) {
// Vim does not support modifier only keys.
return false;
}
// TODO: Current bindings expect the character to be lower case, but
// it looks like vim key notation uses upper case.
if (isUpperCase(lastPiece)) {
pieces[pieces.length - 1] = lastPiece.toLowerCase();
}
return '<' + pieces.join('-') + '>';
}
function getOnPasteFn(cm) {
var vim = cm.state.vim;
if (!vim.onPasteFn) {
vim.onPasteFn = function() {
if (!vim.insertMode) {
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
actions.enterInsertMode(cm, {}, vim);
}
};
}
return vim.onPasteFn;
}
var numberRegex = /[\d]/;
var wordCharTest = [CodeMirror.isWordChar, function(ch) {
return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
}], bigWordCharTest = [function(ch) {
return /\S/.test(ch);
}];
function makeKeyRange(start, size) {
var keys = [];
for (var i = start; i < start + size; i++) {
keys.push(String.fromCharCode(i));
}
return keys;
}
var upperCaseAlphabet = makeKeyRange(65, 26);
var lowerCaseAlphabet = makeKeyRange(97, 26);
var numbers = makeKeyRange(48, 10);
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
function isLine(cm, line) {
return line >= cm.firstLine() && line <= cm.lastLine();
}
function isLowerCase(k) {
return (/^[a-z]$/).test(k);
}
function isMatchableSymbol(k) {
return '()[]{}'.indexOf(k) != -1;
}
function isNumber(k) {
return numberRegex.test(k);
}
function isUpperCase(k) {
return (/^[A-Z]$/).test(k);
}
function isWhiteSpaceString(k) {
return (/^\s*$/).test(k);
}
function inArray(val, arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == val) {
return true;
}
}
return false;
}
var options = {};
function defineOption(name, defaultValue, type, aliases, callback) {
if (defaultValue === undefined && !callback) {
throw Error('defaultValue is required unless callback is provided');
}
if (!type) { type = 'string'; }
options[name] = {
type: type,
defaultValue: defaultValue,
callback: callback
};
if (aliases) {
for (var i = 0; i < aliases.length; i++) {
options[aliases[i]] = options[name];
}
}
if (defaultValue) {
setOption(name, defaultValue);
}
}
function setOption(name, value, cm, cfg) {
var option = options[name];
cfg = cfg || {};
var scope = cfg.scope;
if (!option) {
throw Error('Unknown option: ' + name);
}
if (option.type == 'boolean') {
if (value && value !== true) {
throw Error('Invalid argument: ' + name + '=' + value);
} else if (value !== false) {
// Boolean options are set to true if value is not defined.
value = true;
}
}
if (option.callback) {
if (scope !== 'local') {
option.callback(value, undefined);
}
if (scope !== 'global' && cm) {
option.callback(value, cm);
}
} else {
if (scope !== 'local') {
option.value = option.type == 'boolean' ? !!value : value;
}
if (scope !== 'global' && cm) {
cm.state.vim.options[name] = {value: value};
}
}
}
function getOption(name, cm, cfg) {
var option = options[name];
cfg = cfg || {};
var scope = cfg.scope;
if (!option) {
throw Error('Unknown option: ' + name);
}
if (option.callback) {
var local = cm && option.callback(undefined, cm);
if (scope !== 'global' && local !== undefined) {
return local;
}
if (scope !== 'local') {
return option.callback();
}
return;
} else {
var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
return (local || (scope !== 'local') && option || {}).value;
}
}
defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
// Option is local. Do nothing for global.
if (cm === undefined) {
return;
}
// The 'filetype' option proxies to the CodeMirror 'mode' option.
if (name === undefined) {
var mode = cm.getOption('mode');
return mode == 'null' ? '' : mode;
} else {
var mode = name == '' ? 'null' : name;
cm.setOption('mode', mode);
}
});
var createCircularJumpList = function() {
var size = 100;
var pointer = -1;
var head = 0;
var tail = 0;
var buffer = new Array(size);
function add(cm, oldCur, newCur) {
var current = pointer % size;
var curMark = buffer[current];
function useNextSlot(cursor) {
var next = ++pointer % size;
var trashMark = buffer[next];
if (trashMark) {
trashMark.clear();
}
buffer[next] = cm.setBookmark(cursor);
}
if (curMark) {
var markPos = curMark.find();
// avoid recording redundant cursor position
if (markPos && !cursorEqual(markPos, oldCur)) {
useNextSlot(oldCur);
}
} else {
useNextSlot(oldCur);
}
useNextSlot(newCur);
head = pointer;
tail = pointer - size + 1;
if (tail < 0) {
tail = 0;
}
}
function move(cm, offset) {
pointer += offset;
if (pointer > head) {
pointer = head;
} else if (pointer < tail) {
pointer = tail;
}
var mark = buffer[(size + pointer) % size];
// skip marks that are temporarily removed from text buffer
if (mark && !mark.find()) {
var inc = offset > 0 ? 1 : -1;
var newCur;
var oldCur = cm.getCursor();
do {
pointer += inc;
mark = buffer[(size + pointer) % size];
// skip marks that are the same as current position
if (mark &&
(newCur = mark.find()) &&
!cursorEqual(oldCur, newCur)) {
break;
}
} while (pointer < head && pointer > tail);
}
return mark;
}
return {
cachedCursor: undefined, //used for # and * jumps
add: add,
move: move
};
};
// Returns an object to track the changes associated insert mode. It
// clones the object that is passed in, or creates an empty object one if
// none is provided.
var createInsertModeChanges = function(c) {
if (c) {
// Copy construction
return {
changes: c.changes,
expectCursorActivityForChange: c.expectCursorActivityForChange
};
}
return {
// Change list
changes: [],
// Set to true on change, false on cursorActivity.
expectCursorActivityForChange: false
};
};
function MacroModeState() {
this.latestRegister = undefined;
this.isPlaying = false;
this.isRecording = false;
this.replaySearchQueries = [];
this.onRecordingDone = undefined;
this.lastInsertModeChanges = createInsertModeChanges();
}
MacroModeState.prototype = {
exitMacroRecordMode: function() {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.onRecordingDone) {
macroModeState.onRecordingDone(); // close dialog
}
macroModeState.onRecordingDone = undefined;
macroModeState.isRecording = false;
},
enterMacroRecordMode: function(cm, registerName) {
var register =
vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.clear();
this.latestRegister = registerName;
if (cm.openDialog) {
this.onRecordingDone = cm.openDialog(
'(recording)['+registerName+']', null, {bottom:true});
}
this.isRecording = true;
}
}
};
function maybeInitVimState(cm) {
if (!cm.state.vim) {
// Store instance state in the CodeMirror object.
cm.state.vim = {
inputState: new InputState(),
// Vim's input state that triggered the last edit, used to repeat
// motions and operators with '.'.
lastEditInputState: undefined,
// Vim's action command before the last edit, used to repeat actions
// with '.' and insert mode repeat.
lastEditActionCommand: undefined,
// When using jk for navigation, if you move from a longer line to a
// shorter line, the cursor may clip to the end of the shorter line.
// If j is pressed again and cursor goes to the next line, the
// cursor should go back to its horizontal position on the longer
// line if it can. This is to keep track of the horizontal position.
lastHPos: -1,
// Doing the same with screen-position for gj/gk
lastHSPos: -1,
// The last motion command run. Cleared if a non-motion command gets
// executed in between.
lastMotion: null,
marks: {},
// Mark for rendering fake cursor for visual mode.
fakeCursor: null,
insertMode: false,
// Repeat count for changes made in insert mode, triggered by key
// sequences like 3,i. Only exists when insertMode is true.
insertModeRepeat: undefined,
visualMode: false,
// If we are in visual line mode. No effect if visualMode is false.
visualLine: false,
visualBlock: false,
lastSelection: null,
lastPastedText: null,
sel: {},
// Buffer-local/window-local values of vim options.
options: {}
};
}
return cm.state.vim;
}
var vimGlobalState;
function resetVimGlobalState() {
vimGlobalState = {
// The current search query.
searchQuery: null,
// Whether we are searching backwards.
searchIsReversed: false,
// Replace part of the last substituted pattern
lastSubstituteReplacePart: undefined,
jumpList: createCircularJumpList(),
macroModeState: new MacroModeState,
// Recording latest f, t, F or T motion command.
lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
registerController: new RegisterController({}),
// search history buffer
searchHistoryController: new HistoryController({}),
// ex Command history buffer
exCommandHistoryController : new HistoryController({})
};
for (var optionName in options) {
var option = options[optionName];
option.value = option.defaultValue;
}
}
var lastInsertModeKeyTimer;
var vimApi= {
buildKeyMap: function() {
// TODO: Convert keymap into dictionary format for fast lookup.
},
// Testing hook, though it might be useful to expose the register
// controller anyways.
getRegisterController: function() {
return vimGlobalState.registerController;
},
// Testing hook.
resetVimGlobalState_: resetVimGlobalState,
// Testing hook.
getVimGlobalState_: function() {
return vimGlobalState;
},
// Testing hook.
maybeInitVimState_: maybeInitVimState,
suppressErrorLogging: false,
InsertModeKey: InsertModeKey,
map: function(lhs, rhs, ctx) {
// Add user defined key bindings.
exCommandDispatcher.map(lhs, rhs, ctx);
},
// TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
// them, or somehow make them work with the existing CodeMirror setOption/getOption API.
setOption: setOption,
getOption: getOption,
defineOption: defineOption,
defineEx: function(name, prefix, func){
if (!prefix) {
prefix = name;
} else if (name.indexOf(prefix) !== 0) {
throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
}
exCommands[name]=func;
exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
},
handleKey: function (cm, key, origin) {
var command = this.findKey(cm, key, origin);
if (typeof command === 'function') {
return command();
}
},
/**
* This is the outermost function called by CodeMirror, after keys have
* been mapped to their Vim equivalents.
*
* Finds a command based on the key (and cached keys if there is a
* multi-key sequence). Returns `undefined` if no key is matched, a noop
* function if a partial match is found (multi-key), and a function to
* execute the bound command if a a key is matched. The function always
* returns true.
*/
findKey: function(cm, key, origin) {
var vim = maybeInitVimState(cm);
function handleMacroRecording() {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
if (key == 'q') {
macroModeState.exitMacroRecordMode();
clearInputState(cm);
return true;
}
if (origin != 'mapping') {
logKey(macroModeState, key);
}
}
}
function handleEsc() {
if (key == '<Esc>') {
// Clear input state and get back to normal mode.
clearInputState(cm);
if (vim.visualMode) {
exitVisualMode(cm);
} else if (vim.insertMode) {
exitInsertMode(cm);
}
return true;
}
}
function doKeyToKey(keys) {
// TODO: prevent infinite recursion.
var match;
while (keys) {
// Pull off one command key, which is either a single character
// or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
match = (/<\w+-.+?>|<\w+>|./).exec(keys);
key = match[0];
keys = keys.substring(match.index + key.length);
CodeMirror.Vim.handleKey(cm, key, 'mapping');
}
}
function handleKeyInsertMode() {
if (handleEsc()) { return true; }
var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
var keysAreChars = key.length == 1;
var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
// Need to check all key substrings in insert mode.
while (keys.length > 1 && match.type != 'full') {
var keys = vim.inputState.keyBuffer = keys.slice(1);
var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
if (thisMatch.type != 'none') { match = thisMatch; }
}
if (match.type == 'none') { clearInputState(cm); return false; }
else if (match.type == 'partial') {
if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
lastInsertModeKeyTimer = window.setTimeout(
function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
getOption('insertModeEscKeysTimeout'));
return !keysAreChars;
}
if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
if (keysAreChars) {
var here = cm.getCursor();
cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
}
clearInputState(cm);
return match.command;
}
function handleKeyNonInsertMode() {
if (handleMacroRecording() || handleEsc()) { return true; };
var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
if (/^[1-9]\d*$/.test(keys)) { return true; }
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
if (!keysMatcher) { clearInputState(cm); return false; }
var context = vim.visualMode ? 'visual' :
'normal';
var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
if (match.type == 'none') { clearInputState(cm); return false; }
else if (match.type == 'partial') { return true; }
vim.inputState.keyBuffer = '';
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
if (keysMatcher[1] && keysMatcher[1] != '0') {
vim.inputState.pushRepeatDigit(keysMatcher[1]);
}
return match.command;
}
var command;
if (vim.insertMode) { command = handleKeyInsertMode(); }
else { command = handleKeyNonInsertMode(); }
if (command === false) {
return undefined;
} else if (command === true) {
// TODO: Look into using CodeMirror's multi-key handling.
// Return no-op since we are caching the key. Counts as handled, but
// don't want act on it just yet.
return function() {};
} else {
return function() {
return cm.operation(function() {
cm.curOp.isVimOp = true;
try {
if (command.type == 'keyToKey') {
doKeyToKey(command.toKeys);
} else {
commandDispatcher.processCommand(cm, vim, command);
}
} catch (e) {
// clear VIM state in case it's in a bad state.
cm.state.vim = undefined;
maybeInitVimState(cm);
if (!CodeMirror.Vim.suppressErrorLogging) {
console['log'](e);
}
throw e;
}
return true;
});
};
}
},
handleEx: function(cm, input) {
exCommandDispatcher.processCommand(cm, input);
},
defineMotion: defineMotion,
defineAction: defineAction,
defineOperator: defineOperator,
mapCommand: mapCommand,
_mapCommand: _mapCommand,
defineRegister: defineRegister,
exitVisualMode: exitVisualMode,
exitInsertMode: exitInsertMode
};
// Represents the current input state.
function InputState() {
this.prefixRepeat = [];
this.motionRepeat = [];
this.operator = null;
this.operatorArgs = null;
this.motion = null;
this.motionArgs = null;
this.keyBuffer = []; // For matching multi-key commands.
this.registerName = null; // Defaults to the unnamed register.
}
InputState.prototype.pushRepeatDigit = function(n) {
if (!this.operator) {
this.prefixRepeat = this.prefixRepeat.concat(n);
} else {
this.motionRepeat = this.motionRepeat.concat(n);
}
};
InputState.prototype.getRepeat = function() {
var repeat = 0;
if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
repeat = 1;
if (this.prefixRepeat.length > 0) {
repeat *= parseInt(this.prefixRepeat.join(''), 10);
}
if (this.motionRepeat.length > 0) {
repeat *= parseInt(this.motionRepeat.join(''), 10);
}
}
return repeat;
};
function clearInputState(cm, reason) {
cm.state.vim.inputState = new InputState();
CodeMirror.signal(cm, 'vim-command-done', reason);
}
/*
* Register stores information about copy and paste registers. Besides
* text, a register must store whether it is linewise (i.e., when it is
* pasted, should it insert itself into a new line, or should the text be
* inserted at the cursor position.)
*/
function Register(text, linewise, blockwise) {
this.clear();
this.keyBuffer = [text || ''];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = !!linewise;
this.blockwise = !!blockwise;
}
Register.prototype = {
setText: function(text, linewise, blockwise) {
this.keyBuffer = [text || ''];
this.linewise = !!linewise;
this.blockwise = !!blockwise;
},
pushText: function(text, linewise) {
// if this register has ever been set to linewise, use linewise.
if (linewise) {
if (!this.linewise) {
this.keyBuffer.push('\n');
}
this.linewise = true;
}
this.keyBuffer.push(text);
},
pushInsertModeChanges: function(changes) {
this.insertModeChanges.push(createInsertModeChanges(changes));
},
pushSearchQuery: function(query) {
this.searchQueries.push(query);
},
clear: function() {
this.keyBuffer = [];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = false;
},
toString: function() {
return this.keyBuffer.join('');
}
};
/**
* Defines an external register.
*
* The name should be a single character that will be used to reference the register.
* The register should support setText, pushText, clear, and toString(). See Register
* for a reference implementation.
*/
function defineRegister(name, register) {
var registers = vimGlobalState.registerController.registers[name];
if (!name || name.length != 1) {
throw Error('Register name must be 1 character');
}
if (registers[name]) {
throw Error('Register already defined ' + name);
}
registers[name] = register;
validRegisters.push(name);
}
/*
* vim registers allow you to keep many independent copy and paste buffers.
* See http://usevim.com/2012/04/13/registers/ for an introduction.
*
* RegisterController keeps the state of all the registers. An initial
* state may be passed in. The unnamed register '"' will always be
* overridden.
*/
function RegisterController(registers) {
this.registers = registers;
this.unnamedRegister = registers['"'] = new Register();
registers['.'] = new Register();
registers[':'] = new Register();
registers['/'] = new Register();
}
RegisterController.prototype = {
pushText: function(registerName, operator, text, linewise, blockwise) {
if (linewise && text.charAt(0) == '\n') {
text = text.slice(1) + '\n';
}
if (linewise && text.charAt(text.length - 1) !== '\n'){
text += '\n';
}
// Lowercase and uppercase registers refer to the same register.
// Uppercase just means append.
var register = this.isValidRegister(registerName) ?
this.getRegister(registerName) : null;
// if no register/an invalid register was specified, things go to the
// default registers
if (!register) {
switch (operator) {
case 'yank':
// The 0 register contains the text from the most recent yank.
this.registers['0'] = new Register(text, linewise, blockwise);
break;
case 'delete':
case 'change':
if (text.indexOf('\n') == -1) {
// Delete less than 1 line. Update the small delete register.
this.registers['-'] = new Register(text, linewise);
} else {
// Shift down the contents of the numbered registers and put the
// deleted text into register 1.
this.shiftNumericRegisters_();
this.registers['1'] = new Register(text, linewise);
}
break;
}
// Make sure the unnamed register is set to what just happened
this.unnamedRegister.setText(text, linewise, blockwise);
return;
}
// If we've gotten to this point, we've actually specified a register
var append = isUpperCase(registerName);
if (append) {
register.pushText(text, linewise);
} else {
register.setText(text, linewise, blockwise);
}
// The unnamed register always has the same value as the last used
// register.
this.unnamedRegister.setText(register.toString(), linewise);
},
// Gets the register named @name. If one of @name doesn't already exist,
// create it. If @name is invalid, return the unnamedRegister.
getRegister: function(name) {
if (!this.isValidRegister(name)) {
return this.unnamedRegister;
}
name = name.toLowerCase();
if (!this.registers[name]) {
this.registers[name] = new Register();
}
return this.registers[name];
},
isValidRegister: function(name) {
return name && inArray(name, validRegisters);
},
shiftNumericRegisters_: function() {
for (var i = 9; i >= 2; i--) {
this.registers[i] = this.getRegister('' + (i - 1));
}
}
};
function HistoryController() {
this.historyBuffer = [];
this.iterator;
this.initialPrefix = null;
}
HistoryController.prototype = {
// the input argument here acts a user entered prefix for a small time
// until we start autocompletion in which case it is the autocompleted.
nextMatch: function (input, up) {
var historyBuffer = this.historyBuffer;
var dir = up ? -1 : 1;
if (this.initialPrefix === null) this.initialPrefix = input;
for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
var element = historyBuffer[i];
for (var j = 0; j <= element.length; j++) {
if (this.initialPrefix == element.substring(0, j)) {
this.iterator = i;
return element;
}
}
}
// should return the user input in case we reach the end of buffer.
if (i >= historyBuffer.length) {
this.iterator = historyBuffer.length;
return this.initialPrefix;
}
// return the last autocompleted query or exCommand as it is.
if (i < 0 ) return input;
},
pushInput: function(input) {
var index = this.historyBuffer.indexOf(input);
if (index > -1) this.historyBuffer.splice(index, 1);
if (input.length) this.historyBuffer.push(input);
},
reset: function() {
this.initialPrefix = null;
this.iterator = this.historyBuffer.length;
}
};
var commandDispatcher = {
matchCommand: function(keys, keyMap, inputState, context) {
var matches = commandMatches(keys, keyMap, context, inputState);
if (!matches.full && !matches.partial) {
return {type: 'none'};
} else if (!matches.full && matches.partial) {
return {type: 'partial'};
}
var bestMatch;
for (var i = 0; i < matches.full.length; i++) {
var match = matches.full[i];
if (!bestMatch) {
bestMatch = match;
}
}
if (bestMatch.keys.slice(-11) == '<character>') {
inputState.selectedCharacter = lastChar(keys);
}
return {type: 'full', command: bestMatch};
},
processCommand: function(cm, vim, command) {
vim.inputState.repeatOverride = command.repeatOverride;
switch (command.type) {
case 'motion':
this.processMotion(cm, vim, command);
break;
case 'operator':
this.processOperator(cm, vim, command);
break;
case 'operatorMotion':
this.processOperatorMotion(cm, vim, command);
break;
case 'action':
this.processAction(cm, vim, command);
break;
case 'search':
this.processSearch(cm, vim, command);
break;
case 'ex':
case 'keyToEx':
this.processEx(cm, vim, command);
break;
default:
break;
}
},
processMotion: function(cm, vim, command) {
vim.inputState.motion = command.motion;
vim.inputState.motionArgs = copyArgs(command.motionArgs);
this.evalInput(cm, vim);
},
processOperator: function(cm, vim, command) {
var inputState = vim.inputState;
if (inputState.operator) {
if (inputState.operator == command.operator) {
// Typing an operator twice like 'dd' makes the operator operate
// linewise
inputState.motion = 'expandToLine';
inputState.motionArgs = { linewise: true };
this.evalInput(cm, vim);
return;
} else {
// 2 different operators in a row doesn't make sense.
clearInputState(cm);
}
}
inputState.operator = command.operator;
inputState.operatorArgs = copyArgs(command.operatorArgs);
if (vim.visualMode) {
// Operating on a selection in visual mode. We don't need a motion.
this.evalInput(cm, vim);
}
},
processOperatorMotion: function(cm, vim, command) {
var visualMode = vim.visualMode;
var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
if (operatorMotionArgs) {
// Operator motions may have special behavior in visual mode.
if (visualMode && operatorMotionArgs.visualLine) {
vim.visualLine = true;
}
}
this.processOperator(cm, vim, command);
if (!visualMode) {
this.processMotion(cm, vim, command);
}
},
processAction: function(cm, vim, command) {
var inputState = vim.inputState;
var repeat = inputState.getRepeat();
var repeatIsExplicit = !!repeat;
var actionArgs = copyArgs(command.actionArgs) || {};
if (inputState.selectedCharacter) {
actionArgs.selectedCharacter = inputState.selectedCharacter;
}
// Actions may or may not have motions and operators. Do these first.
if (command.operator) {
this.processOperator(cm, vim, command);
}
if (command.motion) {
this.processMotion(cm, vim, command);
}
if (command.motion || command.operator) {
this.evalInput(cm, vim);
}
actionArgs.repeat = repeat || 1;
actionArgs.repeatIsExplicit = repeatIsExplicit;
actionArgs.registerName = inputState.registerName;
clearInputState(cm);
vim.lastMotion = null;
if (command.isEdit) {
this.recordLastEdit(vim, inputState, command);
}
actions[command.action](cm, actionArgs, vim);
},
processSearch: function(cm, vim, command) {
if (!cm.getSearchCursor) {
// Search depends on SearchCursor.
return;
}
var forward = command.searchArgs.forward;
var wholeWordOnly = command.searchArgs.wholeWordOnly;
getSearchState(cm).setReversed(!forward);
var promptPrefix = (forward) ? '/' : '?';
var originalQuery = getSearchState(cm).getQuery();
var originalScrollPos = cm.getScrollInfo();
function handleQuery(query, ignoreCase, smartCase) {
vimGlobalState.searchHistoryController.pushInput(query);
vimGlobalState.searchHistoryController.reset();
try {
updateSearchQuery(cm, query, ignoreCase, smartCase);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + query);
clearInputState(cm);
return;
}
commandDispatcher.processMotion(cm, vim, {
type: 'motion',
motion: 'findNext',
motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
});
}
function onPromptClose(query) {
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
handleQuery(query, true /** ignoreCase */, true /** smartCase */);
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
logSearchQuery(macroModeState, query);
}
}
function onPromptKeyUp(e, query, close) {
var keyName = CodeMirror.keyName(e), up;
if (keyName == 'Up' || keyName == 'Down') {
up = keyName == 'Up' ? true : false;
query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
close(query);
} else {
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
vimGlobalState.searchHistoryController.reset();
}
var parsedQuery;
try {
parsedQuery = updateSearchQuery(cm, query,
true /** ignoreCase */, true /** smartCase */);
} catch (e) {
// Swallow bad regexes for incremental search.
}
if (parsedQuery) {
cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
} else {
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
}
}
function onPromptKeyDown(e, query, close) {
var keyName = CodeMirror.keyName(e);
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
(keyName == 'Backspace' && query == '')) {
vimGlobalState.searchHistoryController.pushInput(query);
vimGlobalState.searchHistoryController.reset();
updateSearchQuery(cm, originalQuery);
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
CodeMirror.e_stop(e);
clearInputState(cm);
close();
cm.focus();
} else if (keyName == 'Ctrl-U') {
// Ctrl-U clears input.
CodeMirror.e_stop(e);
close('');
}
}
switch (command.searchArgs.querySrc) {
case 'prompt':
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) {
var query = macroModeState.replaySearchQueries.shift();
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
} else {
showPrompt(cm, {
onClose: onPromptClose,
prefix: promptPrefix,
desc: searchPromptDesc,
onKeyUp: onPromptKeyUp,
onKeyDown: onPromptKeyDown
});
}
break;
case 'wordUnderCursor':
var word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
true /** noSymbol */);
var isKeyword = true;
if (!word) {
word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
false /** noSymbol */);
isKeyword = false;
}
if (!word) {
return;
}
var query = cm.getLine(word.start.line).substring(word.start.ch,
word.end.ch);
if (isKeyword && wholeWordOnly) {
query = '\\b' + query + '\\b';
} else {
query = escapeRegex(query);
}
// cachedCursor is used to save the old position of the cursor
// when * or # causes vim to seek for the nearest word and shift
// the cursor before entering the motion.
vimGlobalState.jumpList.cachedCursor = cm.getCursor();
cm.setCursor(word.start);
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
break;
}
},
processEx: function(cm, vim, command) {
function onPromptClose(input) {
// Give the prompt some time to close so that if processCommand shows
// an error, the elements don't overlap.
vimGlobalState.exCommandHistoryController.pushInput(input);
vimGlobalState.exCommandHistoryController.reset();
exCommandDispatcher.processCommand(cm, input);
}
function onPromptKeyDown(e, input, close) {
var keyName = CodeMirror.keyName(e), up;
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
(keyName == 'Backspace' && input == '')) {
vimGlobalState.exCommandHistoryController.pushInput(input);
vimGlobalState.exCommandHistoryController.reset();
CodeMirror.e_stop(e);
clearInputState(cm);
close();
cm.focus();
}
if (keyName == 'Up' || keyName == 'Down') {
up = keyName == 'Up' ? true : false;
input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
close(input);
} else if (keyName == 'Ctrl-U') {
// Ctrl-U clears input.
CodeMirror.e_stop(e);
close('');
} else {
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
vimGlobalState.exCommandHistoryController.reset();
}
}
if (command.type == 'keyToEx') {
// Handle user defined Ex to Ex mappings
exCommandDispatcher.processCommand(cm, command.exArgs.input);
} else {
if (vim.visualMode) {
showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
onKeyDown: onPromptKeyDown});
} else {
showPrompt(cm, { onClose: onPromptClose, prefix: ':',
onKeyDown: onPromptKeyDown});
}
}
},
evalInput: function(cm, vim) {
// If the motion comand is set, execute both the operator and motion.
// Otherwise return.
var inputState = vim.inputState;
var motion = inputState.motion;
var motionArgs = inputState.motionArgs || {};
var operator = inputState.operator;
var operatorArgs = inputState.operatorArgs || {};
var registerName = inputState.registerName;
var sel = vim.sel;
// TODO: Make sure cm and vim selections are identical outside visual mode.
var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
var oldHead = copyCursor(origHead);
var oldAnchor = copyCursor(origAnchor);
var newHead, newAnchor;
var repeat;
if (operator) {
this.recordLastEdit(vim, inputState);
}
if (inputState.repeatOverride !== undefined) {
// If repeatOverride is specified, that takes precedence over the
// input state's repeat. Used by Ex mode and can be user defined.
repeat = inputState.repeatOverride;
} else {
repeat = inputState.getRepeat();
}
if (repeat > 0 && motionArgs.explicitRepeat) {
motionArgs.repeatIsExplicit = true;
} else if (motionArgs.noRepeat ||
(!motionArgs.explicitRepeat && repeat === 0)) {
repeat = 1;
motionArgs.repeatIsExplicit = false;
}
if (inputState.selectedCharacter) {
// If there is a character input, stick it in all of the arg arrays.
motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
inputState.selectedCharacter;
}
motionArgs.repeat = repeat;
clearInputState(cm);
if (motion) {
var motionResult = motions[motion](cm, origHead, motionArgs, vim);
vim.lastMotion = motions[motion];
if (!motionResult) {
return;
}
if (motionArgs.toJumplist) {
var jumpList = vimGlobalState.jumpList;
// if the current motion is # or *, use cachedCursor
var cachedCursor = jumpList.cachedCursor;
if (cachedCursor) {
recordJumpPosition(cm, cachedCursor, motionResult);
delete jumpList.cachedCursor;
} else {
recordJumpPosition(cm, origHead, motionResult);
}
}
if (motionResult instanceof Array) {
newAnchor = motionResult[0];
newHead = motionResult[1];
} else {
newHead = motionResult;
}
// TODO: Handle null returns from motion commands better.
if (!newHead) {
newHead = copyCursor(origHead);
}
if (vim.visualMode) {
if (!(vim.visualBlock && newHead.ch === Infinity)) {
newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
}
if (newAnchor) {
newAnchor = clipCursorToContent(cm, newAnchor, true);
}
newAnchor = newAnchor || oldAnchor;
sel.anchor = newAnchor;
sel.head = newHead;
updateCmSelection(cm);
updateMark(cm, vim, '<',
cursorIsBefore(newAnchor, newHead) ? newAnchor
: newHead);
updateMark(cm, vim, '>',
cursorIsBefore(newAnchor, newHead) ? newHead
: newAnchor);
} else if (!operator) {
newHead = clipCursorToContent(cm, newHead);
cm.setCursor(newHead.line, newHead.ch);
}
}
if (operator) {
if (operatorArgs.lastSel) {
// Replaying a visual mode operation
newAnchor = oldAnchor;
var lastSel = operatorArgs.lastSel;
var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
if (lastSel.visualLine) {
// Linewise Visual mode: The same number of lines.
newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
} else if (lastSel.visualBlock) {
// Blockwise Visual mode: The same number of lines and columns.
newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
} else if (lastSel.head.line == lastSel.anchor.line) {
// Normal Visual mode within one line: The same number of characters.
newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
} else {
// Normal Visual mode with several lines: The same number of lines, in the
// last line the same number of characters as in the last line the last time.
newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
}
vim.visualMode = true;
vim.visualLine = lastSel.visualLine;
vim.visualBlock = lastSel.visualBlock;
sel = vim.sel = {
anchor: newAnchor,
head: newHead
};
updateCmSelection(cm);
} else if (vim.visualMode) {
operatorArgs.lastSel = {
anchor: copyCursor(sel.anchor),
head: copyCursor(sel.head),
visualBlock: vim.visualBlock,
visualLine: vim.visualLine
};
}
var curStart, curEnd, linewise, mode;
var cmSel;
if (vim.visualMode) {
// Init visual op
curStart = cursorMin(sel.head, sel.anchor);
curEnd = cursorMax(sel.head, sel.anchor);
linewise = vim.visualLine || operatorArgs.linewise;
mode = vim.visualBlock ? 'block' :
linewise ? 'line' :
'char';
cmSel = makeCmSelection(cm, {
anchor: curStart,
head: curEnd
}, mode);
if (linewise) {
var ranges = cmSel.ranges;
if (mode == 'block') {
// Linewise operators in visual block mode extend to end of line
for (var i = 0; i < ranges.length; i++) {
ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
}
} else if (mode == 'line') {
ranges[0].head = Pos(ranges[0].head.line + 1, 0);
}
}
} else {
// Init motion op
curStart = copyCursor(newAnchor || oldAnchor);
curEnd = copyCursor(newHead || oldHead);
if (cursorIsBefore(curEnd, curStart)) {
var tmp = curStart;
curStart = curEnd;
curEnd = tmp;
}
linewise = motionArgs.linewise || operatorArgs.linewise;
if (linewise) {
// Expand selection to entire line.
expandSelectionToLine(cm, curStart, curEnd);
} else if (motionArgs.forward) {
// Clip to trailing newlines only if the motion goes forward.
clipToLine(cm, curStart, curEnd);
}
mode = 'char';
var exclusive = !motionArgs.inclusive || linewise;
cmSel = makeCmSelection(cm, {
anchor: curStart,
head: curEnd
}, mode, exclusive);
}
cm.setSelections(cmSel.ranges, cmSel.primary);
vim.lastMotion = null;
operatorArgs.repeat = repeat; // For indent in visual mode.
operatorArgs.registerName = registerName;
// Keep track of linewise as it affects how paste and change behave.
operatorArgs.linewise = linewise;
var operatorMoveTo = operators[operator](
cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
if (vim.visualMode) {
exitVisualMode(cm, operatorMoveTo != null);
}
if (operatorMoveTo) {
cm.setCursor(operatorMoveTo);
}
}
},
recordLastEdit: function(vim, inputState, actionCommand) {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
vim.lastEditInputState = inputState;
vim.lastEditActionCommand = actionCommand;
macroModeState.lastInsertModeChanges.changes = [];
macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
}
};
/**
* typedef {Object{line:number,ch:number}} Cursor An object containing the
* position of the cursor.
*/
// All of the functions below return Cursor objects.
var motions = {
moveToTopLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToMiddleLine: function(cm) {
var range = getUserVisibleLines(cm);
var line = Math.floor((range.top + range.bottom) * 0.5);
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToBottomLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
expandToLine: function(_cm, head, motionArgs) {
// Expands forward to end of line, and then to next line if repeat is
// >1. Does not handle backward motion!
var cur = head;
return Pos(cur.line + motionArgs.repeat - 1, Infinity);
},
findNext: function(cm, _head, motionArgs) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
return;
}
var prev = !motionArgs.forward;
// If search is initiated with ? instead of /, negate direction.
prev = (state.isReversed()) ? !prev : prev;
highlightSearchMatches(cm, query);
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
},
goToMark: function(cm, _head, motionArgs, vim) {
var mark = vim.marks[motionArgs.selectedCharacter];
if (mark) {
var pos = mark.find();
return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
}
return null;
},
moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
if (vim.visualBlock && motionArgs.sameLine) {
var sel = vim.sel;
return [
clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
];
} else {
return ([vim.sel.head, vim.sel.anchor]);
}
},
jumpToMark: function(cm, head, motionArgs, vim) {
var best = head;
for (var i = 0; i < motionArgs.repeat; i++) {
var cursor = best;
for (var key in vim.marks) {
if (!isLowerCase(key)) {
continue;
}
var mark = vim.marks[key].find();
var isWrongDirection = (motionArgs.forward) ?
cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
if (isWrongDirection) {
continue;
}
if (motionArgs.linewise && (mark.line == cursor.line)) {
continue;
}
var equal = cursorEqual(cursor, best);
var between = (motionArgs.forward) ?
cursorIsBetween(cursor, mark, best) :
cursorIsBetween(best, mark, cursor);
if (equal || between) {
best = mark;
}
}
}
if (motionArgs.linewise) {
// Vim places the cursor on the first non-whitespace character of
// the line if there is one, else it places the cursor at the end
// of the line, regardless of whether a mark was found.
best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
}
return best;
},
moveByCharacters: function(_cm, head, motionArgs) {
var cur = head;
var repeat = motionArgs.repeat;
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
return Pos(cur.line, ch);
},
moveByLines: function(cm, head, motionArgs, vim) {
var cur = head;
var endCh = cur.ch;
// Depending what our last motion was, we may want to do different
// things. If our last motion was moving vertically, we want to
// preserve the HPos from our last horizontal move. If our last motion
// was going to the end of a line, moving vertically we should go to
// the end of the line, etc.
switch (vim.lastMotion) {
case this.moveByLines:
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveToColumn:
case this.moveToEol:
endCh = vim.lastHPos;
break;
default:
vim.lastHPos = endCh;
}
var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
var first = cm.firstLine();
var last = cm.lastLine();
// Vim cancels linewise motions that start on an edge and move beyond
// that edge. It does not cancel motions that do not start on an edge.
if ((line < first && cur.line == first) ||
(line > last && cur.line == last)) {
return;
}
if (motionArgs.toFirstChar){
endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
vim.lastHPos = endCh;
}
vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
return Pos(line, endCh);
},
moveByDisplayLines: function(cm, head, motionArgs, vim) {
var cur = head;
switch (vim.lastMotion) {
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveByLines:
case this.moveToColumn:
case this.moveToEol:
break;
default:
vim.lastHSPos = cm.charCoords(cur,'div').left;
}
var repeat = motionArgs.repeat;
var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
if (res.hitSide) {
if (motionArgs.forward) {
var lastCharCoords = cm.charCoords(res, 'div');
var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
var res = cm.coordsChar(goalCoords, 'div');
} else {
var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
resCoords.left = vim.lastHSPos;
res = cm.coordsChar(resCoords, 'div');
}
}
vim.lastHPos = res.ch;
return res;
},
moveByPage: function(cm, head, motionArgs) {
// CodeMirror only exposes functions that move the cursor page down, so
// doing this bad hack to move the cursor and move it back. evalInput
// will move the cursor to where it should be in the end.
var curStart = head;
var repeat = motionArgs.repeat;
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
},
moveByParagraph: function(cm, head, motionArgs) {
var dir = motionArgs.forward ? 1 : -1;
return findParagraph(cm, head, motionArgs.repeat, dir);
},
moveByScroll: function(cm, head, motionArgs, vim) {
var scrollbox = cm.getScrollInfo();
var curEnd = null;
var repeat = motionArgs.repeat;
if (!repeat) {
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
}
var orig = cm.charCoords(head, 'local');
motionArgs.repeat = repeat;
var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
if (!curEnd) {
return null;
}
var dest = cm.charCoords(curEnd, 'local');
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
return curEnd;
},
moveByWords: function(cm, head, motionArgs) {
return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
!!motionArgs.wordEnd, !!motionArgs.bigWord);
},
moveTillCharacter: function(cm, _head, motionArgs) {
var repeat = motionArgs.repeat;
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter);
var increment = motionArgs.forward ? -1 : 1;
recordLastCharacterSearch(increment, motionArgs);
if (!curEnd) return null;
curEnd.ch += increment;
return curEnd;
},
moveToCharacter: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
recordLastCharacterSearch(0, motionArgs);
return moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || head;
},
moveToSymbol: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
return findSymbol(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || head;
},
moveToColumn: function(cm, head, motionArgs, vim) {
var repeat = motionArgs.repeat;
// repeat is equivalent to which column we want to move to!
vim.lastHPos = repeat - 1;
vim.lastHSPos = cm.charCoords(head,'div').left;
return moveToColumn(cm, repeat);
},
moveToEol: function(cm, head, motionArgs, vim) {
var cur = head;
vim.lastHPos = Infinity;
var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
var end=cm.clipPos(retval);
end.ch--;
vim.lastHSPos = cm.charCoords(end,'div').left;
return retval;
},
moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
// Go to the start of the line where the text begins, or the end for
// whitespace-only lines
var cursor = head;
return Pos(cursor.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
},
moveToMatchedSymbol: function(cm, head) {
var cursor = head;
var line = cursor.line;
var ch = cursor.ch;
var lineText = cm.getLine(line);
var symbol;
do {
symbol = lineText.charAt(ch++);
if (symbol && isMatchableSymbol(symbol)) {
var style = cm.getTokenTypeAt(Pos(line, ch));
if (style !== "string" && style !== "comment") {
break;
}
}
} while (symbol);
if (symbol) {
var matched = cm.findMatchingBracket(Pos(line, ch));
return matched.to;
} else {
return cursor;
}
},
moveToStartOfLine: function(_cm, head) {
return Pos(head.line, 0);
},
moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
if (motionArgs.repeatIsExplicit) {
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
}
return Pos(lineNum,
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
},
textObjectManipulation: function(cm, head, motionArgs, vim) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
// TODO: adding <> >< to this map doesn't work, presumably because
// they're operators
var mirroredPairs = {'(': ')', ')': '(',
'{': '}', '}': '{',
'[': ']', ']': '['};
var selfPaired = {'\'': true, '"': true};
var character = motionArgs.selectedCharacter;
// 'b' refers to '()' block.
// 'B' refers to '{}' block.
if (character == 'b') {
character = '(';
} else if (character == 'B') {
character = '{';
}
// Inclusive is the difference between a and i
// TODO: Instead of using the additional text object map to perform text
// object operations, merge the map into the defaultKeyMap and use
// motionArgs to define behavior. Define separate entries for 'aw',
// 'iw', 'a[', 'i[', etc.
var inclusive = !motionArgs.textObjectInner;
var tmp;
if (mirroredPairs[character]) {
tmp = selectCompanionObject(cm, head, character, inclusive);
} else if (selfPaired[character]) {
tmp = findBeginningAndEnd(cm, head, character, inclusive);
} else if (character === 'W') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
true /** bigWord */);
} else if (character === 'w') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
false /** bigWord */);
} else if (character === 'p') {
tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
motionArgs.linewise = true;
if (vim.visualMode) {
if (!vim.visualLine) { vim.visualLine = true; }
} else {
var operatorArgs = vim.inputState.operatorArgs;
if (operatorArgs) { operatorArgs.linewise = true; }
tmp.end.line--;
}
} else {
// No text object defined for this, don't move.
return null;
}
if (!cm.state.vim.visualMode) {
return [tmp.start, tmp.end];
} else {
return expandSelection(cm, tmp.start, tmp.end);
}
},
repeatLastCharacterSearch: function(cm, head, motionArgs) {
var lastSearch = vimGlobalState.lastChararacterSearch;
var repeat = motionArgs.repeat;
var forward = motionArgs.forward === lastSearch.forward;
var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
cm.moveH(-increment, 'char');
motionArgs.inclusive = forward ? true : false;
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
if (!curEnd) {
cm.moveH(increment, 'char');
return head;
}
curEnd.ch += increment;
return curEnd;
}
};
function defineMotion(name, fn) {
motions[name] = fn;
}
function fillArray(val, times) {
var arr = [];
for (var i = 0; i < times; i++) {
arr.push(val);
}
return arr;
}
/**
* An operator acts on a text selection. It receives the list of selections
* as input. The corresponding CodeMirror selection is guaranteed to
* match the input selection.
*/
var operators = {
change: function(cm, args, ranges) {
var finalHead, text;
var vim = cm.state.vim;
vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
if (!vim.visualMode) {
var anchor = ranges[0].anchor,
head = ranges[0].head;
text = cm.getRange(anchor, head);
var lastState = vim.lastEditInputState || {};
if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
// Exclude trailing whitespace if the range is not all whitespace.
var match = (/\s+$/).exec(text);
if (match && lastState.motionArgs && lastState.motionArgs.forward) {
head = offsetCursor(head, 0, - match[0].length);
text = text.slice(0, - match[0].length);
}
}
var wasLastLine = head.line - 1 == cm.lastLine();
cm.replaceRange('', anchor, head);
if (args.linewise && !wasLastLine) {
// Push the next line back down, if there is a next line.
CodeMirror.commands.newlineAndIndent(cm);
// null ch so setCursor moves to end of line.
anchor.ch = null;
}
finalHead = anchor;
} else {
text = cm.getSelection();
var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
}
vimGlobalState.registerController.pushText(
args.registerName, 'change', text,
args.linewise, ranges.length > 1);
actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
},
// delete is a javascript keyword.
'delete': function(cm, args, ranges) {
var finalHead, text;
var vim = cm.state.vim;
if (!vim.visualBlock) {
var anchor = ranges[0].anchor,
head = ranges[0].head;
if (args.linewise &&
head.line != cm.firstLine() &&
anchor.line == cm.lastLine() &&
anchor.line == head.line - 1) {
// Special case for dd on last line (and first line).
if (anchor.line == cm.firstLine()) {
anchor.ch = 0;
} else {
anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
}
}
text = cm.getRange(anchor, head);
cm.replaceRange('', anchor, head);
finalHead = anchor;
if (args.linewise) {
finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
}
} else {
text = cm.getSelection();
var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
finalHead = ranges[0].anchor;
}
vimGlobalState.registerController.pushText(
args.registerName, 'delete', text,
args.linewise, vim.visualBlock);
return clipCursorToContent(cm, finalHead);
},
indent: function(cm, args, ranges) {
var vim = cm.state.vim;
var startLine = ranges[0].anchor.line;
var endLine = vim.visualBlock ?
ranges[ranges.length - 1].anchor.line :
ranges[0].head.line;
// In visual mode, n> shifts the selection right n times, instead of
// shifting n lines right once.
var repeat = (vim.visualMode) ? args.repeat : 1;
if (args.linewise) {
// The only way to delete a newline is to delete until the start of
// the next line, so in linewise mode evalInput will include the next
// line. We don't want this in indent, so we go back a line.
endLine--;
}
for (var i = startLine; i <= endLine; i++) {
for (var j = 0; j < repeat; j++) {
cm.indentLine(i, args.indentRight);
}
}
return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
},
changeCase: function(cm, args, ranges, oldAnchor, newHead) {
var selections = cm.getSelections();
var swapped = [];
var toLower = args.toLower;
for (var j = 0; j < selections.length; j++) {
var toSwap = selections[j];
var text = '';
if (toLower === true) {
text = toSwap.toLowerCase();
} else if (toLower === false) {
text = toSwap.toUpperCase();
} else {
for (var i = 0; i < toSwap.length; i++) {
var character = toSwap.charAt(i);
text += isUpperCase(character) ? character.toLowerCase() :
character.toUpperCase();
}
}
swapped.push(text);
}
cm.replaceSelections(swapped);
if (args.shouldMoveCursor){
return newHead;
} else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
} else if (args.linewise){
return oldAnchor;
} else {
return cursorMin(ranges[0].anchor, ranges[0].head);
}
},
yank: function(cm, args, ranges, oldAnchor) {
var vim = cm.state.vim;
var text = cm.getSelection();
var endPos = vim.visualMode
? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
: oldAnchor;
vimGlobalState.registerController.pushText(
args.registerName, 'yank',
text, args.linewise, vim.visualBlock);
return endPos;
}
};
function defineOperator(name, fn) {
operators[name] = fn;
}
var actions = {
jumpListWalk: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat;
var forward = actionArgs.forward;
var jumpList = vimGlobalState.jumpList;
var mark = jumpList.move(cm, forward ? repeat : -repeat);
var markPos = mark ? mark.find() : undefined;
markPos = markPos ? markPos : cm.getCursor();
cm.setCursor(markPos);
},
scroll: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat || 1;
var lineHeight = cm.defaultTextHeight();
var top = cm.getScrollInfo().top;
var delta = lineHeight * repeat;
var newPos = actionArgs.forward ? top + delta : top - delta;
var cursor = copyCursor(cm.getCursor());
var cursorCoords = cm.charCoords(cursor, 'local');
if (actionArgs.forward) {
if (newPos > cursorCoords.top) {
cursor.line += (newPos - cursorCoords.top) / lineHeight;
cursor.line = Math.ceil(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(null, cursorCoords.top);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
} else {
var newBottom = newPos + cm.getScrollInfo().clientHeight;
if (newBottom < cursorCoords.bottom) {
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
cursor.line = Math.floor(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
}
},
scrollToCursor: function(cm, actionArgs) {
var lineNum = cm.getCursor().line;
var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
var height = cm.getScrollInfo().clientHeight;
var y = charCoords.top;
var lineHeight = charCoords.bottom - y;
switch (actionArgs.position) {
case 'center': y = y - (height / 2) + lineHeight;
break;
case 'bottom': y = y - height + lineHeight*1.4;
break;
case 'top': y = y + lineHeight*0.4;
break;
}
cm.scrollTo(null, y);
},
replayMacro: function(cm, actionArgs, vim) {
var registerName = actionArgs.selectedCharacter;
var repeat = actionArgs.repeat;
var macroModeState = vimGlobalState.macroModeState;
if (registerName == '@') {
registerName = macroModeState.latestRegister;
}
while(repeat--){
executeMacroRegister(cm, vim, macroModeState, registerName);
}
},
enterMacroRecordMode: function(cm, actionArgs) {
var macroModeState = vimGlobalState.macroModeState;
var registerName = actionArgs.selectedCharacter;
macroModeState.enterMacroRecordMode(cm, registerName);
},
enterInsertMode: function(cm, actionArgs, vim) {
if (cm.getOption('readOnly')) { return; }
vim.insertMode = true;
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
var sel = vim.sel;
var head = actionArgs.head || cm.getCursor('head');
var height = cm.listSelections().length;
if (insertAt == 'eol') {
head = Pos(head.line, lineLength(cm, head.line));
} else if (insertAt == 'charAfter') {
head = offsetCursor(head, 0, 1);
} else if (insertAt == 'firstNonBlank') {
head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
} else if (insertAt == 'startOfSelectedArea') {
if (!vim.visualBlock) {
if (sel.head.line < sel.anchor.line) {
head = sel.head;
} else {
head = Pos(sel.anchor.line, 0);
}
} else {
head = Pos(
Math.min(sel.head.line, sel.anchor.line),
Math.min(sel.head.ch, sel.anchor.ch));
height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'endOfSelectedArea') {
if (!vim.visualBlock) {
if (sel.head.line >= sel.anchor.line) {
head = offsetCursor(sel.head, 0, 1);
} else {
head = Pos(sel.anchor.line, 0);
}
} else {
head = Pos(
Math.min(sel.head.line, sel.anchor.line),
Math.max(sel.head.ch + 1, sel.anchor.ch));
height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'inplace') {
if (vim.visualMode){
return;
}
}
cm.setOption('keyMap', 'vim-insert');
cm.setOption('disableInput', false);
if (actionArgs && actionArgs.replace) {
// Handle Replace-mode as a special case of insert mode.
cm.toggleOverwrite(true);
cm.setOption('keyMap', 'vim-replace');
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
} else {
cm.setOption('keyMap', 'vim-insert');
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
}
if (!vimGlobalState.macroModeState.isPlaying) {
// Only record if not replaying.
cm.on('change', onChange);
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
if (vim.visualMode) {
exitVisualMode(cm);
}
selectForInsert(cm, head, height);
},
toggleVisualMode: function(cm, actionArgs, vim) {
var repeat = actionArgs.repeat;
var anchor = cm.getCursor();
var head;
// TODO: The repeat should actually select number of characters/lines
// equal to the repeat times the size of the previous visual
// operation.
if (!vim.visualMode) {
// Entering visual mode
vim.visualMode = true;
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
head = clipCursorToContent(
cm, Pos(anchor.line, anchor.ch + repeat - 1),
true /** includeLineBreak */);
vim.sel = {
anchor: anchor,
head: head
};
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
updateCmSelection(cm);
updateMark(cm, vim, '<', cursorMin(anchor, head));
updateMark(cm, vim, '>', cursorMax(anchor, head));
} else if (vim.visualLine ^ actionArgs.linewise ||
vim.visualBlock ^ actionArgs.blockwise) {
// Toggling between modes
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
updateCmSelection(cm);
} else {
exitVisualMode(cm);
}
},
reselectLastSelection: function(cm, _actionArgs, vim) {
var lastSelection = vim.lastSelection;
if (vim.visualMode) {
updateLastSelection(cm, vim);
}
if (lastSelection) {
var anchor = lastSelection.anchorMark.find();
var head = lastSelection.headMark.find();
if (!anchor || !head) {
// If the marks have been destroyed due to edits, do nothing.
return;
}
vim.sel = {
anchor: anchor,
head: head
};
vim.visualMode = true;
vim.visualLine = lastSelection.visualLine;
vim.visualBlock = lastSelection.visualBlock;
updateCmSelection(cm);
updateMark(cm, vim, '<', cursorMin(anchor, head));
updateMark(cm, vim, '>', cursorMax(anchor, head));
CodeMirror.signal(cm, 'vim-mode-change', {
mode: 'visual',
subMode: vim.visualLine ? 'linewise' :
vim.visualBlock ? 'blockwise' : ''});
}
},
joinLines: function(cm, actionArgs, vim) {
var curStart, curEnd;
if (vim.visualMode) {
curStart = cm.getCursor('anchor');
curEnd = cm.getCursor('head');
if (cursorIsBefore(curEnd, curStart)) {
var tmp = curEnd;
curEnd = curStart;
curStart = tmp;
}
curEnd.ch = lineLength(cm, curEnd.line) - 1;
} else {
// Repeat is the number of lines to join. Minimum 2 lines.
var repeat = Math.max(actionArgs.repeat, 2);
curStart = cm.getCursor();
curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
Infinity));
}
var finalCh = 0;
for (var i = curStart.line; i < curEnd.line; i++) {
finalCh = lineLength(cm, curStart.line);
var tmp = Pos(curStart.line + 1,
lineLength(cm, curStart.line + 1));
var text = cm.getRange(curStart, tmp);
text = text.replace(/\n\s*/g, ' ');
cm.replaceRange(text, curStart, tmp);
}
var curFinalPos = Pos(curStart.line, finalCh);
if (vim.visualMode) {
exitVisualMode(cm, false);
}
cm.setCursor(curFinalPos);
},
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
vim.insertMode = true;
var insertAt = copyCursor(cm.getCursor());
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
// Special case for inserting newline before start of document.
cm.replaceRange('\n', Pos(cm.firstLine(), 0));
cm.setCursor(cm.firstLine(), 0);
} else {
insertAt.line = (actionArgs.after) ? insertAt.line :
insertAt.line - 1;
insertAt.ch = lineLength(cm, insertAt.line);
cm.setCursor(insertAt);
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
CodeMirror.commands.newlineAndIndent;
newlineFn(cm);
}
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
},
paste: function(cm, actionArgs, vim) {
var cur = copyCursor(cm.getCursor());
var register = vimGlobalState.registerController.getRegister(
actionArgs.registerName);
var text = register.toString();
if (!text) {
return;
}
if (actionArgs.matchIndent) {
var tabSize = cm.getOption("tabSize");
// length that considers tabs and tabSize
var whitespaceLength = function(str) {
var tabs = (str.split("\t").length - 1);
var spaces = (str.split(" ").length - 1);
return tabs * tabSize + spaces * 1;
};
var currentLine = cm.getLine(cm.getCursor().line);
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
// chomp last newline b/c don't want it to match /^\s*/gm
var chompedText = text.replace(/\n$/, '');
var wasChomped = text !== chompedText;
var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
var text = chompedText.replace(/^\s*/gm, function(wspace) {
var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
if (newIndent < 0) {
return "";
}
else if (cm.getOption("indentWithTabs")) {
var quotient = Math.floor(newIndent / tabSize);
return Array(quotient + 1).join('\t');
}
else {
return Array(newIndent + 1).join(' ');
}
});
text += wasChomped ? "\n" : "";
}
if (actionArgs.repeat > 1) {
var text = Array(actionArgs.repeat + 1).join(text);
}
var linewise = register.linewise;
var blockwise = register.blockwise;
if (linewise) {
if(vim.visualMode) {
text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
} else if (actionArgs.after) {
// Move the newline at the end to the start instead, and paste just
// before the newline character of the line we are on right now.
text = '\n' + text.slice(0, text.length - 1);
cur.ch = lineLength(cm, cur.line);
} else {
cur.ch = 0;
}
} else {
if (blockwise) {
text = text.split('\n');
for (var i = 0; i < text.length; i++) {
text[i] = (text[i] == '') ? ' ' : text[i];
}
}
cur.ch += actionArgs.after ? 1 : 0;
}
var curPosFinal;
var idx;
if (vim.visualMode) {
// save the pasted text for reselection if the need arises
vim.lastPastedText = text;
var lastSelectionCurEnd;
var selectedArea = getSelectedAreaRange(cm, vim);
var selectionStart = selectedArea[0];
var selectionEnd = selectedArea[1];
var selectedText = cm.getSelection();
var selections = cm.listSelections();
var emptyStrings = new Array(selections.length).join('1').split('1');
// save the curEnd marker before it get cleared due to cm.replaceRange.
if (vim.lastSelection) {
lastSelectionCurEnd = vim.lastSelection.headMark.find();
}
// push the previously selected text to unnamed register
vimGlobalState.registerController.unnamedRegister.setText(selectedText);
if (blockwise) {
// first delete the selected text
cm.replaceSelections(emptyStrings);
// Set new selections as per the block length of the yanked text
selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
cm.setCursor(selectionStart);
selectBlock(cm, selectionEnd);
cm.replaceSelections(text);
curPosFinal = selectionStart;
} else if (vim.visualBlock) {
cm.replaceSelections(emptyStrings);
cm.setCursor(selectionStart);
cm.replaceRange(text, selectionStart, selectionStart);
curPosFinal = selectionStart;
} else {
cm.replaceRange(text, selectionStart, selectionEnd);
curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
}
// restore the the curEnd marker
if(lastSelectionCurEnd) {
vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
}
if (linewise) {
curPosFinal.ch=0;
}
} else {
if (blockwise) {
cm.setCursor(cur);
for (var i = 0; i < text.length; i++) {
var line = cur.line+i;
if (line > cm.lastLine()) {
cm.replaceRange('\n', Pos(line, 0));
}
var lastCh = lineLength(cm, line);
if (lastCh < cur.ch) {
extendLineToColumn(cm, line, cur.ch);
}
}
cm.setCursor(cur);
selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
cm.replaceSelections(text);
curPosFinal = cur;
} else {
cm.replaceRange(text, cur);
// Now fine tune the cursor to where we want it.
if (linewise && actionArgs.after) {
curPosFinal = Pos(
cur.line + 1,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
} else if (linewise && !actionArgs.after) {
curPosFinal = Pos(
cur.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
} else if (!linewise && actionArgs.after) {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length - 1);
} else {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length);
}
}
}
if (vim.visualMode) {
exitVisualMode(cm, false);
}
cm.setCursor(curPosFinal);
},
undo: function(cm, actionArgs) {
cm.operation(function() {
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
cm.setCursor(cm.getCursor('anchor'));
});
},
redo: function(cm, actionArgs) {
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
},
setRegister: function(_cm, actionArgs, vim) {
vim.inputState.registerName = actionArgs.selectedCharacter;
},
setMark: function(cm, actionArgs, vim) {
var markName = actionArgs.selectedCharacter;
updateMark(cm, vim, markName, cm.getCursor());
},
replace: function(cm, actionArgs, vim) {
var replaceWith = actionArgs.selectedCharacter;
var curStart = cm.getCursor();
var replaceTo;
var curEnd;
var selections = cm.listSelections();
if (vim.visualMode) {
curStart = cm.getCursor('start');
curEnd = cm.getCursor('end');
} else {
var line = cm.getLine(curStart.line);
replaceTo = curStart.ch + actionArgs.repeat;
if (replaceTo > line.length) {
replaceTo=line.length;
}
curEnd = Pos(curStart.line, replaceTo);
}
if (replaceWith=='\n') {
if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
// special case, where vim help says to replace by just one line-break
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
} else {
var replaceWithStr = cm.getRange(curStart, curEnd);
//replace all characters in range by selected, but keep linebreaks
replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
if (vim.visualBlock) {
// Tabs are split in visua block before replacing
var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
replaceWithStr = cm.getSelection();
replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
cm.replaceSelections(replaceWithStr);
} else {
cm.replaceRange(replaceWithStr, curStart, curEnd);
}
if (vim.visualMode) {
curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
selections[0].anchor : selections[0].head;
cm.setCursor(curStart);
exitVisualMode(cm, false);
} else {
cm.setCursor(offsetCursor(curEnd, 0, -1));
}
}
},
incrementNumberToken: function(cm, actionArgs) {
var cur = cm.getCursor();
var lineStr = cm.getLine(cur.line);
var re = /-?\d+/g;
var match;
var start;
var end;
var numberStr;
var token;
while ((match = re.exec(lineStr)) !== null) {
token = match[0];
start = match.index;
end = start + token.length;
if (cur.ch < end)break;
}
if (!actionArgs.backtrack && (end <= cur.ch))return;
if (token) {
var increment = actionArgs.increase ? 1 : -1;
var number = parseInt(token) + (increment * actionArgs.repeat);
var from = Pos(cur.line, start);
var to = Pos(cur.line, end);
numberStr = number.toString();
cm.replaceRange(numberStr, from, to);
} else {
return;
}
cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
},
repeatLastEdit: function(cm, actionArgs, vim) {
var lastEditInputState = vim.lastEditInputState;
if (!lastEditInputState) { return; }
var repeat = actionArgs.repeat;
if (repeat && actionArgs.repeatIsExplicit) {
vim.lastEditInputState.repeatOverride = repeat;
} else {
repeat = vim.lastEditInputState.repeatOverride || repeat;
}
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
},
exitInsertMode: exitInsertMode
};
function defineAction(name, fn) {
actions[name] = fn;
}
/*
* Below are miscellaneous utility functions used by vim.js
*/
/**
* Clips cursor to ensure that line is within the buffer's range
* If includeLineBreak is true, then allow cur.ch == lineLength.
*/
function clipCursorToContent(cm, cur, includeLineBreak) {
var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
var maxCh = lineLength(cm, line) - 1;
maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
var ch = Math.min(Math.max(0, cur.ch), maxCh);
return Pos(line, ch);
}
function copyArgs(args) {
var ret = {};
for (var prop in args) {
if (args.hasOwnProperty(prop)) {
ret[prop] = args[prop];
}
}
return ret;
}
function offsetCursor(cur, offsetLine, offsetCh) {
if (typeof offsetLine === 'object') {
offsetCh = offsetLine.ch;
offsetLine = offsetLine.line;
}
return Pos(cur.line + offsetLine, cur.ch + offsetCh);
}
function getOffset(anchor, head) {
return {
line: head.line - anchor.line,
ch: head.line - anchor.line
};
}
function commandMatches(keys, keyMap, context, inputState) {
// Partial matches are not applied. They inform the key handler
// that the current key sequence is a subsequence of a valid key
// sequence, so that the key buffer is not cleared.
var match, partial = [], full = [];
for (var i = 0; i < keyMap.length; i++) {
var command = keyMap[i];
if (context == 'insert' && command.context != 'insert' ||
command.context && command.context != context ||
inputState.operator && command.type == 'action' ||
!(match = commandMatch(keys, command.keys))) { continue; }
if (match == 'partial') { partial.push(command); }
if (match == 'full') { full.push(command); }
}
return {
partial: partial.length && partial,
full: full.length && full
};
}
function commandMatch(pressed, mapped) {
if (mapped.slice(-11) == '<character>') {
// Last character matches anything.
var prefixLen = mapped.length - 11;
var pressedPrefix = pressed.slice(0, prefixLen);
var mappedPrefix = mapped.slice(0, prefixLen);
return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
} else {
return pressed == mapped ? 'full' :
mapped.indexOf(pressed) == 0 ? 'partial' : false;
}
}
function lastChar(keys) {
var match = /^.*(<[\w\-]+>)$/.exec(keys);
var selectedCharacter = match ? match[1] : keys.slice(-1);
if (selectedCharacter.length > 1){
switch(selectedCharacter){
case '<CR>':
selectedCharacter='\n';
break;
case '<Space>':
selectedCharacter=' ';
break;
default:
break;
}
}
return selectedCharacter;
}
function repeatFn(cm, fn, repeat) {
return function() {
for (var i = 0; i < repeat; i++) {
fn(cm);
}
};
}
function copyCursor(cur) {
return Pos(cur.line, cur.ch);
}
function cursorEqual(cur1, cur2) {
return cur1.ch == cur2.ch && cur1.line == cur2.line;
}
function cursorIsBefore(cur1, cur2) {
if (cur1.line < cur2.line) {
return true;
}
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
return true;
}
return false;
}
function cursorMin(cur1, cur2) {
if (arguments.length > 2) {
cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
}
return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
}
function cursorMax(cur1, cur2) {
if (arguments.length > 2) {
cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
}
return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
}
function cursorIsBetween(cur1, cur2, cur3) {
// returns true if cur2 is between cur1 and cur3.
var cur1before2 = cursorIsBefore(cur1, cur2);
var cur2before3 = cursorIsBefore(cur2, cur3);
return cur1before2 && cur2before3;
}
function lineLength(cm, lineNum) {
return cm.getLine(lineNum).length;
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s+|\s+$/g, '');
}
function escapeRegex(s) {
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
}
function extendLineToColumn(cm, lineNum, column) {
var endCh = lineLength(cm, lineNum);
var spaces = new Array(column-endCh+1).join(' ');
cm.setCursor(Pos(lineNum, endCh));
cm.replaceRange(spaces, cm.getCursor());
}
// This functions selects a rectangular block
// of text with selectionEnd as any of its corner
// Height of block:
// Difference in selectionEnd.line and first/last selection.line
// Width of the block:
// Distance between selectionEnd.ch and any(first considered here) selection.ch
function selectBlock(cm, selectionEnd) {
var selections = [], ranges = cm.listSelections();
var head = copyCursor(cm.clipPos(selectionEnd));
var isClipped = !cursorEqual(selectionEnd, head);
var curHead = cm.getCursor('head');
var primIndex = getIndex(ranges, curHead);
var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
var max = ranges.length - 1;
var index = max - primIndex > primIndex ? max : 0;
var base = ranges[index].anchor;
var firstLine = Math.min(base.line, head.line);
var lastLine = Math.max(base.line, head.line);
var baseCh = base.ch, headCh = head.ch;
var dir = ranges[index].head.ch - baseCh;
var newDir = headCh - baseCh;
if (dir > 0 && newDir <= 0) {
baseCh++;
if (!isClipped) { headCh--; }
} else if (dir < 0 && newDir >= 0) {
baseCh--;
if (!wasClipped) { headCh++; }
} else if (dir < 0 && newDir == -1) {
baseCh--;
headCh++;
}
for (var line = firstLine; line <= lastLine; line++) {
var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
selections.push(range);
}
primIndex = head.line == lastLine ? selections.length - 1 : 0;
cm.setSelections(selections);
selectionEnd.ch = headCh;
base.ch = baseCh;
return base;
}
function selectForInsert(cm, head, height) {
var sel = [];
for (var i = 0; i < height; i++) {
var lineHead = offsetCursor(head, i, 0);
sel.push({anchor: lineHead, head: lineHead});
}
cm.setSelections(sel, 0);
}
// getIndex returns the index of the cursor in the selections.
function getIndex(ranges, cursor, end) {
for (var i = 0; i < ranges.length; i++) {
var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
if (atAnchor || atHead) {
return i;
}
}
return -1;
}
function getSelectedAreaRange(cm, vim) {
var lastSelection = vim.lastSelection;
var getCurrentSelectedAreaRange = function() {
var selections = cm.listSelections();
var start = selections[0];
var end = selections[selections.length-1];
var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
return [selectionStart, selectionEnd];
};
var getLastSelectedAreaRange = function() {
var selectionStart = cm.getCursor();
var selectionEnd = cm.getCursor();
var block = lastSelection.visualBlock;
if (block) {
var width = block.width;
var height = block.height;
selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
var selections = [];
// selectBlock creates a 'proper' rectangular block.
// We do not want that in all cases, so we manually set selections.
for (var i = selectionStart.line; i < selectionEnd.line; i++) {
var anchor = Pos(i, selectionStart.ch);
var head = Pos(i, selectionEnd.ch);
var range = {anchor: anchor, head: head};
selections.push(range);
}
cm.setSelections(selections);
} else {
var start = lastSelection.anchorMark.find();
var end = lastSelection.headMark.find();
var line = end.line - start.line;
var ch = end.ch - start.ch;
selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
if (lastSelection.visualLine) {
selectionStart = Pos(selectionStart.line, 0);
selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
}
cm.setSelection(selectionStart, selectionEnd);
}
return [selectionStart, selectionEnd];
};
if (!vim.visualMode) {
// In case of replaying the action.
return getLastSelectedAreaRange();
} else {
return getCurrentSelectedAreaRange();
}
}
// Updates the previous selection with the current selection's values. This
// should only be called in visual mode.
function updateLastSelection(cm, vim) {
var anchor = vim.sel.anchor;
var head = vim.sel.head;
// To accommodate the effect of lastPastedText in the last selection
if (vim.lastPastedText) {
head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
vim.lastPastedText = null;
}
vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
'headMark': cm.setBookmark(head),
'anchor': copyCursor(anchor),
'head': copyCursor(head),
'visualMode': vim.visualMode,
'visualLine': vim.visualLine,
'visualBlock': vim.visualBlock};
}
function expandSelection(cm, start, end) {
var sel = cm.state.vim.sel;
var head = sel.head;
var anchor = sel.anchor;
var tmp;
if (cursorIsBefore(end, start)) {
tmp = end;
end = start;
start = tmp;
}
if (cursorIsBefore(head, anchor)) {
head = cursorMin(start, head);
anchor = cursorMax(anchor, end);
} else {
anchor = cursorMin(start, anchor);
head = cursorMax(head, end);
head = offsetCursor(head, 0, -1);
if (head.ch == -1 && head.line != cm.firstLine()) {
head = Pos(head.line - 1, lineLength(cm, head.line - 1));
}
}
return [anchor, head];
}
/**
* Updates the CodeMirror selection to match the provided vim selection.
* If no arguments are given, it uses the current vim selection state.
*/
function updateCmSelection(cm, sel, mode) {
var vim = cm.state.vim;
sel = sel || vim.sel;
var mode = mode ||
vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
var cmSel = makeCmSelection(cm, sel, mode);
cm.setSelections(cmSel.ranges, cmSel.primary);
updateFakeCursor(cm);
}
function makeCmSelection(cm, sel, mode, exclusive) {
var head = copyCursor(sel.head);
var anchor = copyCursor(sel.anchor);
if (mode == 'char') {
var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
head = offsetCursor(sel.head, 0, headOffset);
anchor = offsetCursor(sel.anchor, 0, anchorOffset);
return {
ranges: [{anchor: anchor, head: head}],
primary: 0
};
} else if (mode == 'line') {
if (!cursorIsBefore(sel.head, sel.anchor)) {
anchor.ch = 0;
var lastLine = cm.lastLine();
if (head.line > lastLine) {
head.line = lastLine;
}
head.ch = lineLength(cm, head.line);
} else {
head.ch = 0;
anchor.ch = lineLength(cm, anchor.line);
}
return {
ranges: [{anchor: anchor, head: head}],
primary: 0
};
} else if (mode == 'block') {
var top = Math.min(anchor.line, head.line),
left = Math.min(anchor.ch, head.ch),
bottom = Math.max(anchor.line, head.line),
right = Math.max(anchor.ch, head.ch) + 1;
var height = bottom - top + 1;
var primary = head.line == top ? 0 : height - 1;
var ranges = [];
for (var i = 0; i < height; i++) {
ranges.push({
anchor: Pos(top + i, left),
head: Pos(top + i, right)
});
}
return {
ranges: ranges,
primary: primary
};
}
}
function getHead(cm) {
var cur = cm.getCursor('head');
if (cm.getSelection().length == 1) {
// Small corner case when only 1 character is selected. The "real"
// head is the left of head and anchor.
cur = cursorMin(cur, cm.getCursor('anchor'));
}
return cur;
}
/**
* If moveHead is set to false, the CodeMirror selection will not be
* touched. The caller assumes the responsibility of putting the cursor
* in the right place.
*/
function exitVisualMode(cm, moveHead) {
var vim = cm.state.vim;
if (moveHead !== false) {
cm.setCursor(clipCursorToContent(cm, vim.sel.head));
}
updateLastSelection(cm, vim);
vim.visualMode = false;
vim.visualLine = false;
vim.visualBlock = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (vim.fakeCursor) {
vim.fakeCursor.clear();
}
}
// Remove any trailing newlines from the selection. For
// example, with the caret at the start of the last word on the line,
// 'dw' should word, but not the newline, while 'w' should advance the
// caret to the first character of the next line.
function clipToLine(cm, curStart, curEnd) {
var selection = cm.getRange(curStart, curEnd);
// Only clip if the selection ends with trailing newline + whitespace
if (/\n\s*$/.test(selection)) {
var lines = selection.split('\n');
// We know this is all whitepsace.
lines.pop();
// Cases:
// 1. Last word is an empty line - do not clip the trailing '\n'
// 2. Last word is not an empty line - clip the trailing '\n'
var line;
// Find the line containing the last word, and clip all whitespace up
// to it.
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
curEnd.line--;
curEnd.ch = 0;
}
// If the last word is not an empty line, clip an additional newline
if (line) {
curEnd.line--;
curEnd.ch = lineLength(cm, curEnd.line);
} else {
curEnd.ch = 0;
}
}
}
// Expand the selection to line ends.
function expandSelectionToLine(_cm, curStart, curEnd) {
curStart.ch = 0;
curEnd.ch = 0;
curEnd.line++;
}
function findFirstNonWhiteSpaceCharacter(text) {
if (!text) {
return 0;
}
var firstNonWS = text.search(/\S/);
return firstNonWS == -1 ? text.length : firstNonWS;
}
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
var cur = getHead(cm);
var line = cm.getLine(cur.line);
var idx = cur.ch;
// Seek to first word or non-whitespace character, depending on if
// noSymbol is true.
var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
while (!test(line.charAt(idx))) {
idx++;
if (idx >= line.length) { return null; }
}
if (bigWord) {
test = bigWordCharTest[0];
} else {
test = wordCharTest[0];
if (!test(line.charAt(idx))) {
test = wordCharTest[1];
}
}
var end = idx, start = idx;
while (test(line.charAt(end)) && end < line.length) { end++; }
while (test(line.charAt(start)) && start >= 0) { start--; }
start++;
if (inclusive) {
// If present, include all whitespace after word.
// Otherwise, include all whitespace before word, except indentation.
var wordEnd = end;
while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
if (wordEnd == end) {
var wordStart = start;
while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
if (!start) { start = wordStart; }
}
}
return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
}
function recordJumpPosition(cm, oldCur, newCur) {
if (!cursorEqual(oldCur, newCur)) {
vimGlobalState.jumpList.add(cm, oldCur, newCur);
}
}
function recordLastCharacterSearch(increment, args) {
vimGlobalState.lastChararacterSearch.increment = increment;
vimGlobalState.lastChararacterSearch.forward = args.forward;
vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
}
var symbolToMode = {
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
'[': 'section', ']': 'section',
'*': 'comment', '/': 'comment',
'm': 'method', 'M': 'method',
'#': 'preprocess'
};
var findSymbolModes = {
bracket: {
isComplete: function(state) {
if (state.nextCh === state.symb) {
state.depth++;
if (state.depth >= 1)return true;
} else if (state.nextCh === state.reverseSymb) {
state.depth--;
}
return false;
}
},
section: {
init: function(state) {
state.curMoveThrough = true;
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
},
isComplete: function(state) {
return state.index === 0 && state.nextCh === state.symb;
}
},
comment: {
isComplete: function(state) {
var found = state.lastCh === '*' && state.nextCh === '/';
state.lastCh = state.nextCh;
return found;
}
},
// TODO: The original Vim implementation only operates on level 1 and 2.
// The current implementation doesn't check for code block level and
// therefore it operates on any levels.
method: {
init: function(state) {
state.symb = (state.symb === 'm' ? '{' : '}');
state.reverseSymb = state.symb === '{' ? '}' : '{';
},
isComplete: function(state) {
if (state.nextCh === state.symb)return true;
return false;
}
},
preprocess: {
init: function(state) {
state.index = 0;
},
isComplete: function(state) {
if (state.nextCh === '#') {
var token = state.lineText.match(/#(\w+)/)[1];
if (token === 'endif') {
if (state.forward && state.depth === 0) {
return true;
}
state.depth++;
} else if (token === 'if') {
if (!state.forward && state.depth === 0) {
return true;
}
state.depth--;
}
if (token === 'else' && state.depth === 0)return true;
}
return false;
}
}
};
function findSymbol(cm, repeat, forward, symb) {
var cur = copyCursor(cm.getCursor());
var increment = forward ? 1 : -1;
var endLine = forward ? cm.lineCount() : -1;
var curCh = cur.ch;
var line = cur.line;
var lineText = cm.getLine(line);
var state = {
lineText: lineText,
nextCh: lineText.charAt(curCh),
lastCh: null,
index: curCh,
symb: symb,
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
forward: forward,
depth: 0,
curMoveThrough: false
};
var mode = symbolToMode[symb];
if (!mode)return cur;
var init = findSymbolModes[mode].init;
var isComplete = findSymbolModes[mode].isComplete;
if (init) { init(state); }
while (line !== endLine && repeat) {
state.index += increment;
state.nextCh = state.lineText.charAt(state.index);
if (!state.nextCh) {
line += increment;
state.lineText = cm.getLine(line) || '';
if (increment > 0) {
state.index = 0;
} else {
var lineLen = state.lineText.length;
state.index = (lineLen > 0) ? (lineLen-1) : 0;
}
state.nextCh = state.lineText.charAt(state.index);
}
if (isComplete(state)) {
cur.line = line;
cur.ch = state.index;
repeat--;
}
}
if (state.nextCh || state.curMoveThrough) {
return Pos(line, state.index);
}
return cur;
}
/*
* Returns the boundaries of the next word. If the cursor in the middle of
* the word, then returns the boundaries of the current word, starting at
* the cursor. If the cursor is at the start/end of a word, and we are going
* forward/backward, respectively, find the boundaries of the next word.
*
* @param {CodeMirror} cm CodeMirror object.
* @param {Cursor} cur The cursor position.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only [a-zA-Z0-9] characters count as part of the word.
* @param {boolean} emptyLineIsWord True if empty lines should be treated
* as words.
* @return {Object{from:number, to:number, line: number}} The boundaries of
* the word, or null if there are no more words.
*/
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
var lineNum = cur.line;
var pos = cur.ch;
var line = cm.getLine(lineNum);
var dir = forward ? 1 : -1;
var charTests = bigWord ? bigWordCharTest: wordCharTest;
if (emptyLineIsWord && line == '') {
lineNum += dir;
line = cm.getLine(lineNum);
if (!isLine(cm, lineNum)) {
return null;
}
pos = (forward) ? 0 : line.length;
}
while (true) {
if (emptyLineIsWord && line == '') {
return { from: 0, to: 0, line: lineNum };
}
var stop = (dir > 0) ? line.length : -1;
var wordStart = stop, wordEnd = stop;
// Find bounds of next word.
while (pos != stop) {
var foundWord = false;
for (var i = 0; i < charTests.length && !foundWord; ++i) {
if (charTests[i](line.charAt(pos))) {
wordStart = pos;
// Advance to end of word.
while (pos != stop && charTests[i](line.charAt(pos))) {
pos += dir;
}
wordEnd = pos;
foundWord = wordStart != wordEnd;
if (wordStart == cur.ch && lineNum == cur.line &&
wordEnd == wordStart + dir) {
// We started at the end of a word. Find the next one.
continue;
} else {
return {
from: Math.min(wordStart, wordEnd + 1),
to: Math.max(wordStart, wordEnd),
line: lineNum };
}
}
}
if (!foundWord) {
pos += dir;
}
}
// Advance to next/prev line.
lineNum += dir;
if (!isLine(cm, lineNum)) {
return null;
}
line = cm.getLine(lineNum);
pos = (dir > 0) ? 0 : line.length;
}
// Should never get here.
throw new Error('The impossible happened.');
}
/**
* @param {CodeMirror} cm CodeMirror object.
* @param {Pos} cur The position to start from.
* @param {int} repeat Number of words to move past.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} wordEnd True to move to end of word. False to move to
* beginning of word.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only alphabet characters count as part of the word.
* @return {Cursor} The position the cursor should move to.
*/
function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
var curStart = copyCursor(cur);
var words = [];
if (forward && !wordEnd || !forward && wordEnd) {
repeat++;
}
// For 'e', empty lines are not considered words, go figure.
var emptyLineIsWord = !(forward && wordEnd);
for (var i = 0; i < repeat; i++) {
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
if (!word) {
var eodCh = lineLength(cm, cm.lastLine());
words.push(forward
? {line: cm.lastLine(), from: eodCh, to: eodCh}
: {line: 0, from: 0, to: 0});
break;
}
words.push(word);
cur = Pos(word.line, forward ? (word.to - 1) : word.from);
}
var shortCircuit = words.length != repeat;
var firstWord = words[0];
var lastWord = words.pop();
if (forward && !wordEnd) {
// w
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return Pos(lastWord.line, lastWord.from);
} else if (forward && wordEnd) {
return Pos(lastWord.line, lastWord.to - 1);
} else if (!forward && wordEnd) {
// ge
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return Pos(lastWord.line, lastWord.to);
} else {
// b
return Pos(lastWord.line, lastWord.from);
}
}
function moveToCharacter(cm, repeat, forward, character) {
var cur = cm.getCursor();
var start = cur.ch;
var idx;
for (var i = 0; i < repeat; i ++) {
var line = cm.getLine(cur.line);
idx = charIdxInLine(start, line, character, forward, true);
if (idx == -1) {
return null;
}
start = idx;
}
return Pos(cm.getCursor().line, idx);
}
function moveToColumn(cm, repeat) {
// repeat is always >= 1, so repeat - 1 always corresponds
// to the column we want to go to.
var line = cm.getCursor().line;
return clipCursorToContent(cm, Pos(line, repeat - 1));
}
function updateMark(cm, vim, markName, pos) {
if (!inArray(markName, validMarks)) {
return;
}
if (vim.marks[markName]) {
vim.marks[markName].clear();
}
vim.marks[markName] = cm.setBookmark(pos);
}
function charIdxInLine(start, line, character, forward, includeChar) {
// Search for char in line.
// motion_options: {forward, includeChar}
// If includeChar = true, include it too.
// If forward = true, search forward, else search backwards.
// If char is not found on this line, do nothing
var idx;
if (forward) {
idx = line.indexOf(character, start + 1);
if (idx != -1 && !includeChar) {
idx -= 1;
}
} else {
idx = line.lastIndexOf(character, start - 1);
if (idx != -1 && !includeChar) {
idx += 1;
}
}
return idx;
}
function findParagraph(cm, head, repeat, dir, inclusive) {
var line = head.line;
var min = cm.firstLine();
var max = cm.lastLine();
var start, end, i = line;
function isEmpty(i) { return !cm.getLine(i); }
function isBoundary(i, dir, any) {
if (any) { return isEmpty(i) != isEmpty(i + dir); }
return !isEmpty(i) && isEmpty(i + dir);
}
if (dir) {
while (min <= i && i <= max && repeat > 0) {
if (isBoundary(i, dir)) { repeat--; }
i += dir;
}
return new Pos(i, 0);
}
var vim = cm.state.vim;
if (vim.visualLine && isBoundary(line, 1, true)) {
var anchor = vim.sel.anchor;
if (isBoundary(anchor.line, -1, true)) {
if (!inclusive || anchor.line != line) {
line += 1;
}
}
}
var startState = isEmpty(line);
for (i = line; i <= max && repeat; i++) {
if (isBoundary(i, 1, true)) {
if (!inclusive || isEmpty(i) != startState) {
repeat--;
}
}
}
end = new Pos(i, 0);
// select boundary before paragraph for the last one
if (i > max && !startState) { startState = true; }
else { inclusive = false; }
for (i = line; i > min; i--) {
if (!inclusive || isEmpty(i) == startState || i == line) {
if (isBoundary(i, -1, true)) { break; }
}
}
start = new Pos(i, 0);
return { start: start, end: end };
}
// TODO: perhaps this finagling of start and end positions belonds
// in codmirror/replaceRange?
function selectCompanionObject(cm, head, symb, inclusive) {
var cur = head, start, end;
var bracketRegexp = ({
'(': /[()]/, ')': /[()]/,
'[': /[[\]]/, ']': /[[\]]/,
'{': /[{}]/, '}': /[{}]/})[symb];
var openSym = ({
'(': '(', ')': '(',
'[': '[', ']': '[',
'{': '{', '}': '{'})[symb];
var curChar = cm.getLine(cur.line).charAt(cur.ch);
// Due to the behavior of scanForBracket, we need to add an offset if the
// cursor is on a matching open bracket.
var offset = curChar === openSym ? 1 : 0;
start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp});
end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp});
if (!start || !end) {
return { start: cur, end: cur };
}
start = start.pos;
end = end.pos;
if ((start.line == end.line && start.ch > end.ch)
|| (start.line > end.line)) {
var tmp = start;
start = end;
end = tmp;
}
if (inclusive) {
end.ch += 1;
} else {
start.ch += 1;
}
return { start: start, end: end };
}
// Takes in a symbol and a cursor and tries to simulate text objects that
// have identical opening and closing symbols
// TODO support across multiple lines
function findBeginningAndEnd(cm, head, symb, inclusive) {
var cur = copyCursor(head);
var line = cm.getLine(cur.line);
var chars = line.split('');
var start, end, i, len;
var firstIndex = chars.indexOf(symb);
// the decision tree is to always look backwards for the beginning first,
// but if the cursor is in front of the first instance of the symb,
// then move the cursor forward
if (cur.ch < firstIndex) {
cur.ch = firstIndex;
// Why is this line even here???
// cm.setCursor(cur.line, firstIndex+1);
}
// otherwise if the cursor is currently on the closing symbol
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
end = cur.ch; // assign end to the current cursor
--cur.ch; // make sure to look backwards
}
// if we're currently on the symbol, we've got a start
if (chars[cur.ch] == symb && !end) {
start = cur.ch + 1; // assign start to ahead of the cursor
} else {
// go backwards to find the start
for (i = cur.ch; i > -1 && !start; i--) {
if (chars[i] == symb) {
start = i + 1;
}
}
}
// look forwards for the end symbol
if (start && !end) {
for (i = start, len = chars.length; i < len && !end; i++) {
if (chars[i] == symb) {
end = i;
}
}
}
// nothing found
if (!start || !end) {
return { start: cur, end: cur };
}
// include the symbols
if (inclusive) {
--start; ++end;
}
return {
start: Pos(cur.line, start),
end: Pos(cur.line, end)
};
}
// Search functions
defineOption('pcre', true, 'boolean');
function SearchState() {}
SearchState.prototype = {
getQuery: function() {
return vimGlobalState.query;
},
setQuery: function(query) {
vimGlobalState.query = query;
},
getOverlay: function() {
return this.searchOverlay;
},
setOverlay: function(overlay) {
this.searchOverlay = overlay;
},
isReversed: function() {
return vimGlobalState.isReversed;
},
setReversed: function(reversed) {
vimGlobalState.isReversed = reversed;
},
getScrollbarAnnotate: function() {
return this.annotate;
},
setScrollbarAnnotate: function(annotate) {
this.annotate = annotate;
}
};
function getSearchState(cm) {
var vim = cm.state.vim;
return vim.searchState_ || (vim.searchState_ = new SearchState());
}
function dialog(cm, template, shortText, onClose, options) {
if (cm.openDialog) {
cm.openDialog(template, onClose, { bottom: true, value: options.value,
onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
selectValueOnOpen: false});
}
else {
onClose(prompt(shortText, ''));
}
}
function splitBySlash(argString) {
var slashes = findUnescapedSlashes(argString) || [];
if (!slashes.length) return [];
var tokens = [];
// in case of strings like foo/bar
if (slashes[0] !== 0) return;
for (var i = 0; i < slashes.length; i++) {
if (typeof slashes[i] == 'number')
tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
}
return tokens;
}
function findUnescapedSlashes(str) {
var escapeNextChar = false;
var slashes = [];
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (!escapeNextChar && c == '/') {
slashes.push(i);
}
escapeNextChar = !escapeNextChar && (c == '\\');
}
return slashes;
}
// Translates a search string from ex (vim) syntax into javascript form.
function translateRegex(str) {
// When these match, add a '\' if unescaped or remove one if escaped.
var specials = '|(){';
// Remove, but never add, a '\' for these.
var unescape = '}';
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
var specialComesNext = (n && specials.indexOf(n) != -1);
if (escapeNextChar) {
if (c !== '\\' || !specialComesNext) {
out.push(c);
}
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
// Treat the unescape list as special for removing, but not adding '\'.
if (n && unescape.indexOf(n) != -1) {
specialComesNext = true;
}
// Not passing this test means removing a '\'.
if (!specialComesNext || n === '\\') {
out.push(c);
}
} else {
out.push(c);
if (specialComesNext && n !== '\\') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Translates the replace part of a search and replace from ex (vim) syntax into
// javascript form. Similar to translateRegex, but additionally fixes back references
// (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
function translateRegexReplace(str) {
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
if (charUnescapes[c + n]) {
out.push(charUnescapes[c+n]);
i++;
} else if (escapeNextChar) {
// At any point in the loop, escapeNextChar is true if the previous
// character was a '\' and was not escaped.
out.push(c);
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
if ((isNumber(n) || n === '$')) {
out.push('$');
} else if (n !== '/' && n !== '\\') {
out.push('\\');
}
} else {
if (c === '$') {
out.push('$');
}
out.push(c);
if (n === '/') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Unescape \ and / in the replace part, for PCRE mode.
var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'};
function unescapeRegexReplace(str) {
var stream = new CodeMirror.StringStream(str);
var output = [];
while (!stream.eol()) {
// Search for \.
while (stream.peek() && stream.peek() != '\\') {
output.push(stream.next());
}
var matched = false;
for (var matcher in unescapes) {
if (stream.match(matcher, true)) {
matched = true;
output.push(unescapes[matcher]);
break;
}
}
if (!matched) {
// Don't change anything
output.push(stream.next());
}
}
return output.join('');
}
/**
* Extract the regular expression from the query and return a Regexp object.
* Returns null if the query is blank.
* If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
* If smartCase is passed in, and the query contains upper case letters,
* then ignoreCase is overridden, and the 'i' flag will not be set.
* If the query contains the /i in the flag part of the regular expression,
* then both ignoreCase and smartCase are ignored, and 'i' will be passed
* through to the Regex object.
*/
function parseQuery(query, ignoreCase, smartCase) {
// First update the last search register
var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
lastSearchRegister.setText(query);
// Check if the query is already a regex.
if (query instanceof RegExp) { return query; }
// First try to extract regex + flags from the input. If no flags found,
// extract just the regex. IE does not accept flags directly defined in
// the regex string in the form /regex/flags
var slashes = findUnescapedSlashes(query);
var regexPart;
var forceIgnoreCase;
if (!slashes.length) {
// Query looks like 'regexp'
regexPart = query;
} else {
// Query looks like 'regexp/...'
regexPart = query.substring(0, slashes[0]);
var flagsPart = query.substring(slashes[0]);
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
}
if (!regexPart) {
return null;
}
if (!getOption('pcre')) {
regexPart = translateRegex(regexPart);
}
if (smartCase) {
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
}
var regexp = new RegExp(regexPart,
(ignoreCase || forceIgnoreCase) ? 'i' : undefined);
return regexp;
}
function showConfirm(cm, text) {
if (cm.openNotification) {
cm.openNotification('<span style="color: red">' + text + '</span>',
{bottom: true, duration: 5000});
} else {
alert(text);
}
}
function makePrompt(prefix, desc) {
var raw = '';
if (prefix) {
raw += '<span style="font-family: monospace">' + prefix + '</span>';
}
raw += '<input type="text"/> ' +
'<span style="color: #888">';
if (desc) {
raw += '<span style="color: #888">';
raw += desc;
raw += '</span>';
}
return raw;
}
var searchPromptDesc = '(Javascript regexp)';
function showPrompt(cm, options) {
var shortText = (options.prefix || '') + ' ' + (options.desc || '');
var prompt = makePrompt(options.prefix, options.desc);
dialog(cm, prompt, shortText, options.onClose, options);
}
function regexEqual(r1, r2) {
if (r1 instanceof RegExp && r2 instanceof RegExp) {
var props = ['global', 'multiline', 'ignoreCase', 'source'];
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (r1[prop] !== r2[prop]) {
return false;
}
}
return true;
}
return false;
}
// Returns true if the query is valid.
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
if (!rawQuery) {
return;
}
var state = getSearchState(cm);
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
if (!query) {
return;
}
highlightSearchMatches(cm, query);
if (regexEqual(query, state.getQuery())) {
return query;
}
state.setQuery(query);
return query;
}
function searchOverlay(query) {
if (query.source.charAt(0) == '^') {
var matchSol = true;
}
return {
token: function(stream) {
if (matchSol && !stream.sol()) {
stream.skipToEnd();
return;
}
var match = stream.match(query, false);
if (match) {
if (match[0].length == 0) {
// Matched empty string, skip to next.
stream.next();
return 'searching';
}
if (!stream.sol()) {
// Backtrack 1 to match \b
stream.backUp(1);
if (!query.exec(stream.next() + match[0])) {
stream.next();
return null;
}
}
stream.match(query);
return 'searching';
}
while (!stream.eol()) {
stream.next();
if (stream.match(query, false)) break;
}
},
query: query
};
}
function highlightSearchMatches(cm, query) {
var searchState = getSearchState(cm);
var overlay = searchState.getOverlay();
if (!overlay || query != overlay.query) {
if (overlay) {
cm.removeOverlay(overlay);
}
overlay = searchOverlay(query);
cm.addOverlay(overlay);
if (cm.showMatchesOnScrollbar) {
if (searchState.getScrollbarAnnotate()) {
searchState.getScrollbarAnnotate().clear();
}
searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
}
searchState.setOverlay(overlay);
}
}
function findNext(cm, prev, query, repeat) {
if (repeat === undefined) { repeat = 1; }
return cm.operation(function() {
var pos = cm.getCursor();
var cursor = cm.getSearchCursor(query, pos);
for (var i = 0; i < repeat; i++) {
var found = cursor.find(prev);
if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
if (!found) {
// SearchCursor may have returned null because it hit EOF, wrap
// around and try again.
cursor = cm.getSearchCursor(query,
(prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
if (!cursor.find(prev)) {
return;
}
}
}
return cursor.from();
});
}
function clearSearchHighlight(cm) {
var state = getSearchState(cm);
cm.removeOverlay(getSearchState(cm).getOverlay());
state.setOverlay(null);
if (state.getScrollbarAnnotate()) {
state.getScrollbarAnnotate().clear();
state.setScrollbarAnnotate(null);
}
}
/**
* Check if pos is in the specified range, INCLUSIVE.
* Range can be specified with 1 or 2 arguments.
* If the first range argument is an array, treat it as an array of line
* numbers. Match pos against any of the lines.
* If the first range argument is a number,
* if there is only 1 range argument, check if pos has the same line
* number
* if there are 2 range arguments, then check if pos is in between the two
* range arguments.
*/
function isInRange(pos, start, end) {
if (typeof pos != 'number') {
// Assume it is a cursor position. Get the line number.
pos = pos.line;
}
if (start instanceof Array) {
return inArray(pos, start);
} else {
if (end) {
return (pos >= start && pos <= end);
} else {
return pos == start;
}
}
}
function getUserVisibleLines(cm) {
var scrollInfo = cm.getScrollInfo();
var occludeToleranceTop = 6;
var occludeToleranceBottom = 10;
var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
var to = cm.coordsChar({left:0, top: bottomY}, 'local');
return {top: from.line, bottom: to.line};
}
var ExCommandDispatcher = function() {
this.buildCommandMap_();
};
ExCommandDispatcher.prototype = {
processCommand: function(cm, input, opt_params) {
var that = this;
cm.operation(function () {
cm.curOp.isVimOp = true;
that._processCommand(cm, input, opt_params);
});
},
_processCommand: function(cm, input, opt_params) {
var vim = cm.state.vim;
var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
var previousCommand = commandHistoryRegister.toString();
if (vim.visualMode) {
exitVisualMode(cm);
}
var inputStream = new CodeMirror.StringStream(input);
// update ": with the latest command whether valid or invalid
commandHistoryRegister.setText(input);
var params = opt_params || {};
params.input = input;
try {
this.parseInput_(cm, inputStream, params);
} catch(e) {
showConfirm(cm, e);
throw e;
}
var command;
var commandName;
if (!params.commandName) {
// If only a line range is defined, move to the line.
if (params.line !== undefined) {
commandName = 'move';
}
} else {
command = this.matchCommand_(params.commandName);
if (command) {
commandName = command.name;
if (command.excludeFromCommandHistory) {
commandHistoryRegister.setText(previousCommand);
}
this.parseCommandArgs_(inputStream, params, command);
if (command.type == 'exToKey') {
// Handle Ex to Key mapping.
for (var i = 0; i < command.toKeys.length; i++) {
CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
}
return;
} else if (command.type == 'exToEx') {
// Handle Ex to Ex mapping.
this.processCommand(cm, command.toInput);
return;
}
}
}
if (!commandName) {
showConfirm(cm, 'Not an editor command ":' + input + '"');
return;
}
try {
exCommands[commandName](cm, params);
// Possibly asynchronous commands (e.g. substitute, which might have a
// user confirmation), are responsible for calling the callback when
// done. All others have it taken care of for them here.
if ((!command || !command.possiblyAsync) && params.callback) {
params.callback();
}
} catch(e) {
showConfirm(cm, e);
throw e;
}
},
parseInput_: function(cm, inputStream, result) {
inputStream.eatWhile(':');
// Parse range.
if (inputStream.eat('%')) {
result.line = cm.firstLine();
result.lineEnd = cm.lastLine();
} else {
result.line = this.parseLineSpec_(cm, inputStream);
if (result.line !== undefined && inputStream.eat(',')) {
result.lineEnd = this.parseLineSpec_(cm, inputStream);
}
}
// Parse command name.
var commandMatch = inputStream.match(/^(\w+)/);
if (commandMatch) {
result.commandName = commandMatch[1];
} else {
result.commandName = inputStream.match(/.*/)[0];
}
return result;
},
parseLineSpec_: function(cm, inputStream) {
var numberMatch = inputStream.match(/^(\d+)/);
if (numberMatch) {
return parseInt(numberMatch[1], 10) - 1;
}
switch (inputStream.next()) {
case '.':
return cm.getCursor().line;
case '$':
return cm.lastLine();
case '\'':
var mark = cm.state.vim.marks[inputStream.next()];
if (mark && mark.find()) {
return mark.find().line;
}
throw new Error('Mark not set');
default:
inputStream.backUp(1);
return undefined;
}
},
parseCommandArgs_: function(inputStream, params, command) {
if (inputStream.eol()) {
return;
}
params.argString = inputStream.match(/.*/)[0];
// Parse command-line arguments
var delim = command.argDelimiter || /\s+/;
var args = trim(params.argString).split(delim);
if (args.length && args[0]) {
params.args = args;
}
},
matchCommand_: function(commandName) {
// Return the command in the command map that matches the shortest
// prefix of the passed in command name. The match is guaranteed to be
// unambiguous if the defaultExCommandMap's shortNames are set up
// correctly. (see @code{defaultExCommandMap}).
for (var i = commandName.length; i > 0; i--) {
var prefix = commandName.substring(0, i);
if (this.commandMap_[prefix]) {
var command = this.commandMap_[prefix];
if (command.name.indexOf(commandName) === 0) {
return command;
}
}
}
return null;
},
buildCommandMap_: function() {
this.commandMap_ = {};
for (var i = 0; i < defaultExCommandMap.length; i++) {
var command = defaultExCommandMap[i];
var key = command.shortName || command.name;
this.commandMap_[key] = command;
}
},
map: function(lhs, rhs, ctx) {
if (lhs != ':' && lhs.charAt(0) == ':') {
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (rhs != ':' && rhs.charAt(0) == ':') {
// Ex to Ex mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToEx',
toInput: rhs.substring(1),
user: true
};
} else {
// Ex to key mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToKey',
toKeys: rhs,
user: true
};
}
} else {
if (rhs != ':' && rhs.charAt(0) == ':') {
// Key to Ex mapping.
var mapping = {
keys: lhs,
type: 'keyToEx',
exArgs: { input: rhs.substring(1) },
user: true};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
} else {
// Key to key mapping
var mapping = {
keys: lhs,
type: 'keyToKey',
toKeys: rhs,
user: true
};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
}
}
},
unmap: function(lhs, ctx) {
if (lhs != ':' && lhs.charAt(0) == ':') {
// Ex to Ex or Ex to key mapping
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
delete this.commandMap_[commandName];
return;
}
} else {
// Key to Ex or key to key mapping
var keys = lhs;
for (var i = 0; i < defaultKeymap.length; i++) {
if (keys == defaultKeymap[i].keys
&& defaultKeymap[i].context === ctx
&& defaultKeymap[i].user) {
defaultKeymap.splice(i, 1);
return;
}
}
}
throw Error('No such mapping.');
}
};
var exCommands = {
colorscheme: function(cm, params) {
if (!params.args || params.args.length < 1) {
showConfirm(cm, cm.getOption('theme'));
return;
}
cm.setOption('theme', params.args[0]);
},
map: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 2) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
},
imap: function(cm, params) { this.map(cm, params, 'insert'); },
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
unmap: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 1) {
if (cm) {
showConfirm(cm, 'No such mapping: ' + params.input);
}
return;
}
exCommandDispatcher.unmap(mapArgs[0], ctx);
},
move: function(cm, params) {
commandDispatcher.processCommand(cm, cm.state.vim, {
type: 'motion',
motion: 'moveToLineOrEdgeOfDocument',
motionArgs: { forward: false, explicitRepeat: true,
linewise: true },
repeatOverride: params.line+1});
},
set: function(cm, params) {
var setArgs = params.args;
// Options passed through to the setOption/getOption calls. May be passed in by the
// local/global versions of the set command
var setCfg = params.setCfg || {};
if (!setArgs || setArgs.length < 1) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
var expr = setArgs[0].split('=');
var optionName = expr[0];
var value = expr[1];
var forceGet = false;
if (optionName.charAt(optionName.length - 1) == '?') {
// If post-fixed with ?, then the set is actually a get.
if (value) { throw Error('Trailing characters: ' + params.argString); }
optionName = optionName.substring(0, optionName.length - 1);
forceGet = true;
}
if (value === undefined && optionName.substring(0, 2) == 'no') {
// To set boolean options to false, the option name is prefixed with
// 'no'.
optionName = optionName.substring(2);
value = false;
}
var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
if (optionIsBoolean && value == undefined) {
// Calling set with a boolean option sets it to true.
value = true;
}
// If no value is provided, then we assume this is a get.
if (!optionIsBoolean && value === undefined || forceGet) {
var oldValue = getOption(optionName, cm, setCfg);
if (oldValue === true || oldValue === false) {
showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
} else {
showConfirm(cm, ' ' + optionName + '=' + oldValue);
}
} else {
setOption(optionName, value, cm, setCfg);
}
},
setlocal: function (cm, params) {
// setCfg is passed through to setOption
params.setCfg = {scope: 'local'};
this.set(cm, params);
},
setglobal: function (cm, params) {
// setCfg is passed through to setOption
params.setCfg = {scope: 'global'};
this.set(cm, params);
},
registers: function(cm, params) {
var regArgs = params.args;
var registers = vimGlobalState.registerController.registers;
var regInfo = '----------Registers----------<br><br>';
if (!regArgs) {
for (var registerName in registers) {
var text = registers[registerName].toString();
if (text.length) {
regInfo += '"' + registerName + ' ' + text + '<br>';
}
}
} else {
var registerName;
regArgs = regArgs.join('');
for (var i = 0; i < regArgs.length; i++) {
registerName = regArgs.charAt(i);
if (!vimGlobalState.registerController.isValidRegister(registerName)) {
continue;
}
var register = registers[registerName] || new Register();
regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
}
}
showConfirm(cm, regInfo);
},
sort: function(cm, params) {
var reverse, ignoreCase, unique, number;
function parseArgs() {
if (params.argString) {
var args = new CodeMirror.StringStream(params.argString);
if (args.eat('!')) { reverse = true; }
if (args.eol()) { return; }
if (!args.eatSpace()) { return 'Invalid arguments'; }
var opts = args.match(/[a-z]+/);
if (opts) {
opts = opts[0];
ignoreCase = opts.indexOf('i') != -1;
unique = opts.indexOf('u') != -1;
var decimal = opts.indexOf('d') != -1 && 1;
var hex = opts.indexOf('x') != -1 && 1;
var octal = opts.indexOf('o') != -1 && 1;
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
}
if (args.match(/\/.*\//)) { return 'patterns not supported'; }
}
}
var err = parseArgs();
if (err) {
showConfirm(cm, err + ': ' + params.argString);
return;
}
var lineStart = params.line || cm.firstLine();
var lineEnd = params.lineEnd || params.line || cm.lastLine();
if (lineStart == lineEnd) { return; }
var curStart = Pos(lineStart, 0);
var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
var text = cm.getRange(curStart, curEnd).split('\n');
var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
(number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
(number == 'octal') ? /([0-7]+)/ : null;
var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
var numPart = [], textPart = [];
if (number) {
for (var i = 0; i < text.length; i++) {
if (numberRegex.exec(text[i])) {
numPart.push(text[i]);
} else {
textPart.push(text[i]);
}
}
} else {
textPart = text;
}
function compareFn(a, b) {
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
var anum = number && numberRegex.exec(a);
var bnum = number && numberRegex.exec(b);
if (!anum) { return a < b ? -1 : 1; }
anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
return anum - bnum;
}
numPart.sort(compareFn);
textPart.sort(compareFn);
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
if (unique) { // Remove duplicate lines
var textOld = text;
var lastLine;
text = [];
for (var i = 0; i < textOld.length; i++) {
if (textOld[i] != lastLine) {
text.push(textOld[i]);
}
lastLine = textOld[i];
}
}
cm.replaceRange(text.join('\n'), curStart, curEnd);
},
global: function(cm, params) {
// a global command is of the form
// :[range]g/pattern/[cmd]
// argString holds the string /pattern/[cmd]
var argString = params.argString;
if (!argString) {
showConfirm(cm, 'Regular Expression missing from global');
return;
}
// range is specified here
var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
var lineEnd = params.lineEnd || params.line || cm.lastLine();
// get the tokens from argString
var tokens = splitBySlash(argString);
var regexPart = argString, cmd;
if (tokens.length) {
regexPart = tokens[0];
cmd = tokens.slice(1, tokens.length).join('/');
}
if (regexPart) {
// If regex part is empty, then use the previous query. Otherwise
// use the regex part as the new query.
try {
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
true /** smartCase */);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + regexPart);
return;
}
}
// now that we have the regexPart, search for regex matches in the
// specified range of lines
var query = getSearchState(cm).getQuery();
var matchedLines = [], content = '';
for (var i = lineStart; i <= lineEnd; i++) {
var matched = query.test(cm.getLine(i));
if (matched) {
matchedLines.push(i+1);
content+= cm.getLine(i) + '<br>';
}
}
// if there is no [cmd], just display the list of matched lines
if (!cmd) {
showConfirm(cm, content);
return;
}
var index = 0;
var nextCommand = function() {
if (index < matchedLines.length) {
var command = matchedLines[index] + cmd;
exCommandDispatcher.processCommand(cm, command, {
callback: nextCommand
});
}
index++;
};
nextCommand();
},
substitute: function(cm, params) {
if (!cm.getSearchCursor) {
throw new Error('Search feature not available. Requires searchcursor.js or ' +
'any other getSearchCursor implementation.');
}
var argString = params.argString;
var tokens = argString ? splitBySlash(argString) : [];
var regexPart, replacePart = '', trailing, flagsPart, count;
var confirm = false; // Whether to confirm each replace.
var global = false; // True to replace all instances on a line, false to replace only 1.
if (tokens.length) {
regexPart = tokens[0];
replacePart = tokens[1];
if (replacePart !== undefined) {
if (getOption('pcre')) {
replacePart = unescapeRegexReplace(replacePart);
} else {
replacePart = translateRegexReplace(replacePart);
}
vimGlobalState.lastSubstituteReplacePart = replacePart;
}
trailing = tokens[2] ? tokens[2].split(' ') : [];
} else {
// either the argString is empty or its of the form ' hello/world'
// actually splitBySlash returns a list of tokens
// only if the string starts with a '/'
if (argString && argString.length) {
showConfirm(cm, 'Substitutions should be of the form ' +
':s/pattern/replace/');
return;
}
}
// After the 3rd slash, we can have flags followed by a space followed
// by count.
if (trailing) {
flagsPart = trailing[0];
count = parseInt(trailing[1]);
if (flagsPart) {
if (flagsPart.indexOf('c') != -1) {
confirm = true;
flagsPart.replace('c', '');
}
if (flagsPart.indexOf('g') != -1) {
global = true;
flagsPart.replace('g', '');
}
regexPart = regexPart + '/' + flagsPart;
}
}
if (regexPart) {
// If regex part is empty, then use the previous query. Otherwise use
// the regex part as the new query.
try {
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
true /** smartCase */);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + regexPart);
return;
}
}
replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
if (replacePart === undefined) {
showConfirm(cm, 'No previous substitute regular expression');
return;
}
var state = getSearchState(cm);
var query = state.getQuery();
var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
var lineEnd = params.lineEnd || lineStart;
if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
lineEnd = Infinity;
}
if (count) {
lineStart = lineEnd;
lineEnd = lineStart + count - 1;
}
var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
var cursor = cm.getSearchCursor(query, startPos);
doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
},
redo: CodeMirror.commands.redo,
undo: CodeMirror.commands.undo,
write: function(cm) {
if (CodeMirror.commands.save) {
// If a save command is defined, call it.
CodeMirror.commands.save(cm);
} else {
// Saves to text area if no save command is defined.
cm.save();
}
},
nohlsearch: function(cm) {
clearSearchHighlight(cm);
},
delmarks: function(cm, params) {
if (!params.argString || !trim(params.argString)) {
showConfirm(cm, 'Argument required');
return;
}
var state = cm.state.vim;
var stream = new CodeMirror.StringStream(trim(params.argString));
while (!stream.eol()) {
stream.eatSpace();
// Record the streams position at the beginning of the loop for use
// in error messages.
var count = stream.pos;
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var sym = stream.next();
// Check if this symbol is part of a range
if (stream.match('-', true)) {
// This symbol is part of a range.
// The range must terminate at an alphabetic character.
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var startMark = sym;
var finishMark = stream.next();
// The range must terminate at an alphabetic character which
// shares the same case as the start of the range.
if (isLowerCase(startMark) && isLowerCase(finishMark) ||
isUpperCase(startMark) && isUpperCase(finishMark)) {
var start = startMark.charCodeAt(0);
var finish = finishMark.charCodeAt(0);
if (start >= finish) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
// Because marks are always ASCII values, and we have
// determined that they are the same case, we can use
// their char codes to iterate through the defined range.
for (var j = 0; j <= finish - start; j++) {
var mark = String.fromCharCode(start + j);
delete state.marks[mark];
}
} else {
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
return;
}
} else {
// This symbol is a valid mark, and is not part of a range.
delete state.marks[sym];
}
}
}
};
var exCommandDispatcher = new ExCommandDispatcher();
/**
* @param {CodeMirror} cm CodeMirror instance we are in.
* @param {boolean} confirm Whether to confirm each replace.
* @param {Cursor} lineStart Line to start replacing from.
* @param {Cursor} lineEnd Line to stop replacing at.
* @param {RegExp} query Query for performing matches with.
* @param {string} replaceWith Text to replace matches with. May contain $1,
* $2, etc for replacing captured groups using Javascript replace.
* @param {function()} callback A callback for when the replace is done.
*/
function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
replaceWith, callback) {
// Set up all the functions.
cm.state.vim.exMode = true;
var done = false;
var lastPos = searchCursor.from();
function replaceAll() {
cm.operation(function() {
while (!done) {
replace();
next();
}
stop();
});
}
function replace() {
var text = cm.getRange(searchCursor.from(), searchCursor.to());
var newText = text.replace(query, replaceWith);
searchCursor.replace(newText);
}
function next() {
// The below only loops to skip over multiple occurrences on the same
// line when 'global' is not true.
while(searchCursor.findNext() &&
isInRange(searchCursor.from(), lineStart, lineEnd)) {
if (!global && lastPos && searchCursor.from().line == lastPos.line) {
continue;
}
cm.scrollIntoView(searchCursor.from(), 30);
cm.setSelection(searchCursor.from(), searchCursor.to());
lastPos = searchCursor.from();
done = false;
return;
}
done = true;
}
function stop(close) {
if (close) { close(); }
cm.focus();
if (lastPos) {
cm.setCursor(lastPos);
var vim = cm.state.vim;
vim.exMode = false;
vim.lastHPos = vim.lastHSPos = lastPos.ch;
}
if (callback) { callback(); }
}
function onPromptKeyDown(e, _value, close) {
// Swallow all keys.
CodeMirror.e_stop(e);
var keyName = CodeMirror.keyName(e);
switch (keyName) {
case 'Y':
replace(); next(); break;
case 'N':
next(); break;
case 'A':
// replaceAll contains a call to close of its own. We don't want it
// to fire too early or multiple times.
var savedCallback = callback;
callback = undefined;
cm.operation(replaceAll);
callback = savedCallback;
break;
case 'L':
replace();
// fall through and exit.
case 'Q':
case 'Esc':
case 'Ctrl-C':
case 'Ctrl-[':
stop(close);
break;
}
if (done) { stop(close); }
return true;
}
// Actually do replace.
next();
if (done) {
showConfirm(cm, 'No matches for ' + query.source);
return;
}
if (!confirm) {
replaceAll();
if (callback) { callback(); };
return;
}
showPrompt(cm, {
prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
onKeyDown: onPromptKeyDown
});
}
CodeMirror.keyMap.vim = {
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
function exitInsertMode(cm) {
var vim = cm.state.vim;
var macroModeState = vimGlobalState.macroModeState;
var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
var isPlaying = macroModeState.isPlaying;
var lastChange = macroModeState.lastInsertModeChanges;
// In case of visual block, the insertModeChanges are not saved as a
// single word, so we convert them to a single word
// so as to update the ". register as expected in real vim.
var text = [];
if (!isPlaying) {
var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1;
var changes = lastChange.changes;
var text = [];
var i = 0;
// In case of multiple selections in blockwise visual,
// the inserted text, for example: 'f<Backspace>oo', is stored as
// 'f', 'f', InsertModeKey 'o', 'o', 'o', 'o'. (if you have a block with 2 lines).
// We push the contents of the changes array as per the following:
// 1. In case of InsertModeKey, just increment by 1.
// 2. In case of a character, jump by selLength (2 in the example).
while (i < changes.length) {
// This loop will convert 'ff<bs>oooo' to 'f<bs>oo'.
text.push(changes[i]);
if (changes[i] instanceof InsertModeKey) {
i++;
} else {
i+= selLength;
}
}
lastChange.changes = text;
cm.off('change', onChange);
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
if (!isPlaying && vim.insertModeRepeat > 1) {
// Perform insert mode repeat for commands like 3,a and 3,o.
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
true /** repeatForInsert */);
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
}
delete vim.insertModeRepeat;
vim.insertMode = false;
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
cm.setOption('keyMap', 'vim');
cm.setOption('disableInput', true);
cm.toggleOverwrite(false); // exit replace mode if we were in it.
// update the ". register before exiting insert mode
insertModeChangeRegister.setText(lastChange.changes.join(''));
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (macroModeState.isRecording) {
logInsertModeChange(macroModeState);
}
}
function _mapCommand(command) {
defaultKeymap.unshift(command);
}
function mapCommand(keys, type, name, args, extra) {
var command = {keys: keys, type: type};
command[type] = name;
command[type + "Args"] = args;
for (var key in extra)
command[key] = extra[key];
_mapCommand(command);
}
// The timeout in milliseconds for the two-character ESC keymap should be
// adjusted according to your typing speed to prevent false positives.
defineOption('insertModeEscKeysTimeout', 200, 'number');
CodeMirror.keyMap['vim-insert'] = {
// TODO: override navigation keys so that Esc will cancel automatic
// indentation from o, O, i_<CR>
'Ctrl-N': 'autocomplete',
'Ctrl-P': 'autocomplete',
'Enter': function(cm) {
var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
CodeMirror.commands.newlineAndIndent;
fn(cm);
},
fallthrough: ['default'],
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
CodeMirror.keyMap['vim-replace'] = {
'Backspace': 'goCharLeft',
fallthrough: ['vim-insert'],
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
function executeMacroRegister(cm, vim, macroModeState, registerName) {
var register = vimGlobalState.registerController.getRegister(registerName);
if (registerName == ':') {
// Read-only register containing last Ex command.
if (register.keyBuffer[0]) {
exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
}
macroModeState.isPlaying = false;
return;
}
var keyBuffer = register.keyBuffer;
var imc = 0;
macroModeState.isPlaying = true;
macroModeState.replaySearchQueries = register.searchQueries.slice(0);
for (var i = 0; i < keyBuffer.length; i++) {
var text = keyBuffer[i];
var match, key;
while (text) {
// Pull off one command key, which is either a single character
// or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
match = (/<\w+-.+?>|<\w+>|./).exec(text);
key = match[0];
text = text.substring(match.index + key.length);
CodeMirror.Vim.handleKey(cm, key, 'macro');
if (vim.insertMode) {
var changes = register.insertModeChanges[imc++].changes;
vimGlobalState.macroModeState.lastInsertModeChanges.changes =
changes;
repeatInsertModeChanges(cm, changes, 1);
exitInsertMode(cm);
}
}
};
macroModeState.isPlaying = false;
}
function logKey(macroModeState, key) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.pushText(key);
}
}
function logInsertModeChange(macroModeState) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register && register.pushInsertModeChanges) {
register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
}
}
function logSearchQuery(macroModeState, query) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register && register.pushSearchQuery) {
register.pushSearchQuery(query);
}
}
/**
* Listens for changes made in insert mode.
* Should only be active in insert mode.
*/
function onChange(_cm, changeObj) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
if (!macroModeState.isPlaying) {
while(changeObj) {
lastChange.expectCursorActivityForChange = true;
if (changeObj.origin == '+input' || changeObj.origin == 'paste'
|| changeObj.origin === undefined /* only in testing */) {
var text = changeObj.text.join('\n');
lastChange.changes.push(text);
}
// Change objects may be chained with next.
changeObj = changeObj.next;
}
}
}
/**
* Listens for any kind of cursor activity on CodeMirror.
*/
function onCursorActivity(cm) {
var vim = cm.state.vim;
if (vim.insertMode) {
// Tracking cursor activity in insert mode (for macro support).
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
var lastChange = macroModeState.lastInsertModeChanges;
if (lastChange.expectCursorActivityForChange) {
lastChange.expectCursorActivityForChange = false;
} else {
// Cursor moved outside the context of an edit. Reset the change.
lastChange.changes = [];
}
} else if (!cm.curOp.isVimOp) {
handleExternalSelection(cm, vim);
}
if (vim.visualMode) {
updateFakeCursor(cm);
}
}
function updateFakeCursor(cm) {
var vim = cm.state.vim;
var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
var to = offsetCursor(from, 0, 1);
if (vim.fakeCursor) {
vim.fakeCursor.clear();
}
vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
}
function handleExternalSelection(cm, vim) {
var anchor = cm.getCursor('anchor');
var head = cm.getCursor('head');
// Enter or exit visual mode to match mouse selection.
if (vim.visualMode && !cm.somethingSelected()) {
exitVisualMode(cm, false);
} else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
vim.visualMode = true;
vim.visualLine = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
}
if (vim.visualMode) {
// Bind CodeMirror selection model to vim selection model.
// Mouse selections are considered visual characterwise.
var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
head = offsetCursor(head, 0, headOffset);
anchor = offsetCursor(anchor, 0, anchorOffset);
vim.sel = {
anchor: anchor,
head: head
};
updateMark(cm, vim, '<', cursorMin(head, anchor));
updateMark(cm, vim, '>', cursorMax(head, anchor));
} else if (!vim.insertMode) {
// Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
vim.lastHPos = cm.getCursor().ch;
}
}
/** Wrapper for special keys pressed in insert mode */
function InsertModeKey(keyName) {
this.keyName = keyName;
}
/**
* Handles raw key down events from the text area.
* - Should only be active in insert mode.
* - For recording deletes in insert mode.
*/
function onKeyEventTargetKeyDown(e) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
var keyName = CodeMirror.keyName(e);
if (!keyName) { return; }
function onKeyFound() {
lastChange.changes.push(new InsertModeKey(keyName));
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
}
}
/**
* Repeats the last edit, which includes exactly 1 command and at most 1
* insert. Operator and motion commands are read from lastEditInputState,
* while action commands are read from lastEditActionCommand.
*
* If repeatForInsert is true, then the function was called by
* exitInsertMode to repeat the insert mode changes the user just made. The
* corresponding enterInsertMode call was made with a count.
*/
function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
var macroModeState = vimGlobalState.macroModeState;
macroModeState.isPlaying = true;
var isAction = !!vim.lastEditActionCommand;
var cachedInputState = vim.inputState;
function repeatCommand() {
if (isAction) {
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
} else {
commandDispatcher.evalInput(cm, vim);
}
}
function repeatInsert(repeat) {
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
// For some reason, repeat cw in desktop VIM does not repeat
// insert mode changes. Will conform to that behavior.
repeat = !vim.lastEditActionCommand ? 1 : repeat;
var changeObject = macroModeState.lastInsertModeChanges;
repeatInsertModeChanges(cm, changeObject.changes, repeat);
}
}
vim.inputState = vim.lastEditInputState;
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
// o and O repeat have to be interlaced with insert repeats so that the
// insertions appear on separate lines instead of the last line.
for (var i = 0; i < repeat; i++) {
repeatCommand();
repeatInsert(1);
}
} else {
if (!repeatForInsert) {
// Hack to get the cursor to end up at the right place. If I is
// repeated in insert mode repeat, cursor will be 1 insert
// change set left of where it should be.
repeatCommand();
}
repeatInsert(repeat);
}
vim.inputState = cachedInputState;
if (vim.insertMode && !repeatForInsert) {
// Don't exit insert mode twice. If repeatForInsert is set, then we
// were called by an exitInsertMode call lower on the stack.
exitInsertMode(cm);
}
macroModeState.isPlaying = false;
};
function repeatInsertModeChanges(cm, changes, repeat) {
function keyHandler(binding) {
if (typeof binding == 'string') {
CodeMirror.commands[binding](cm);
} else {
binding(cm);
}
return true;
}
var head = cm.getCursor('head');
var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
if (inVisualBlock) {
// Set up block selection again for repeating the changes.
var vim = cm.state.vim;
var lastSel = vim.lastSelection;
var offset = getOffset(lastSel.anchor, lastSel.head);
selectForInsert(cm, head, offset.line + 1);
repeat = cm.listSelections().length;
cm.setCursor(head);
}
for (var i = 0; i < repeat; i++) {
if (inVisualBlock) {
cm.setCursor(offsetCursor(head, i, 0));
}
for (var j = 0; j < changes.length; j++) {
var change = changes[j];
if (change instanceof InsertModeKey) {
CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
} else {
var cur = cm.getCursor();
cm.replaceRange(change, cur, cur);
}
}
}
if (inVisualBlock) {
cm.setCursor(offsetCursor(head, 0, 1));
}
}
resetVimGlobalState();
return vimApi;
};
// Initialize Vim and make it available as an API.
CodeMirror.Vim = Vim();
});
| {
"content_hash": "2095b51cb3fb3130272ae92134856900",
"timestamp": "",
"source": "github",
"line_count": 5061,
"max_line_length": 185,
"avg_line_length": 39.03714680893104,
"alnum_prop": 0.554080387919035,
"repo_name": "ZalmanB/HealthTracker",
"id": "ccf332b5afa1adb2f0a525b2a936ef9ba687e97d",
"size": "197567",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/assets/codemirror/keymaps/vim-fc56c6934fbe80d60fdce7a3caac9e333e63ede2c98b40bf6799ab634c042d96.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1043967"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "HTML",
"bytes": "4323581"
},
{
"name": "JavaScript",
"bytes": "9630792"
},
{
"name": "Ruby",
"bytes": "167349"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.7.4 at 2017-05-08
| Rendered using Apache Maven Fluido Skin 1.6
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20170508" />
<meta http-equiv="Content-Language" content="en" />
<title>Play! 2.x Provider for Play! 2.1.x – Generated Reports</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.6.min.js"></script>
<link rel="stylesheet" href="./css/site.css" type="text/css" />
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-17472708-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left"><div id="bannerLeft"><h2>Play! 2.x Provider for Play! 2.1.x</h2>
</div>
</div>
<div class="pull-right"><div id="bannerRight"><img src="images/my-avatar-80.png" alt="avatar"/></div>
</div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2017-05-08<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.0.0-beta8</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Parent Project</li>
<li><a href="../index.html" title="Play! 2.x Providers"><span class="none"></span>Play! 2.x Providers</a> </li>
<li class="nav-header">Overview</li>
<li><a href="index.html" title="Introduction"><span class="none"></span>Introduction</a> </li>
<li><a href="usage.html" title="Usage"><span class="none"></span>Usage</a> </li>
<li><a href="apidocs/index.html" title="JavaDocs"><span class="none"></span>JavaDocs</a> </li>
<li class="nav-header">Project Documentation</li>
<li><a href="project-info.html" title="Project Information"><span class="icon-chevron-right"></span>Project Information</a> </li>
<li class="active"><a href="#"><span class="icon-chevron-down"></span>Project Reports</a>
<ul class="nav nav-list">
<li><a href="apidocs/index.html" title="JavaDocs"><span class="none"></span>JavaDocs</a> </li>
</ul>
</li>
</ul>
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2><a name="Generated_Reports"></a>Generated Reports</h2>
<p>This document provides an overview of the various reports that are automatically generated by <a class="externalLink" href="http://maven.apache.org">Maven</a> . Each report is briefly described below.</p>
<div class="section">
<h3><a name="Overview"></a>Overview</h3>
<table border="0" class="table table-striped">
<tr class="a">
<th>Document</th>
<th>Description</th></tr>
<tr class="b">
<td><a href="apidocs/index.html">JavaDocs</a></td>
<td>JavaDoc API documentation.</td></tr></table></div></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p>Copyright ©2013–2017.
All rights reserved.</p>
</div>
</div>
</footer>
</body>
</html>
| {
"content_hash": "4ea88b1be96637cabdbb532de6982b8e",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 207,
"avg_line_length": 43.359223300970875,
"alnum_prop": 0.5960591133004927,
"repo_name": "play2-maven-plugin/play2-maven-plugin.github.io",
"id": "f71333ed1d1a513fd1335a4aeaea334b488d158a",
"size": "4466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play2-maven-plugin/1.0.0-beta8/play2-providers/play2-provider-play21/project-reports.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2793124"
},
{
"name": "HTML",
"bytes": "178221432"
},
{
"name": "JavaScript",
"bytes": "120742"
}
],
"symlink_target": ""
} |
class MyFrame : public wxFrame
{
public:
// Constructor.
MyFrame( wxWindow* parent=(wxWindow *)NULL);
private:
// Event handlers (these functions should _not_ be virtual)
void OnUnloadResourceMenuCommand(wxCommandEvent& event);
void OnReloadResourceMenuCommand(wxCommandEvent& event);
void OnExitToolOrMenuCommand(wxCommandEvent& event);
void OnAboutToolOrMenuCommand(wxCommandEvent& event);
void OnNonDerivedDialogToolOrMenuCommand(wxCommandEvent& event);
void OnDerivedDialogToolOrMenuCommand(wxCommandEvent& event);
void OnControlsToolOrMenuCommand(wxCommandEvent& event);
void OnUncenteredToolOrMenuCommand(wxCommandEvent& event);
void OnAuiDemoToolOrMenuCommand(wxCommandEvent& event);
void OnObjRefToolOrMenuCommand(wxCommandEvent& event);
void OnCustomClassToolOrMenuCommand(wxCommandEvent& event);
void OnPlatformPropertyToolOrMenuCommand(wxCommandEvent& event);
void OnArtProviderToolOrMenuCommand(wxCommandEvent& event);
void OnVariableExpansionToolOrMenuCommand(wxCommandEvent& event);
void OnRecursiveLoad(wxCommandEvent& event);
void OnAnimationCtrlPlay(wxCommandEvent& event);
// Any class wishing to process wxWidgets events must use this macro
wxDECLARE_EVENT_TABLE();
};
//-----------------------------------------------------------------------------
// End single inclusion of this .h file condition
//-----------------------------------------------------------------------------
#endif // _MYFRAME_H_
| {
"content_hash": "341f6998fc7a6978871feeb37f32f4fb",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 79,
"avg_line_length": 39.81578947368421,
"alnum_prop": 0.7005948446794448,
"repo_name": "chartly/portfolio",
"id": "52c3d8ce52f78ec7264ec9ee311efd751a0454ff",
"size": "2634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ditfw-gfx/deps/wxwidgets/samples/xrc/myframe.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1858"
},
{
"name": "AppleScript",
"bytes": "8932"
},
{
"name": "Assembly",
"bytes": "56211"
},
{
"name": "Awk",
"bytes": "42674"
},
{
"name": "C",
"bytes": "14658690"
},
{
"name": "C#",
"bytes": "16016"
},
{
"name": "C++",
"bytes": "152172949"
},
{
"name": "CSS",
"bytes": "63103"
},
{
"name": "D",
"bytes": "416653"
},
{
"name": "HTML",
"bytes": "10956176"
},
{
"name": "JavaScript",
"bytes": "83645"
},
{
"name": "Lua",
"bytes": "2489072"
},
{
"name": "Makefile",
"bytes": "110228"
},
{
"name": "Mercury",
"bytes": "7093"
},
{
"name": "Nemerle",
"bytes": "28217"
},
{
"name": "Objective-C",
"bytes": "5596199"
},
{
"name": "Objective-C++",
"bytes": "1315875"
},
{
"name": "Pascal",
"bytes": "28104"
},
{
"name": "Perl",
"bytes": "18473"
},
{
"name": "Prolog",
"bytes": "4605"
},
{
"name": "Python",
"bytes": "333684"
},
{
"name": "R",
"bytes": "672260"
},
{
"name": "Rebol",
"bytes": "1286"
},
{
"name": "Shell",
"bytes": "1153351"
},
{
"name": "TeX",
"bytes": "202321"
},
{
"name": "XSLT",
"bytes": "44320"
}
],
"symlink_target": ""
} |
import { Component, Input } from '@angular/core';
import { FormGroup, FormArray, AbstractControl, FormControl } from '@angular/forms';
@Component({
selector: 'app-person',
templateUrl: './person.component.html',
styleUrls: ['./person.component.scss']
})
export class PersonComponent {
@Input() person: FormGroup;
disabled(condition) {
return condition ? 'disabled' : undefined;
}
get personValue() {
return this.person.value;
}
get childrenNames(): FormControl[] {
const children = this.person.get('childrenNames') as FormArray;
return children.controls as FormControl[];
}
get hobbies(): FormControl[] {
const hobbies = this.person.get('hobbies') as FormArray;
return hobbies && hobbies.controls as FormControl[];
}
get addressGroupInvalid() {
const address = this.person.get('address') as FormGroup;
return address && address.invalid;
}
}
| {
"content_hash": "837f60b4328ad98ec29e559971bbdb55",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 25.25,
"alnum_prop": 0.6864686468646864,
"repo_name": "Opinya/ngx-model2form",
"id": "ed8ce2a2026efcddbb0dc3575be63d4dbc42f146",
"size": "909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/src/app/person/person.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "287"
},
{
"name": "HTML",
"bytes": "1374"
},
{
"name": "JavaScript",
"bytes": "1646"
},
{
"name": "TypeScript",
"bytes": "12208"
}
],
"symlink_target": ""
} |
"""
# Created on
# @author:
# @contact:
"""
# 以下是自动生成的 #
# --- 导入系统配置
import dHydra.core.util as util
from dHydra.core.Vendor import Vendor
# --- 导入自定义配置
# 以上是自动生成的 #
from datetime import datetime, timedelta
from pymongo import MongoClient
from dHydra.core.Functions import get_vendor
import copy
class WorkerManager(Vendor):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.redis = get_vendor("DB").get_redis()
self.worker_names = list()
self.worker_info = dict()
self.updating = False
if "auto_remove_terminated" in kwargs:
self.auto_remove_terminated = kwargs["auto_remove_terminated"]
else:
self.auto_remove_terminated = -1
# -1: never;
# otherwise: auto remove terminated workers
# after (self.auto_remove_terminated) seconds
def get_worker_names(self):
worker_names = util.get_worker_names(logger=self.logger)
return worker_names
def get_workers_from_redis(self):
keys = self.redis.keys("dHydra.Worker.*.*.Info")
workers = dict()
for i in range(0, len(keys)):
channel = keys[i]
parsed_channel = channel.split('.')
if (len(parsed_channel) == 5) and (parsed_channel[4] == "Info") \
and (parsed_channel[0] == 'dHydra') \
and (parsed_channel[1] == 'Worker'):
if parsed_channel[2] not in workers:
workers[parsed_channel[2]] = dict()
worker = self.redis.hgetall(keys[i])
workers[parsed_channel[2]][parsed_channel[3]] = worker
return workers
def update_workers(self):
"""
更新Worker信息
:return:
"""
self.updating = True
# 根据文件目录检索
self.worker_names = self.get_worker_names()
# 从redis中获取worker信息并更新
worker_info = self.get_workers_from_redis()
# 去除掉过期信息
for worker_name, workers in worker_info.items():
if worker_name not in self.worker_info:
self.worker_info[worker_name] = dict()
for nickname, worker_info in workers.items():
heart_beat_interval = 1
if "heart_beat_interval" in worker_info:
heart_beat_interval = int(worker_info["heart_beat_interval"])
try:
difference = datetime.now() -\
datetime.strptime(
worker_info["heart_beat"],
'%Y-%m-%d %H:%M:%S.%f'
)
except ValueError:
difference = datetime.now() -\
datetime.strptime(
worker_info["heart_beat"],
'%Y-%m-%d %H:%M:%S'
)
if difference > timedelta(seconds=heart_beat_interval+1):
# 已经停止
if worker_info["status"] == "started":
worker_info["status"] = "disappeared"
self.logger.warning(
"发现一个没有正常关闭的Worker:\n"
"\tworker_name: {}\n"
"\tnickname: {}"
.format(worker_name, nickname)
)
self.redis.hmset("dHydra.Worker."+worker_name+"."+nickname+".Info",worker_info)
self.worker_info[worker_name][nickname] = copy.deepcopy(worker_info)
if self.auto_remove_terminated > -1 and\
difference>timedelta(seconds=self.auto_remove_terminated+1):
if "token" in worker_info:
token = worker_info["token"]
else:
token = None
removed = self.remove_worker(
worker_name=worker_name,
nickname=nickname,
token=token
)
if removed == 1:
self.logger.info(
"从redis中自动移除过期Worker:\n"
"\tworker_name:{}\n"
"\tnickname:{}\n"
"\ttoken:{}\n"
.format(worker_name,nickname,token)
)
else:
self.logger.warning(
"从redis中自动移除过期Worker:{}\n"
"\tworker_name:{}\n"
"\tnickname:{}\n"
"\ttoken:{}\n"
.format(
removed,
worker_name,
nickname,
token
)
)
self.updating = False
def remove_worker(
self,
worker_name,
nickname,
token
):
key = "dHydra.Worker."+worker_name+"."+nickname+"."+"Info"
worker_info = self.redis.hgetall(key)
if "token" in worker_info:
if worker_info["token"] == token:
return self.redis.delete(key)
else:
if token is None:
return self.redis.delete(key)
return 0 | {
"content_hash": "ba0eb5854a0c5001d392b952b4ec2c37",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 103,
"avg_line_length": 37.13013698630137,
"alnum_prop": 0.4501014572957019,
"repo_name": "Emptyset110/dHydra",
"id": "d1742bbd76c85c46e882756530b1b48063b89007",
"size": "5621",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dHydra/Vendor/WorkerManager/WorkerManager.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "8795"
},
{
"name": "Python",
"bytes": "1634611"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Sales\Test\Unit\Model\Order\Shipment\Comment;
/**
* Class ValidatorTest
*/
class ValidatorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Sales\Model\Order\Shipment\Comment\Validator
*/
protected $validator;
/**
* @var \Magento\Sales\Model\Order\Shipment\Comment|\PHPUnit_Framework_MockObject_MockObject
*/
protected $commentModelMock;
/**
* Set up
*/
protected function setUp()
{
$this->commentModelMock = $this->getMock(
'Magento\Sales\Model\Order\Shipment\Comment',
['hasData', 'getData', '__wakeup'],
[],
'',
false
);
$this->validator = new \Magento\Sales\Model\Order\Shipment\Comment\Validator();
}
/**
* Run test validate
*
* @param $commentDataMap
* @param $commentData
* @param $expectedWarnings
* @dataProvider providerCommentData
*/
public function testValidate($commentDataMap, $commentData, $expectedWarnings)
{
$this->commentModelMock->expects($this->any())
->method('hasData')
->will($this->returnValueMap($commentDataMap));
$this->commentModelMock->expects($this->once())
->method('getData')
->will($this->returnValue($commentData));
$actualWarnings = $this->validator->validate($this->commentModelMock);
$this->assertEquals($expectedWarnings, $actualWarnings);
}
/**
* Provides comment data for tests
*
* @return array
*/
public function providerCommentData()
{
return [
[
[
['parent_id', true],
['comment', true],
],
[
'parent_id' => 25,
'comment' => 'Hello world!'
],
[],
],
[
[
['parent_id', true],
['comment', false],
],
[
'parent_id' => 0,
'comment' => null
],
[
'parent_id' => 'Parent Shipment Id can not be empty',
'comment' => 'Comment is a required field'
]
]
];
}
}
| {
"content_hash": "245c3df18f0195270339497812cbe068",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 96,
"avg_line_length": 26.57777777777778,
"alnum_prop": 0.4778428093645485,
"repo_name": "tarikgwa/test",
"id": "fe56a9660c0a39aa2c4062a101ce94a59025a089",
"size": "2490",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "html/app/code/Magento/Sales/Test/Unit/Model/Order/Shipment/Comment/ValidatorTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "26588"
},
{
"name": "CSS",
"bytes": "4874492"
},
{
"name": "HTML",
"bytes": "8635167"
},
{
"name": "JavaScript",
"bytes": "6810903"
},
{
"name": "PHP",
"bytes": "55645559"
},
{
"name": "Perl",
"bytes": "7938"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
class IOSChromeMetricsServiceAccessorTest : public testing::Test {
public:
IOSChromeMetricsServiceAccessorTest() {
prefs_.registry()->RegisterBooleanPref(
metrics::prefs::kMetricsReportingEnabled, false);
TestingApplicationContext::GetGlobal()->SetLocalState(&prefs_);
}
PrefService* GetLocalState() { return &prefs_; }
private:
TestingPrefServiceSimple prefs_;
DISALLOW_COPY_AND_ASSIGN(IOSChromeMetricsServiceAccessorTest);
};
TEST_F(IOSChromeMetricsServiceAccessorTest, MetricsReportingEnabled) {
#if defined(GOOGLE_CHROME_BUILD)
const char* pref = metrics::prefs::kMetricsReportingEnabled;
GetLocalState()->SetDefaultPrefValue(pref, new base::FundamentalValue(false));
GetLocalState()->SetBoolean(pref, false);
EXPECT_FALSE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
GetLocalState()->SetBoolean(pref, true);
EXPECT_TRUE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
GetLocalState()->ClearPref(pref);
EXPECT_FALSE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
// If field trials are forced, metrics should always be disabled, regardless
// of the value of the pref.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kForceFieldTrials);
EXPECT_FALSE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
GetLocalState()->SetBoolean(pref, true);
EXPECT_FALSE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
#else
// Metrics Reporting is never enabled when GOOGLE_CHROME_BUILD is undefined.
EXPECT_FALSE(
IOSChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled());
#endif
}
| {
"content_hash": "a4bdc229c82dc1b7cc737cc8edd7ec8e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 80,
"avg_line_length": 37.58695652173913,
"alnum_prop": 0.7755928282244072,
"repo_name": "Workday/OpenFrame",
"id": "1d7a9d496c4c0d03cf3e9ad479699b7ea4a2f0eb",
"size": "2281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ios/chrome/browser/metrics/ios_chrome_metrics_service_accessor_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
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.
-->
<geronimo-plugin xmlns="http://geronimo.apache.org/xml/ns/plugins-1.3"
xmlns:ns2="http://geronimo.apache.org/xml/ns/attributes-1.2">
<name>Geronimo Configs :: J2EE System</name>
<category>Geronimo Core</category>
<description>Apache Geronimo, the JavaEE server project of the Apache Software Foundation.</description>
<url>http://geronimo.apache.org/</url>
<author>The Apache Geronimo development community</author>
<license osi-approved="true">The Apache Software License, Version 2.0</license>
<plugin-artifact>
<module-id>
<groupId>org.apache.geronimo.buildsupport.it</groupId>
<artifactId>j2ee-system</artifactId>
<version>2.2-TEST</version>
<type>car</type>
</module-id>
<dependency start="true">
<groupId>org.apache.geronimo.framework</groupId>
<artifactId>geronimo-common</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>org.apache.geronimo.framework</groupId>
<artifactId>geronimo-system</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>org.apache.geronimo.framework</groupId>
<artifactId>geronimo-crypto</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>asm</groupId>
<artifactId>asm-commons</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>jline</groupId>
<artifactId>jline</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>commons-jexl</groupId>
<artifactId>commons-jexl</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jaxb_2.1_spec</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-stax-api_1.0_spec</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>woodstox</groupId>
<artifactId>wstx-asl</artifactId>
<type>jar</type>
</dependency>
<dependency start="true">
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-activation_1.1_spec</artifactId>
<type>jar</type>
</dependency>
</plugin-artifact>
</geronimo-plugin>
| {
"content_hash": "f7d85b1c706b0c1439ef41daa4d08c39",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 108,
"avg_line_length": 40.85576923076923,
"alnum_prop": 0.610496587432337,
"repo_name": "apache/geronimo",
"id": "8549b8d84e2f3a23f9e77d585d4568db2566345c",
"size": "4249",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "framework/configs/geronimo-gbean-deployer/src/it/j2ee-system-it2/src/test/resources/META-INF/geronimo-plugin.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29627"
},
{
"name": "CSS",
"bytes": "47972"
},
{
"name": "HTML",
"bytes": "838469"
},
{
"name": "Java",
"bytes": "8975734"
},
{
"name": "JavaScript",
"bytes": "906"
},
{
"name": "Shell",
"bytes": "32814"
},
{
"name": "XSLT",
"bytes": "4468"
}
],
"symlink_target": ""
} |
package gov.hhs.fha.nhinc.mpi.adapter.proxy;
import gov.hhs.fha.nhinc.aspect.AdapterDelegationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.PRPAIN201305UV02EventDescriptionBuilder;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.PRPAIN201306UV02EventDescriptionBuilder;
import org.hl7.v3.PRPAIN201305UV02;
import org.hl7.v3.PRPAIN201306UV02;
/**
* NoOp Implementation for the AdapterMpi component proxy.
*
* @author Les Westberg
*/
public class AdapterMpiProxyNoOpImpl implements AdapterMpiProxy {
/**
* Find the matching candidates from the MPI.
*
* @param findCandidatesRequest
* The information to use for matching.
* @param assertion
* The assertion data.
* @return The matches that are found.
*/
@Override
@AdapterDelegationEvent(beforeBuilder = PRPAIN201305UV02EventDescriptionBuilder.class,
afterReturningBuilder = PRPAIN201306UV02EventDescriptionBuilder.class,
serviceType = "Patient Discovery MPI", version = "1.0")
public PRPAIN201306UV02 findCandidates(PRPAIN201305UV02 findCandidatesRequest, AssertionType assertion) {
return new PRPAIN201306UV02();
}
}
| {
"content_hash": "a33d20838b234ab84b9fbd737bc49fc6",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 109,
"avg_line_length": 37.05882352941177,
"alnum_prop": 0.746031746031746,
"repo_name": "sailajaa/CONNECT",
"id": "9cbcffe27342b4f29d478e80a0633149763f73d8",
"size": "2930",
"binary": false,
"copies": "3",
"ref": "refs/heads/CONNECT_integration",
"path": "Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/mpi/adapter/proxy/AdapterMpiProxyNoOpImpl.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5539"
},
{
"name": "Groovy",
"bytes": "1641"
},
{
"name": "Java",
"bytes": "12552183"
},
{
"name": "Python",
"bytes": "773"
},
{
"name": "Shell",
"bytes": "14607"
},
{
"name": "XSLT",
"bytes": "35057"
}
],
"symlink_target": ""
} |
package com.esotericsoftware.spine;
import com.badlogic.gdx.utils.Array;
public class SkeletonData {
String name;
final Array<BoneData> bones = new Array(); // Ordered parents first.
final Array<SlotData> slots = new Array(); // Setup pose draw order.
final Array<Skin> skins = new Array();
Skin defaultSkin;
final Array<EventData> events = new Array();
final Array<Animation> animations = new Array();
final Array<IkConstraintData> ikConstraints = new Array();
final Array<TransformConstraintData> transformConstraints = new Array();
float width, height;
String version, hash, imagesPath;
// --- Bones.
public Array<BoneData> getBones () {
return bones;
}
/** @return May be null. */
public BoneData findBone (String boneName) {
if (boneName == null) throw new IllegalArgumentException("boneName cannot be null.");
Array<BoneData> bones = this.bones;
for (int i = 0, n = bones.size; i < n; i++) {
BoneData bone = bones.get(i);
if (bone.name.equals(boneName)) return bone;
}
return null;
}
/** @return -1 if the bone was not found. */
public int findBoneIndex (String boneName) {
if (boneName == null) throw new IllegalArgumentException("boneName cannot be null.");
Array<BoneData> bones = this.bones;
for (int i = 0, n = bones.size; i < n; i++)
if (bones.get(i).name.equals(boneName)) return i;
return -1;
}
// --- Slots.
public Array<SlotData> getSlots () {
return slots;
}
/** @return May be null. */
public SlotData findSlot (String slotName) {
if (slotName == null) throw new IllegalArgumentException("slotName cannot be null.");
Array<SlotData> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++) {
SlotData slot = slots.get(i);
if (slot.name.equals(slotName)) return slot;
}
return null;
}
/** @return -1 if the bone was not found. */
public int findSlotIndex (String slotName) {
if (slotName == null) throw new IllegalArgumentException("slotName cannot be null.");
Array<SlotData> slots = this.slots;
for (int i = 0, n = slots.size; i < n; i++)
if (slots.get(i).name.equals(slotName)) return i;
return -1;
}
// --- Skins.
/** @return May be null. */
public Skin getDefaultSkin () {
return defaultSkin;
}
/** @param defaultSkin May be null. */
public void setDefaultSkin (Skin defaultSkin) {
this.defaultSkin = defaultSkin;
}
/** @return May be null. */
public Skin findSkin (String skinName) {
if (skinName == null) throw new IllegalArgumentException("skinName cannot be null.");
for (Skin skin : skins)
if (skin.name.equals(skinName)) return skin;
return null;
}
/** Returns all skins, including the default skin. */
public Array<Skin> getSkins () {
return skins;
}
// --- Events.
/** @return May be null. */
public EventData findEvent (String eventDataName) {
if (eventDataName == null) throw new IllegalArgumentException("eventDataName cannot be null.");
for (EventData eventData : events)
if (eventData.name.equals(eventDataName)) return eventData;
return null;
}
public Array<EventData> getEvents () {
return events;
}
// --- Animations.
public Array<Animation> getAnimations () {
return animations;
}
/** @return May be null. */
public Animation findAnimation (String animationName) {
if (animationName == null) throw new IllegalArgumentException("animationName cannot be null.");
Array<Animation> animations = this.animations;
for (int i = 0, n = animations.size; i < n; i++) {
Animation animation = animations.get(i);
if (animation.name.equals(animationName)) return animation;
}
return null;
}
// --- IK constraints
public Array<IkConstraintData> getIkConstraints () {
return ikConstraints;
}
/** @return May be null. */
public IkConstraintData findIkConstraint (String constraintName) {
if (constraintName == null) throw new IllegalArgumentException("constraintName cannot be null.");
Array<IkConstraintData> ikConstraints = this.ikConstraints;
for (int i = 0, n = ikConstraints.size; i < n; i++) {
IkConstraintData constraint = ikConstraints.get(i);
if (constraint.name.equals(constraintName)) return constraint;
}
return null;
}
// --- Transform constraints
public Array<TransformConstraintData> getTransformConstraints () {
return transformConstraints;
}
/** @return May be null. */
public TransformConstraintData findTransformConstraint (String constraintName) {
if (constraintName == null) throw new IllegalArgumentException("constraintName cannot be null.");
Array<TransformConstraintData> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.size; i < n; i++) {
TransformConstraintData constraint = transformConstraints.get(i);
if (constraint.name.equals(constraintName)) return constraint;
}
return null;
}
// ---
/** @return May be null. */
public String getName () {
return name;
}
/** @param name May be null. */
public void setName (String name) {
this.name = name;
}
public float getWidth () {
return width;
}
public void setWidth (float width) {
this.width = width;
}
public float getHeight () {
return height;
}
public void setHeight (float height) {
this.height = height;
}
/** Returns the Spine version used to export this data, or null. */
public String getVersion () {
return version;
}
/** @param version May be null. */
public void setVersion (String version) {
this.version = version;
}
/** @return May be null. */
public String getHash () {
return hash;
}
/** @param hash May be null. */
public void setHash (String hash) {
this.hash = hash;
}
/** @return May be null. */
public String getImagesPath () {
return imagesPath;
}
/** @param imagesPath May be null. */
public void setImagesPath (String imagesPath) {
this.imagesPath = imagesPath;
}
public String toString () {
return name != null ? name : super.toString();
}
}
| {
"content_hash": "86b195f01df8b0678d63a92bc537905e",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 99,
"avg_line_length": 26.556053811659194,
"alnum_prop": 0.6862546437014522,
"repo_name": "piotr-j/VisEditor",
"id": "4914ebeb0994276114803379be983e7694c8e9f8",
"size": "7768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/vis-runtime-spine/src/main/java/com/esotericsoftware/spine/SkeletonData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "4167"
},
{
"name": "Java",
"bytes": "3008310"
},
{
"name": "Kotlin",
"bytes": "15639"
}
],
"symlink_target": ""
} |
package com.stulsoft.pjava.basics.regex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Parser for MongoDB connection string
*
* @author Yuriy Stul
*/
public class MongodbConnectionStringParser {
private static final Logger logger = LoggerFactory.getLogger(MongodbConnectionStringParser.class);
private static final Pattern connectionStringPattern = Pattern.compile("^mongodb://(.*)@(.*)");
public static void main(String[] args) {
logger.info("==>main");
test1();
test2();
test3();
test4();
}
private static void test1() {
logger.info("==>test1");
try {
MongoConnection mongoConnection = MongoConnection.create("mongodb://user:pass@host1:1234,host2:1234");
logger.info("{}", mongoConnection);
} catch (Exception exception) {
logger.error(exception.getMessage());
}
}
private static void test2() {
logger.info("==>test2");
try {
MongoConnection mongoConnection = MongoConnection.create("mongodb://user:pass@host1:1234");
logger.info("{}", mongoConnection);
} catch (Exception exception) {
logger.error(exception.getMessage());
}
}
private static void test3() {
logger.info("==>test3");
var connectionString = "mon222godb://user:pass@host1:1234";
try {
MongoConnection mongoConnection = MongoConnection.create(connectionString);
logger.info("{}", mongoConnection);
} catch (Exception exception) {
logger.error(exception.getMessage() + ": " + connectionString);
}
}
private static void test4() {
logger.info("==>test3");
var connectionString = "mongodb://user:pass@host1!!!1234";
try {
MongoConnection mongoConnection = MongoConnection.create(connectionString);
logger.info("{}", mongoConnection);
} catch (Exception exception) {
logger.error(exception.getMessage() + ": " + connectionString);
}
}
static class MongoCredentials {
private final String username;
private final String password;
public MongoCredentials(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "MongoCredential{" +
"username='" + getUsername() + '\'' +
", password='" + getPassword() + '\'' +
'}';
}
}
static class MongoServerAddress {
private final String host;
private final int port;
public MongoServerAddress(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public String toString() {
return "MongoServerAddress{" +
"host='" + host + '\'' +
", port=" + port +
'}';
}
}
static class MongoConnection {
private final MongoCredentials mongoCredentials;
private final List<MongoServerAddress> mongoServerAddressList;
private MongoConnection(MongoCredentials mongoCredentials, List<MongoServerAddress> mongoServerAddressList) {
this.mongoCredentials = mongoCredentials;
this.mongoServerAddressList = mongoServerAddressList;
}
public static MongoConnection create(final String connectionString) throws IllegalArgumentException {
try {
var matcher = connectionStringPattern.matcher(connectionString);
if (matcher.find()) {
if (matcher.groupCount() == 2) {
MongoCredentials mongoCredentials;
var usernameAndPass = matcher.group(1).split(":");
if (usernameAndPass.length != 2) {
var errMsg = "Wrong format: invalid credentials";
throw new IllegalArgumentException(errMsg);
} else {
mongoCredentials = new MongoCredentials(usernameAndPass[0], usernameAndPass[1]);
}
var serverAddresses = new ArrayList<MongoServerAddress>();
var hostsAndPorts = matcher.group(2).split(",");
for (var hostAndPortItem : hostsAndPorts) {
var hostAndPort = hostAndPortItem.split(":");
if (hostAndPort.length == 2) {
serverAddresses.add(new MongoServerAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
} else {
throw new IllegalArgumentException("Wrong format: invalid hosts");
}
}
return new MongoConnection(mongoCredentials, serverAddresses);
} else {
throw new IllegalArgumentException("Wrong format");
}
} else {
throw new IllegalArgumentException("Wrong format");
}
} catch (Exception exception) {
logger.error(exception.getMessage());
throw new IllegalArgumentException(exception.getMessage());
}
}
public MongoCredentials getMongoCredentials() {
return mongoCredentials;
}
public List<MongoServerAddress> getMongoServerAddressList() {
return mongoServerAddressList;
}
@Override
public String toString() {
return "MongoConnection{" +
"mongoCredentials=" + getMongoCredentials() +
", mongoServerAddressList=" + getMongoServerAddressList() +
'}';
}
}
}
| {
"content_hash": "0e411dc35464930632c8071c09e1576b",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 126,
"avg_line_length": 35.18539325842696,
"alnum_prop": 0.5487785406354782,
"repo_name": "ysden123/ys-pjava",
"id": "1b72b68d7463cdd7b6cbc10faf90725457cd9616",
"size": "6303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "basics/src/main/java/com/stulsoft/pjava/basics/regex/MongodbConnectionStringParser.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "351"
},
{
"name": "Java",
"bytes": "255575"
},
{
"name": "Kotlin",
"bytes": "2205"
}
],
"symlink_target": ""
} |
module.exports.getTitle = (frontMatterTitle) => {
return `${frontMatterTitle} | Cypress Documentation`
}
| {
"content_hash": "ac180a05e632d61365f1f6bc28836fbf",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 54,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.7383177570093458,
"repo_name": "cypress-io/cypress-documentation",
"id": "38f328030bf0306787aa59c57e282b6978012d66",
"size": "107",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utils/getTitle.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7417"
},
{
"name": "JavaScript",
"bytes": "115450"
},
{
"name": "Shell",
"bytes": "58"
},
{
"name": "Vue",
"bytes": "94470"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../ncollide_geometry/shape/struct.Torus.html">
</head>
<body>
<p>Redirecting to <a href="../../../ncollide_geometry/shape/struct.Torus.html">../../../ncollide_geometry/shape/struct.Torus.html</a>...</p>
<script>location.replace("../../../ncollide_geometry/shape/struct.Torus.html" + location.search + location.hash);</script>
</body>
</html> | {
"content_hash": "0bae3c29cefb9542a9e243e6996f79b3",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 144,
"avg_line_length": 44.1,
"alnum_prop": 0.6575963718820862,
"repo_name": "nitro-devs/nitro-game-engine",
"id": "45ed40f5a2e1def7df75d07679d0d713b8685d40",
"size": "441",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/ncollide_geometry/shape/torus/struct.Torus.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CMake",
"bytes": "1032"
},
{
"name": "Rust",
"bytes": "59380"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<Socket name="LOGSTASH" host="logstash" port="5001">
<JsonLayout properties="true"/>
</Socket>
</Appenders>
<Loggers>
<Logger name="org.openkilda.wfm.simulator" level="warn" additivity="false">
<AppenderRef ref="STDOUT"/>
<AppenderRef ref="LOGSTASH"/>
</Logger>
<Root level="DEBUG">
<AppenderRef ref="STDOUT"/>
<AppenderRef ref="LOGSTASH"/>
</Root>
</Loggers>
</Configuration>
| {
"content_hash": "b92be585299c6d7221d558ad01ef9a7b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 86,
"avg_line_length": 35.285714285714285,
"alnum_prop": 0.5560053981106613,
"repo_name": "carmine/open-kilda",
"id": "636e9f04c5cff8d279088e1146976fb40e142836",
"size": "741",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "services/wfm/src/main/resources/log4j2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "43802"
},
{
"name": "Gherkin",
"bytes": "60014"
},
{
"name": "Groovy",
"bytes": "243"
},
{
"name": "HTML",
"bytes": "64303"
},
{
"name": "Java",
"bytes": "2710769"
},
{
"name": "JavaScript",
"bytes": "115618"
},
{
"name": "Makefile",
"bytes": "23037"
},
{
"name": "Python",
"bytes": "369980"
},
{
"name": "Ruby",
"bytes": "1185"
},
{
"name": "Shell",
"bytes": "76773"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/arizona/st-johns-arizona-usa" xmlns:sem="http://marklogic.com/semantics">
<sem:triple>
<sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/arizona/st-johns-arizona-usa</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
<sem:object datatype="xsd:string" xml:lang="eng">St. Johns (Arizona, USA)</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/arizona/st-johns-arizona-usa</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
<sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/arizona/st-johns-arizona-usa</sem:subject>
<sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
<sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
</sem:triple>
</sem:triples>
| {
"content_hash": "04058e25fd314194a03fb32e70d0180e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 181,
"avg_line_length": 70.16666666666667,
"alnum_prop": 0.733174980205859,
"repo_name": "freshie/ml-taxonomies",
"id": "24cf8496fc41ee9052eb79574d2282eb94dc9844",
"size": "1263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/geo-political/north-america-and-caribbean/united-states-of-america/arizona/st-johns-arizona-usa.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4422"
},
{
"name": "CSS",
"bytes": "38665"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "411651"
},
{
"name": "Ruby",
"bytes": "259121"
},
{
"name": "Shell",
"bytes": "7329"
},
{
"name": "XQuery",
"bytes": "857170"
},
{
"name": "XSLT",
"bytes": "13753"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4a49551884f9f99edc54afc35047d086",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "c63b5945b332eca0bccaf07fc701e55be7dab21d",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Silene/Silene caryophylloides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
id: 587d7b84367417b2b2512b35
title: Catch Misspelled Variable and Function Names
challengeType: 1
forumTopicId: 301186
dashedName: catch-misspelled-variable-and-function-names
---
# --description--
The `console.log()` and `typeof` methods are the two primary ways to check intermediate values and types of program output. Now it's time to get into the common forms that bugs take. One syntax-level issue that fast typers can commiserate with is the humble spelling error.
Transposed, missing, or mis-capitalized characters in a variable or function name will have the browser looking for an object that doesn't exist - and complain in the form of a reference error. JavaScript variable and function names are case-sensitive.
# --instructions--
Fix the two spelling errors in the code so the `netWorkingCapital` calculation works.
# --hints--
Check the spelling of the two variables used in the netWorkingCapital calculation, the console output should show that "Net working capital is: 2".
```js
assert(netWorkingCapital === 2);
```
There should be no instances of mis-spelled variables in the code.
```js
assert(!code.match(/recievables/g));
```
The `receivables` variable should be declared and used properly in the code.
```js
assert(code.match(/receivables/g).length == 2);
```
There should be no instances of mis-spelled variables in the code.
```js
assert(!code.match(/payable;/g));
```
The `payables` variable should be declared and used properly in the code.
```js
assert(code.match(/payables/g).length == 2);
```
# --seed--
## --seed-contents--
```js
let receivables = 10;
let payables = 8;
let netWorkingCapital = recievables - payable;
console.log(`Net working capital is: ${netWorkingCapital}`);
```
# --solutions--
```js
let receivables = 10;
let payables = 8;
let netWorkingCapital = receivables - payables;
console.log(`Net working capital is: ${netWorkingCapital}`);
```
| {
"content_hash": "fe254217b1abf418c884920c3f176299",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 273,
"avg_line_length": 28.058823529411764,
"alnum_prop": 0.7463312368972747,
"repo_name": "FreeCodeCamp/FreeCodeCamp",
"id": "cdadad853493779657f3e8a7d67b27b5f701208f",
"size": "1912",
"binary": false,
"copies": "2",
"ref": "refs/heads/i18n-sync-client",
"path": "curriculum/challenges/english/02-javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "190263"
},
{
"name": "HTML",
"bytes": "160430"
},
{
"name": "JavaScript",
"bytes": "546299"
}
],
"symlink_target": ""
} |
extern std::string DEVELOPER_NAME;
extern std::string APPLICATION_NAME;
static char TEMP_BUFFER[1024];
namespace ouzel
{
FileSystemRasp::FileSystemRasp()
{
if (readlink("/proc/self/exe", TEMP_BUFFER, sizeof(TEMP_BUFFER)) != -1)
{
appPath = getDirectoryPart(TEMP_BUFFER);
}
else
{
Log(Log::Level::ERR) << "Failed to get current directory";
}
}
std::string FileSystemRasp::getStorageDirectory(bool user) const
{
std::string path;
passwd* pw = getpwuid(getuid());
if (!pw)
{
Log(Log::Level::ERR) << "Failed to get home directory";
return "";
}
path = pw->pw_dir;
path += DIRECTORY_SEPARATOR + "." + DEVELOPER_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
path += DIRECTORY_SEPARATOR + APPLICATION_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
return path;
}
std::string FileSystemRasp::getTempDirectory() const
{
char const* path = getenv("TMPDIR");
if (path)
{
return path;
}
else
{
return "/tmp";
}
}
}
| {
"content_hash": "da96441d9d188ec88c3dc795684ac994",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 80,
"avg_line_length": 24.028985507246375,
"alnum_prop": 0.4794933655006031,
"repo_name": "Hotspotmar/ouzel",
"id": "c37cad5b62dedc112f7376f968bd01ba94de8c03",
"size": "1851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ouzel/files/raspbian/FileSystemRasp.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "590"
},
{
"name": "C",
"bytes": "344043"
},
{
"name": "C++",
"bytes": "1518302"
},
{
"name": "GLSL",
"bytes": "4080"
},
{
"name": "HLSL",
"bytes": "1752"
},
{
"name": "Makefile",
"bytes": "21835"
},
{
"name": "Metal",
"bytes": "2702"
},
{
"name": "Objective-C",
"bytes": "123351"
},
{
"name": "Objective-C++",
"bytes": "263746"
},
{
"name": "Shell",
"bytes": "5619"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe SerializeHasMany::Validators::TypeValidator do
subject do
described_class.new(attr_name: :children, child_class: OpenStruct)
end
it 'should allow nil' do
record = TestParentModel.new(children: nil)
subject.validate record
expect(record.errors).to be_empty
end
it 'should allow empty array' do
record = TestParentModel.new(children: [])
subject.validate record
expect(record.errors).to be_empty
end
it 'should allow items with nil' do
record = TestParentModel.new(children: [nil, nil, nil])
subject.validate record
expect(record.errors).to be_empty
end
it 'should allow items with correct data type' do
record = TestParentModel.new(children: [OpenStruct.new, OpenStruct.new, OpenStruct.new])
subject.validate record
expect(record.errors).to be_empty
end
it 'should not allow primitives' do
record = TestParentModel.new(children: '')
subject.validate record
expect(record.errors[:children]).to include /is not an array/
end
it 'should not allow hash' do
record = TestParentModel.new(children: {})
subject.validate record
expect(record.errors[:children]).to include /is not an array/
end
it 'should not items with wrong data type' do
record = TestParentModel.new(children: [ {}, '', 1 ])
subject.validate record
expect(record.errors[:children].count).to be 3
expect(record.errors[:children].uniq.first).to match /is not of type/
end
end
| {
"content_hash": "54ec2b155fe660d72736c1257bb5f020",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 92,
"avg_line_length": 29.94,
"alnum_prop": 0.7100868403473614,
"repo_name": "rdsubhas/serialize_has_many",
"id": "7650acac18c85a091713628c9b18dd2aa5d80135",
"size": "1497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/serialize_has_many/validators/type_validator_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1713"
},
{
"name": "HTML",
"bytes": "7475"
},
{
"name": "JavaScript",
"bytes": "667"
},
{
"name": "Ruby",
"bytes": "40986"
}
],
"symlink_target": ""
} |
<?php
require 'template/header.php';
require 'template/index_body.php';
require 'template/footer.php';
?> | {
"content_hash": "a780b4894e8029f9412c22a71d8c1519",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 35,
"avg_line_length": 21.6,
"alnum_prop": 0.7222222222222222,
"repo_name": "OverStruck/memenaitor",
"id": "a0adc6aab380211f1b94ab456bf056e78c04166e",
"size": "108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2068"
},
{
"name": "JavaScript",
"bytes": "4992"
},
{
"name": "PHP",
"bytes": "3152"
}
],
"symlink_target": ""
} |
package org.eclipse.collections.impl.map.immutable.primitive;
import org.eclipse.collections.impl.factory.primitive.ObjectBooleanMaps;
import org.eclipse.collections.impl.map.mutable.primitive.ObjectBooleanHashMap;
import org.junit.Assert;
import org.junit.Test;
public class ImmutableObjectBooleanMapFactoryImplTest
{
@Test
public void of()
{
Assert.assertEquals(new ObjectBooleanHashMap<String>().toImmutable(), ObjectBooleanMaps.immutable.of());
Assert.assertEquals(ObjectBooleanHashMap.newWithKeysValues("1", true).toImmutable(), ObjectBooleanMaps.immutable.of("1", true));
}
@Test
public void with()
{
Assert.assertEquals(ObjectBooleanHashMap.newWithKeysValues("1", true).toImmutable(), ObjectBooleanMaps.immutable.with("1", true));
}
@Test
public void ofAll()
{
Assert.assertEquals(new ObjectBooleanHashMap().toImmutable(), ObjectBooleanMaps.immutable.ofAll(ObjectBooleanMaps.immutable.of()));
}
@Test
public void withAll()
{
Assert.assertEquals(new ObjectBooleanHashMap().toImmutable(), ObjectBooleanMaps.immutable.withAll(ObjectBooleanMaps.immutable.of()));
}
}
| {
"content_hash": "132912b18c54527a8496bf7e891e7a0d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 141,
"avg_line_length": 32.80555555555556,
"alnum_prop": 0.7366638441998307,
"repo_name": "bhav0904/eclipse-collections",
"id": "ed0a6863eb3217c520df530e9d2ac79ab149c70b",
"size": "1640",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "unit-tests/src/test/java/org/eclipse/collections/impl/map/immutable/primitive/ImmutableObjectBooleanMapFactoryImplTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "14227"
},
{
"name": "Java",
"bytes": "13221126"
},
{
"name": "Scala",
"bytes": "154482"
},
{
"name": "Shell",
"bytes": "1062"
}
],
"symlink_target": ""
} |
import logging
from django.contrib.contenttypes.models import ContentType
from django.db.models import CASCADE
from django.db.models.signals import post_save, post_delete
from river.core.riverobject import RiverObject
from river.core.workflowregistry import workflow_registry
from river.models import OnApprovedHook, OnTransitHook, OnCompleteHook
try:
from django.contrib.contenttypes.fields import GenericRelation
except ImportError:
from django.contrib.contenttypes.generic import GenericRelation
from river.models.state import State
from river.models.transitionapproval import TransitionApproval
from river.models.transition import Transition
from django.db import models
LOGGER = logging.getLogger(__name__)
class classproperty(object):
def __init__(self, getter):
self.getter = getter
def __get__(self, instance, owner):
return self.getter(instance) if instance else self.getter(owner)
class StateField(models.ForeignKey):
def __init__(self, *args, **kwargs):
self.field_name = None
kwargs['null'] = True
kwargs['blank'] = True
kwargs['to'] = '%s.%s' % (State._meta.app_label, State._meta.object_name)
kwargs['on_delete'] = kwargs.get('on_delete', CASCADE)
kwargs['related_name'] = "+"
super(StateField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name, *args, **kwargs):
@classproperty
def river(_self):
return RiverObject(_self)
self.field_name = name
self._add_to_class(cls, self.field_name + "_transition_approvals",
GenericRelation('%s.%s' % (TransitionApproval._meta.app_label, TransitionApproval._meta.object_name)))
self._add_to_class(cls, self.field_name + "_transitions", GenericRelation('%s.%s' % (Transition._meta.app_label, Transition._meta.object_name)))
if id(cls) not in workflow_registry.workflows:
self._add_to_class(cls, "river", river)
super(StateField, self).contribute_to_class(cls, name, *args, **kwargs)
if id(cls) not in workflow_registry.workflows:
post_save.connect(_on_workflow_object_saved, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
post_delete.connect(_on_workflow_object_deleted, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
workflow_registry.add(self.field_name, cls)
@staticmethod
def _add_to_class(cls, key, value, ignore_exists=False):
if ignore_exists or not hasattr(cls, key):
cls.add_to_class(key, value)
def _on_workflow_object_saved(sender, instance, created, *args, **kwargs):
for instance_workflow in instance.river.all(instance.__class__):
if created:
instance_workflow.initialize_approvals()
if not instance_workflow.get_state():
init_state = getattr(instance.__class__.river, instance_workflow.field_name).initial_state
instance_workflow.set_state(init_state)
instance.save()
def _on_workflow_object_deleted(sender, instance, *args, **kwargs):
OnApprovedHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
OnTransitHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
OnCompleteHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
| {
"content_hash": "8275c161c0ae2cd41709cb8df1a1a058",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 152,
"avg_line_length": 42.55952380952381,
"alnum_prop": 0.686993006993007,
"repo_name": "javrasya/django-river",
"id": "02c30ea4b522b6f1d95c5c2403e29d77b381db02",
"size": "3575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "river/models/fields/state.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Gherkin",
"bytes": "15065"
},
{
"name": "Python",
"bytes": "254833"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
package com.shaubert.ui.dialogs;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
class Keyboard {
public static void hideKeyboard(Activity activity) {
hideKeyboard(activity.getCurrentFocus());
}
public static void hideKeyboard(View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}
}
public static void showKeyboard(final View view, Handler handler) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
showKeyboard(view);
}
}, 500);
}
public static void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
public static void showKeyboardForced(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
| {
"content_hash": "239fe7d152b46189a483b157e3d20e68",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 123,
"avg_line_length": 34.926829268292686,
"alnum_prop": 0.6899441340782123,
"repo_name": "shaubert/dialogs",
"id": "d2f4c46b777f0c09abc0999b96797bcbdbf11808",
"size": "1432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/src/main/java/com/shaubert/ui/dialogs/Keyboard.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "39"
},
{
"name": "Java",
"bytes": "63283"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b8564cf188bc44454adde7a9c6c445af",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "fc07640274d2bf051e31b277c6f0dd99d61f63c9",
"size": "204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium dentatum/ Syn. Hieracium dentatum tigridinaevum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.desklampstudios.thyroxine.news.provider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.util.Log;
import static com.desklampstudios.thyroxine.news.provider.NewsContract.NewsEntries;
class NewsDatabase extends SQLiteOpenHelper {
private static final String TAG = NewsDatabase.class.getSimpleName();
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "thyroxine.db.news";
// NewsEntry table
interface Tables {
String TABLE_NEWSENTRIES = "newsEntries";
}
public NewsDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
final String SQL_CREATE_NEWSENTRIES_TABLE =
"CREATE TABLE " + Tables.TABLE_NEWSENTRIES + " (" +
NewsEntries._ID + " INTEGER PRIMARY KEY, " +
NewsEntries.KEY_NEWS_ID + " INTEGER NOT NULL, " +
NewsEntries.KEY_TITLE + " TEXT, " +
NewsEntries.KEY_PUBLISHED + " INTEGER NOT NULL, " +
NewsEntries.KEY_CONTENT + " TEXT, " +
NewsEntries.KEY_CONTENT_SNIPPET + " TEXT, " +
NewsEntries.KEY_LIKED + " INTEGER, " +
NewsEntries.KEY_NUM_LIKES + " INTEGER" +
");";
Log.d(TAG, "Creating newsEntries table: "+ SQL_CREATE_NEWSENTRIES_TABLE);
db.execSQL(SQL_CREATE_NEWSENTRIES_TABLE);
}
@Override
public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrading from "+ oldVersion + " to " + newVersion);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_NEWSENTRIES);
this.onCreate(db);
}
} | {
"content_hash": "5719a63b272f472799a4b98ddcd93e97",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 87,
"avg_line_length": 39.46,
"alnum_prop": 0.6254434870755196,
"repo_name": "gengkev/thyroxine",
"id": "8c89ad342b0958bc356ead744eb2f872b0d80fc1",
"size": "1973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/desklampstudios/thyroxine/news/provider/NewsDatabase.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "293534"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml" th:fragment="header">
<header id="header" class="">
<div class="container">
<a href="/addon-administration" th:href="@{/}"><h1>Administration</h1></a>
<div id="logo">
<img src="../../img/osiam_logo.png" th:src="@{/img/osiam_logo.png}" alt="OSIAM Logo" width="150px"/>
</div>
<ul style="width: 50%;" th:if="${isLoggedIn}">
<!-- Please write <li>s next to each other (not in separate lines) as it prevents a layout bug in FF -->
<li>
<a id="userListLink" href="user/list.html" th:href="@{/admin/user/list}" th:text="#{msg.list.userList}">User List</a>
</li>
<li>
<a id="groupListLink" href="group/list.html" th:href="@{/admin/group/list}" th:text="#{msg.list.groupList}">Group List</a>
</li>
</ul>
</div>
</header>
<div class="topbar"></div>
</html>
| {
"content_hash": "1e41af5edc16ca19b3210d279f8824f1",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 138,
"avg_line_length": 39.96,
"alnum_prop": 0.5495495495495496,
"repo_name": "osiam/addon-administration",
"id": "3634638a1c116a88dd0ddbbfcbf43baa7a6b875a",
"size": "999",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/resources/templates/header.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6511"
},
{
"name": "Groovy",
"bytes": "3679"
},
{
"name": "HTML",
"bytes": "148610"
},
{
"name": "Java",
"bytes": "222248"
},
{
"name": "JavaScript",
"bytes": "14724"
}
],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "6ecfd001fd43b53ae45f7749329d5435",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 60,
"avg_line_length": 19.5,
"alnum_prop": 0.7863247863247863,
"repo_name": "genterist/whiteWolf",
"id": "5031606f0f1d62037e8999d17209c354465f70e2",
"size": "248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Matt_UI_Code/All_Code/whitewolfdemo-ObjC/whitewolfdemo/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "249864"
},
{
"name": "HTML",
"bytes": "55828"
},
{
"name": "JavaScript",
"bytes": "64781"
},
{
"name": "Objective-C",
"bytes": "1981511"
},
{
"name": "PHP",
"bytes": "4000"
},
{
"name": "Ruby",
"bytes": "3308"
},
{
"name": "Swift",
"bytes": "15797"
}
],
"symlink_target": ""
} |
<?php
//----------------------------------------------------------------------------
// This software is licensed under the MIT license. Use as you wish but give
// and take credit where due.
//
// Author: Paul Lemmons
//----------------------------------------------------------------------------
?>
<?php
include 'include/RegFunctions.php';
if ($Admin != 'Y')
{
header("refresh: 0; URL=Admin.php");
die();
}
if (isset($_POST['Reports']))
{
$db->query("update $UsersTable
set Status = 'R'
where Admin = 'N'
and Status != 'L'
")
or die ("Unable to lock users".sqlError());
}
else if (isset($_POST['Lock']))
{
$db->query("update $UsersTable
set Status = 'L'
where Admin = 'N'
")
or die ("Unable to lock users".sqlError());
}
else if (isset($_POST['Unlock']))
{
$db->query("update $UsersTable
set Status = 'O'
where Admin = 'N'
")
or die ("Unable to lock users".sqlError());
}
else if (isset($_POST['Open']))
{
$db->query("update $UsersTable
set Status = 'O'
where Admin = 'N'
and Status != 'L'
")
or die ("Unable to lock users".sqlError());
}
else if (isset($_POST['Close']))
{
$db->query("update $UsersTable
set Status = 'C'
where Admin = 'N'
and Status != 'L'
")
or die ("Unable to lock users".sqlError());
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en-us" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="include/registration.css" type="text/css" />
<title>Lock or Unlock Registration</title>
</head>
<body>
<h1 align="center">Open or Close Registration </h1>
<?php
if (isset($_POST['Lock']))
{
print "<h3 align='center'><font color=\"#FF0000\">All non-administrative users have been locked</font></h3>";
}
else if (isset($_POST['Unlock']))
{
print "<h3 align='center'><font color=\"#FF0000\">All non-administrative users have been unlocked</font></h3>";
}
else if (isset($_POST['Open']))
{
print "<h3 align='center'><font color=\"#FF0000\">Registration is opened</font></h3>";
print "<h3 align='center'><font color=\"#FF0000\">All unlocked users may now register new participants</font></h3>";
}
else if (isset($_POST['Close']))
{
print "<h3 align='center'><font color=\"#FF0000\">Registration is closed</font></h3>";
print "<h3 align='center'><font color=\"#FF0000\">Only Administrative users may now add new participants</font></h3>";
}
?>
<form method="post">
<?php
$results = $db->query("select Userid,
ChurchID,
Name,
Admin,
Status
from $UsersTable
Order by ChurchID,
Userid")
or die ("Unable to get user list:" . sqlError());
?>
<table class='registrationTable'>
<tr>
<th style='text-align:left'>Userid</th>
<th>User Name</th>
<th>Church Name</th>
<th>Administrator</th>
<th>Status</th>
</tr>
<?php
while ($row = $results->fetch(PDO::FETCH_ASSOC))
{
$chResult = $db->query("select ChurchName
from $ChurchesTable
where ChurchID = ".$row['ChurchID']
)
or die ("Unable to get Church Name:" . sqlError());
$chRow = $chResult->fetch(PDO::FETCH_ASSOC);
$ChurchName = $chRow['ChurchName'];
if ($row['Status'] == 'O')
{
$row['Status'] = 'Open';
}
else if ($row['Status'] == 'C')
{
$row['Status'] = 'Closed';
}
else if ($row['Status'] == 'L')
{
$row['Status'] = 'Locked';
}
else if ($row['Status'] == 'R')
{
$row['Status'] = 'Report Only';
}
else
{
$row['Status'] = 'Unknown';
}
?>
<tr>
<td style='text-align:left'><?php print $row['Userid']; ?></td>
<td><?php print $row['Name']; ?></td>
<td><?php print $ChurchName; ?></td>
<td style='text-align: center'><?php print $row['Admin']; ?></td>
<td style='text-align: center'><?php print $row['Status']; ?></td>
</tr>
<?php
}
?>
</table>
<p align="center">
<input type="submit" value="Close Registration" name="Close" />
<input type="submit" value="Open Registration" name="Open" />
</p>
<p align="center">
<input type="submit" value="Lock Users" name="Lock" />
<input type="submit" value="Unlock Users" name="Unlock" />
</p>
<p align="center">
<input type="submit" value="Reports Only" name="Reports" />
</p>
</form>
<?php footer("","")?>
</body>
</html> | {
"content_hash": "27de6ce4987c1a4bc206a63c8e037422",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 121,
"avg_line_length": 32.2183908045977,
"alnum_prop": 0.45397788084195506,
"repo_name": "poetimp/ltcsw",
"id": "5db02591cde41fd785c46a9504a6dfc8005ccd62",
"size": "5606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "registration/LockRegistration.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1592"
},
{
"name": "HTML",
"bytes": "2336"
},
{
"name": "JavaScript",
"bytes": "6124"
},
{
"name": "PHP",
"bytes": "857425"
}
],
"symlink_target": ""
} |
// snippet-sourcedescription:[ListAndPurchaseReservedNodeOffering demonstrates how to list and purchase Amazon Redshift reserved node offerings.]
// snippet-service:[redshift]
// snippet-keyword:[Java]
// snippet-sourcesyntax:[java]
// snippet-keyword:[Amazon Redshift]
// snippet-keyword:[Code Sample]
// snippet-keyword:[DescribeReservedNodeOfferings]
// snippet-keyword:[PurchaseReservedNodeOffering]
// snippet-keyword:[ReservedNode]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2019-01-31]
// snippet-sourceauthor:[AWS]
// snippet-start:[redshift.java.ListAndPurchaseReservedNodeOffering.complete]
package com.amazonaws.services.redshift;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.amazonaws.services.redshift.model.*;
public class ListAndPurchaseReservedNodeOffering {
public static AmazonRedshift client;
public static String nodeTypeToPurchase = "dc2.large";
public static Double fixedPriceLimit = 10000.00;
public static ArrayList<ReservedNodeOffering> matchingNodes = new ArrayList<ReservedNodeOffering>();
public static void main(String[] args) throws IOException {
// Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain}
client = AmazonRedshiftClientBuilder.defaultClient();
try {
listReservedNodes();
findReservedNodeOffer();
purchaseReservedNodeOffer();
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
private static void listReservedNodes() {
DescribeReservedNodesResult result = client.describeReservedNodes();
System.out.println("Listing nodes already purchased.");
for (ReservedNode node : result.getReservedNodes()) {
printReservedNodeDetails(node);
}
}
private static void findReservedNodeOffer()
{
DescribeReservedNodeOfferingsRequest request = new DescribeReservedNodeOfferingsRequest();
DescribeReservedNodeOfferingsResult result = client.describeReservedNodeOfferings(request);
Integer count = 0;
System.out.println("\nFinding nodes to purchase.");
for (ReservedNodeOffering offering : result.getReservedNodeOfferings())
{
if (offering.getNodeType().equals(nodeTypeToPurchase)){
if (offering.getFixedPrice() < fixedPriceLimit) {
matchingNodes.add(offering);
printOfferingDetails(offering);
count +=1;
}
}
}
if (count == 0) {
System.out.println("\nNo reserved node offering matches found.");
} else {
System.out.println("\nFound " + count + " matches.");
}
}
private static void purchaseReservedNodeOffer() throws IOException {
if (matchingNodes.size() == 0) {
return;
} else {
System.out.println("\nPurchasing nodes.");
for (ReservedNodeOffering offering : matchingNodes) {
printOfferingDetails(offering);
System.out.println("WARNING: purchasing this offering will incur costs.");
System.out.println("Purchase this offering [Y or N]?");
DataInput in = new DataInputStream(System.in);
String purchaseOpt = in.readLine();
if (purchaseOpt.equalsIgnoreCase("y")){
try {
PurchaseReservedNodeOfferingRequest request = new PurchaseReservedNodeOfferingRequest()
.withReservedNodeOfferingId(offering.getReservedNodeOfferingId());
ReservedNode reservedNode = client.purchaseReservedNodeOffering(request);
printReservedNodeDetails(reservedNode);
}
catch (ReservedNodeAlreadyExistsException ex1){
}
catch (ReservedNodeOfferingNotFoundException ex2){
}
catch (ReservedNodeQuotaExceededException ex3){
}
catch (Exception ex4){
}
}
}
System.out.println("Finished.");
}
}
private static void printOfferingDetails(
ReservedNodeOffering offering) {
System.out.println("\nOffering Match:");
System.out.format("Id: %s\n", offering.getReservedNodeOfferingId());
System.out.format("Node Type: %s\n", offering.getNodeType());
System.out.format("Fixed Price: %s\n", offering.getFixedPrice());
System.out.format("Offering Type: %s\n", offering.getOfferingType());
System.out.format("Duration: %s\n", offering.getDuration());
}
private static void printReservedNodeDetails(ReservedNode node) {
System.out.println("\nPurchased Node Details:");
System.out.format("Id: %s\n", node.getReservedNodeOfferingId());
System.out.format("State: %s\n", node.getState());
System.out.format("Node Type: %s\n", node.getNodeType());
System.out.format("Start Time: %s\n", node.getStartTime());
System.out.format("Fixed Price: %s\n", node.getFixedPrice());
System.out.format("Offering Type: %s\n", node.getOfferingType());
System.out.format("Duration: %s\n", node.getDuration());
}
}
// snippet-end:[redshift.java.ListAndPurchaseReservedNodeOffering.complete] | {
"content_hash": "2b9c5d87f3f5d49611d150e1fb1bbab8",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 145,
"avg_line_length": 40.10071942446043,
"alnum_prop": 0.637064944384643,
"repo_name": "awsdocs/aws-doc-sdk-examples",
"id": "5a952c4ff1147d7dc3d8afb7417caedcbf918f56",
"size": "6119",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java/example_code/redshift/ListAndPurchaseReservedNodeOffering.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ABAP",
"bytes": "476653"
},
{
"name": "Batchfile",
"bytes": "900"
},
{
"name": "C",
"bytes": "3852"
},
{
"name": "C#",
"bytes": "2051923"
},
{
"name": "C++",
"bytes": "943634"
},
{
"name": "CMake",
"bytes": "82068"
},
{
"name": "CSS",
"bytes": "33378"
},
{
"name": "Dockerfile",
"bytes": "2243"
},
{
"name": "Go",
"bytes": "1764292"
},
{
"name": "HTML",
"bytes": "319090"
},
{
"name": "Java",
"bytes": "4966853"
},
{
"name": "JavaScript",
"bytes": "1655476"
},
{
"name": "Jupyter Notebook",
"bytes": "9749"
},
{
"name": "Kotlin",
"bytes": "1099902"
},
{
"name": "Makefile",
"bytes": "4922"
},
{
"name": "PHP",
"bytes": "1220594"
},
{
"name": "Python",
"bytes": "2507509"
},
{
"name": "Ruby",
"bytes": "500331"
},
{
"name": "Rust",
"bytes": "558811"
},
{
"name": "Shell",
"bytes": "63776"
},
{
"name": "Swift",
"bytes": "267325"
},
{
"name": "TypeScript",
"bytes": "119632"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "aad73474345cc761b94b4bf3ccf1f944",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "708135db8f5092fff61517bda5c960f359de06be",
"size": "174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Brossaea/Brossaea roraimae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.somohano.youmeal.model.db.entity;
import com.somohano.youmeal.bean.MemberBean;
import com.somohano.youmeal.utils.Constants;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by rafa on 21/04/16.
*/
@Entity
public class Family implements SQLEntity {
/**
* The database tables should use the identifier _id for the primary key of the table.
* Several Android functions rely on this standard.
*/
@Id(autoincrement = true)
private Long _id;
private String name;
private String avatarPath;
@Generated(hash = 1701349596)
public Family(Long _id, String name, String avatarPath) {
this._id = _id;
this.name = name;
this.avatarPath = avatarPath;
}
@Generated(hash = 627106668)
public Family() {
}
public Long get_id() {
return this._id;
}
public void set_id(Long _id) {
this._id = _id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarPath() {
return this.avatarPath;
}
public void setAvatarPath(String avatarPath) {
this.avatarPath = avatarPath;
}
}
| {
"content_hash": "16d74ef9b3aba57c7d8e3be5e44c7d95",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 87,
"avg_line_length": 23.21818181818182,
"alnum_prop": 0.7102584181675803,
"repo_name": "teksuo/YouMeal",
"id": "ef613060319a46ea62b5db857247c7c90086cede",
"size": "1277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/somohano/youmeal/model/db/entity/Family.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "300368"
}
],
"symlink_target": ""
} |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/common/async_policy_loader.h"
#include <utility>
#include "base/bind.h"
#include "base/location.h"
#include "base/sequenced_task_runner.h"
#include "components/policy/core/common/policy_bundle.h"
using base::Time;
using base::TimeDelta;
namespace policy {
namespace {
// Amount of time to wait for the files on disk to settle before trying to load
// them. This alleviates the problem of reading partially written files and
// makes it possible to batch quasi-simultaneous changes.
constexpr TimeDelta kSettleInterval = TimeDelta::FromSeconds(5);
// The time interval for rechecking policy. This is the fallback in case the
// implementation never detects changes.
constexpr TimeDelta kReloadInterval = TimeDelta::FromMinutes(15);
} // namespace
AsyncPolicyLoader::AsyncPolicyLoader(
const scoped_refptr<base::SequencedTaskRunner>& task_runner)
: task_runner_(task_runner) {}
AsyncPolicyLoader::~AsyncPolicyLoader() {}
Time AsyncPolicyLoader::LastModificationTime() {
return Time();
}
void AsyncPolicyLoader::Reload(bool force) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
TimeDelta delay;
Time now = Time::Now();
// Check if there was a recent modification to the underlying files.
if (!force && !IsSafeToReload(now, &delay)) {
ScheduleNextReload(delay);
return;
}
std::unique_ptr<PolicyBundle> bundle(Load());
// Check if there was a modification while reading.
if (!force && !IsSafeToReload(now, &delay)) {
ScheduleNextReload(delay);
return;
}
// Filter out mismatching policies.
schema_map_->FilterBundle(bundle.get());
update_callback_.Run(std::move(bundle));
ScheduleNextReload(kReloadInterval);
}
std::unique_ptr<PolicyBundle> AsyncPolicyLoader::InitialLoad(
const scoped_refptr<SchemaMap>& schema_map) {
// This is the first load, early during startup. Use this to record the
// initial |last_modification_time_|, so that potential changes made before
// installing the watches can be detected.
last_modification_time_ = LastModificationTime();
schema_map_ = schema_map;
std::unique_ptr<PolicyBundle> bundle(Load());
// Filter out mismatching policies.
schema_map_->FilterBundle(bundle.get());
return bundle;
}
void AsyncPolicyLoader::Init(const UpdateCallback& update_callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK(update_callback_.is_null());
DCHECK(!update_callback.is_null());
update_callback_ = update_callback;
InitOnBackgroundThread();
// There might have been changes to the underlying files since the initial
// load and before the watchers have been created.
if (LastModificationTime() != last_modification_time_)
Reload(false);
// Start periodic refreshes.
ScheduleNextReload(kReloadInterval);
}
void AsyncPolicyLoader::RefreshPolicies(scoped_refptr<SchemaMap> schema_map) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
schema_map_ = schema_map;
Reload(true);
}
void AsyncPolicyLoader::ScheduleNextReload(TimeDelta delay) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
weak_factory_.InvalidateWeakPtrs();
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&AsyncPolicyLoader::Reload, weak_factory_.GetWeakPtr(),
false /* force */),
delay);
}
bool AsyncPolicyLoader::IsSafeToReload(const Time& now, TimeDelta* delay) {
Time last_modification = LastModificationTime();
if (last_modification.is_null())
return true;
// If there was a change since the last recorded modification, wait some more.
if (last_modification != last_modification_time_) {
last_modification_time_ = last_modification;
last_modification_clock_ = now;
*delay = kSettleInterval;
return false;
}
// Check whether the settle interval has elapsed.
const TimeDelta age = now - last_modification_clock_;
if (age < kSettleInterval) {
*delay = kSettleInterval - age;
return false;
}
return true;
}
} // namespace policy
| {
"content_hash": "90561bf6d4def4b0237e1f08101fd903",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 80,
"avg_line_length": 30.525547445255473,
"alnum_prop": 0.7290769966523195,
"repo_name": "endlessm/chromium-browser",
"id": "833fe8e62e266470c230630581806eb0432b0199",
"size": "4182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/policy/core/common/async_policy_loader.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using System;
public class StartUp
{
public static void Main()
{
SmartPhone phone = new SmartPhone();
string[] numbers = Console.ReadLine().Split(' ');
string[] webPages = Console.ReadLine().Split(' ');
foreach (var number in numbers)
{
try
{
phone.Call(number);
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
}
foreach (var webPage in webPages)
{
try
{
phone.Browse(webPage);
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
}
}
} | {
"content_hash": "b5c9fe8ce11835dedffbb60a7ff6b8a3",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 58,
"avg_line_length": 21.8,
"alnum_prop": 0.436435124508519,
"repo_name": "Koceto/SoftUni",
"id": "a3083a8fd713f813b102be6e03f2579fb4feaffd",
"size": "765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C# Fundamentals/C# OOP Advanced/Interfaces and Abstraction/Telephony/StartUp.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1564072"
},
{
"name": "HTML",
"bytes": "27834"
},
{
"name": "JavaScript",
"bytes": "99363"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
<?php
/** @phpstub */
class Yaf_Request_Abstract
{
const SCHEME_HTTP = 'http';
const SCHEME_HTTPS = 'https';
public $module;
public $method;
public $controller;
public $action;
protected $uri;
protected $routed;
protected $params;
protected $language;
protected $dispatched;
protected $_exception;
protected $_base_uri;
/**
* The getActionName purpose
*
* @return void
*/
public function getActionName()
{
}
/**
* The getBaseUri purpose
*
* @return void
*/
public function getBaseUri()
{
}
/**
* The getControllerName purpose
*
* @return void
*/
public function getControllerName()
{
}
/**
* Retrieve ENV varialbe
*
* @param string $name
* @param string $default
*
* @return void
*/
public function getEnv($name, $default = NULL)
{
}
/**
* The getException purpose
*
* @return void
*/
public function getException()
{
}
/**
* The getLanguage purpose
*
* @return void
*/
public function getLanguage()
{
}
/**
* The getMethod purpose
*
* @return void
*/
public function getMethod()
{
}
/**
* The getModuleName purpose
*
* @return void
*/
public function getModuleName()
{
}
/**
* The getParam purpose
*
* @param string $name
* @param string $default
*
* @return void
*/
public function getParam($name, $default = NULL)
{
}
/**
* The getParams purpose
*
* @return void
*/
public function getParams()
{
}
/**
* The getRequestUri purpose
*
* @return void
*/
public function getRequestUri()
{
}
/**
* Retrieve SERVER variable
*
* @param string $name
* @param string $default
*
* @return void
*/
public function getServer($name, $default = NULL)
{
}
/**
* The isCli purpose
*
* @return void
*/
public function isCli()
{
}
/**
* The isDispatched purpose
*
* @return void
*/
public function isDispatched()
{
}
/**
* The isGet purpose
*
* @return void
*/
public function isGet()
{
}
/**
* The isHead purpose
*
* @return void
*/
public function isHead()
{
}
/**
* The isOptions purpose
*
* @return void
*/
public function isOptions()
{
}
/**
* The isPost purpose
*
* @return void
*/
public function isPost()
{
}
/**
* The isPut purpose
*
* @return void
*/
public function isPut()
{
}
/**
* The isRouted purpose
*
* @return void
*/
public function isRouted()
{
}
/**
* The isXmlHttpRequest purpose
*
* @return void
*/
public function isXmlHttpRequest()
{
}
/**
* The setActionName purpose
*
* @param string $action
*
* @return void
*/
public function setActionName($action)
{
}
/**
* The setBaseUri purpose
*
* @param string $uir
*
* @return void
*/
public function setBaseUri($uir)
{
}
/**
* The setControllerName purpose
*
* @param string $controller
*
* @return void
*/
public function setControllerName($controller)
{
}
/**
* The setDispatched purpose
*
* @return void
*/
public function setDispatched()
{
}
/**
* The setModuleName purpose
*
* @param string $module
*
* @return void
*/
public function setModuleName($module)
{
}
/**
* The setParam purpose
*
* @param string $name
* @param string $value
*
* @return void
*/
public function setParam($name, $value = NULL)
{
}
/**
* The setRequestUri purpose
*
* @param string $uir
*
* @return void
*/
public function setRequestUri($uir)
{
}
/**
* The setRouted purpose
*
* @param string $flag
*
* @return void
*/
public function setRouted($flag = NULL)
{
}
} | {
"content_hash": "986d6b34b6f133184420335316543401",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 53,
"avg_line_length": 14.668852459016394,
"alnum_prop": 0.4798837729101475,
"repo_name": "schmittjoh/php-stubs",
"id": "d2f1f9090e6c97dc8a9f3dd965c77ed34f959dc5",
"size": "4474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/php/yaf/yaf-request-abstract.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "2203628"
}
],
"symlink_target": ""
} |
@interface CountryPicker () <UIPickerViewDelegate, UIPickerViewDataSource>
@end
@implementation CountryPicker
//doesn't use _ prefix to avoid name clash
@synthesize delegate;
+ (NSArray *)countryNames
{
static NSArray *_countryNames = nil;
if (!_countryNames)
{
_countryNames = [[[[self countryNamesByCode] allValues] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] copy];
}
return _countryNames;
}
+ (NSArray *)countryCodes
{
static NSArray *_countryCodes = nil;
if (!_countryCodes)
{
_countryCodes = [[[self countryCodesByName] objectsForKeys:[self countryNames] notFoundMarker:@""] copy];
}
return _countryCodes;
}
+ (NSDictionary *)countryNamesByCode
{
static NSDictionary *_countryNamesByCode = nil;
if (!_countryNamesByCode)
{
NSMutableDictionary *namesByCode = [NSMutableDictionary dictionary];
for (NSString *code in [NSLocale ISOCountryCodes])
{
NSString *identifier = [NSLocale localeIdentifierFromComponents:@{NSLocaleCountryCode: code}];
NSString *countryName = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:identifier];
if (countryName) namesByCode[code] = countryName;
}
_countryNamesByCode = [namesByCode copy];
}
return _countryNamesByCode;
}
+ (NSDictionary *)countryCodesByName
{
static NSDictionary *_countryCodesByName = nil;
if (!_countryCodesByName)
{
NSDictionary *countryNamesByCode = [self countryNamesByCode];
NSMutableDictionary *codesByName = [NSMutableDictionary dictionary];
for (NSString *code in countryNamesByCode)
{
codesByName[countryNamesByCode[code]] = code;
}
_countryCodesByName = [codesByName copy];
}
return _countryCodesByName;
}
- (void)setup
{
[super setDataSource:self];
[super setDelegate:self];
}
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self setup];
}
return self;
}
- (void)setDataSource:(__unused id<UIPickerViewDataSource>)dataSource
{
//does nothing
}
- (void)setSelectedCountryCode:(NSString *)countryCode animated:(BOOL)animated
{
NSInteger index = [[[self class] countryCodes] indexOfObject:countryCode];
if (index != NSNotFound)
{
[self selectRow:index inComponent:0 animated:animated];
}
}
- (void)setSelectedCountryCode:(NSString *)countryCode
{
[self setSelectedCountryCode:countryCode animated:NO];
}
- (NSString *)selectedCountryCode
{
NSInteger index = [self selectedRowInComponent:0];
return [[self class] countryCodes][index];
}
- (void)setSelectedCountryName:(NSString *)countryName animated:(BOOL)animated
{
NSInteger index = [[[self class] countryNames] indexOfObject:countryName];
if (index != NSNotFound)
{
[self selectRow:index inComponent:0 animated:animated];
}
}
- (void)setSelectedCountryName:(NSString *)countryName
{
[self setSelectedCountryName:countryName animated:NO];
}
- (NSString *)selectedCountryName
{
NSInteger index = [self selectedRowInComponent:0];
return [[self class] countryNames][index];
}
- (void)setSelectedLocale:(NSLocale *)locale animated:(BOOL)animated
{
[self setSelectedCountryCode:[locale objectForKey:NSLocaleCountryCode] animated:animated];
}
- (void)setSelectedLocale:(NSLocale *)locale
{
[self setSelectedLocale:locale animated:NO];
}
- (NSLocale *)selectedLocale
{
NSString *countryCode = self.selectedCountryCode;
if (countryCode)
{
NSString *identifier = [NSLocale localeIdentifierFromComponents:@{NSLocaleCountryCode: countryCode}];
return [NSLocale localeWithLocaleIdentifier:identifier];
}
return nil;
}
#pragma mark -
#pragma mark UIPicker
- (NSInteger)numberOfComponentsInPickerView:(__unused UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(__unused UIPickerView *)pickerView numberOfRowsInComponent:(__unused NSInteger)component
{
return [[[self class] countryCodes] count];
}
- (UIView *)pickerView:(__unused UIPickerView *)pickerView viewForRow:(NSInteger)row
forComponent:(__unused NSInteger)component reusingView:(UIView *)view
{
if (!view)
{
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(35, 3, 245, 24)];
label.backgroundColor = [UIColor clearColor];
label.tag = 1;
[view addSubview:label];
UIImageView *flagView = [[UIImageView alloc] initWithFrame:CGRectMake(3, 3, 24, 24)];
flagView.contentMode = UIViewContentModeScaleAspectFit;
flagView.tag = 2;
[view addSubview:flagView];
}
((UILabel *)[view viewWithTag:1]).text = [[self class] countryNames][row];
((UIImageView *)[view viewWithTag:2]).image = [UIImage imageNamed:[[self class] countryCodes][row]];
return view;
}
- (void)pickerView:(__unused UIPickerView *)pickerView
didSelectRow:(__unused NSInteger)row
inComponent:(__unused NSInteger)component
{
NSString *code = self.selectedCountryCode;
NSString *name = self.selectedCountryName;
[delegate countryPicker:self didSelectCountryWithName:name code:code];
}
@end
| {
"content_hash": "f92dac3a550b575a6bd7bbb1d80b4952",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 131,
"avg_line_length": 27.405,
"alnum_prop": 0.6880131362889984,
"repo_name": "tdyn2000/PhoneNumberValidate",
"id": "3f8002604f33da56833488ee346a418f161aacd0",
"size": "7112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libPhoneNumber/CountryPicker/CountryPicker.m",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "784802"
},
{
"name": "PHP",
"bytes": "2381"
},
{
"name": "Perl",
"bytes": "1309"
},
{
"name": "Ruby",
"bytes": "1317"
}
],
"symlink_target": ""
} |
/**
* Data structures used for indexing AND searching (ex: co-occurrences)
*/
package alix.lucene.util; | {
"content_hash": "653b539b939d4a93b5dc78d5cfe1121d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 71,
"avg_line_length": 17.833333333333332,
"alnum_prop": 0.719626168224299,
"repo_name": "oeuvres/Alix",
"id": "68b80ace7af7cd01659d4280cc68706a2e5a4814",
"size": "1485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/alix/lucene/util/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "55823"
},
{
"name": "Java",
"bytes": "963640"
},
{
"name": "XSLT",
"bytes": "200751"
}
],
"symlink_target": ""
} |
var structrocksdb_1_1TransactionLogIterator_1_1ReadOptions =
[
[ "ReadOptions", "structrocksdb_1_1TransactionLogIterator_1_1ReadOptions.html#ae7e1d80dfad8f2c263aa75d3deb5ddc4", null ],
[ "ReadOptions", "structrocksdb_1_1TransactionLogIterator_1_1ReadOptions.html#a21d630f1ec2743b6e2eb11d23a29be9b", null ],
[ "verify_checksums_", "structrocksdb_1_1TransactionLogIterator_1_1ReadOptions.html#ac54467282bf7138a52cc0a39ee302987", null ]
]; | {
"content_hash": "d59e61576c0cb238c579739cec54368c",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 130,
"avg_line_length": 74.66666666666667,
"alnum_prop": 0.8102678571428571,
"repo_name": "seguijoaquin/taller2-appserver",
"id": "310f06ae5d37e4b3afc8497d22292567e79b11cf",
"size": "448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Documentacion/html/structrocksdb_1_1TransactionLogIterator_1_1ReadOptions.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "99679"
},
{
"name": "C++",
"bytes": "10237477"
},
{
"name": "CMake",
"bytes": "144910"
},
{
"name": "CSS",
"bytes": "43601"
},
{
"name": "HTML",
"bytes": "14331186"
},
{
"name": "Java",
"bytes": "790366"
},
{
"name": "JavaScript",
"bytes": "651118"
},
{
"name": "M4",
"bytes": "25387"
},
{
"name": "Makefile",
"bytes": "217222"
},
{
"name": "Objective-C",
"bytes": "9308"
},
{
"name": "PHP",
"bytes": "38694"
},
{
"name": "Perl",
"bytes": "54513"
},
{
"name": "PostScript",
"bytes": "331209"
},
{
"name": "PowerShell",
"bytes": "9458"
},
{
"name": "Python",
"bytes": "2144821"
},
{
"name": "Ruby",
"bytes": "1562"
},
{
"name": "Shell",
"bytes": "158255"
},
{
"name": "TeX",
"bytes": "950289"
},
{
"name": "XSLT",
"bytes": "1290"
}
],
"symlink_target": ""
} |
package de.replayreader.printer;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import de.replayreader.model.ReplayCollection;
public class CSVPrinter {
private final ReplayCollection replayCollection;
private final List<String> players;
public CSVPrinter(final ReplayCollection replayCollection, final List<String> players) {
this.replayCollection = replayCollection;
this.players = players;
}
// TODO: encapsulate row writing
public void print(final File csvFile) throws IOException {
final List<List<String>> csv = new ArrayList<>();
final List<String> rowHeader = new ArrayList<>();
rowHeader.add(COLS.PLAYER.getColName());
rowHeader.add(COLS.GAMES.getColName());
rowHeader.add(COLS.TANK.getColName());
rowHeader.add(COLS.DMG.getColName());
rowHeader.add(COLS.KILLS.getColName());
rowHeader.add(COLS.PENRATE.getColName());
rowHeader.add(COLS.HITRATE.getColName());
rowHeader.add(COLS.SPOT_ASSIST.getColName());
rowHeader.add(COLS.TRACK_ASSIST.getColName());
rowHeader.add(COLS.SPOTS.getColName());
rowHeader.add(COLS.BLOCKED.getColName());
rowHeader.add(COLS.LIFETIME.getColName());
rowHeader.add(COLS.HITS_RECEIVED.getColName());
rowHeader.add(COLS.DMG_RECEIVED.getColName());
rowHeader.add(COLS.DMG_INVIS_RECEIVED.getColName());
csv.add(rowHeader);
for (final String player : players) {
// overall stats
final List<String> overallRow = new ArrayList<>();
overallRow.add(player);
overallRow.add(String.format("%s", replayCollection.getNumberOfGames(player, null)));
overallRow.add("<overall>");
overallRow.add(String.valueOf(replayCollection.getAvgDamageDealt(player, null)));
overallRow.add(String.format("%.1f", replayCollection.getAvgKills(player, null)));
overallRow.add(String.format("%.0f", 100 * replayCollection.getPenRate(player, null)));
overallRow.add(String.format("%.0f", 100 * replayCollection.getHitRate(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgSpotAssist(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgTrackAssist(player, null)));
overallRow.add(String.format("%.1f", replayCollection.getAvgSpots(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgBlocked(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgLifeTime(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgHitsReceived(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgDamageReceived(player, null)));
overallRow.add(String.format("%s", replayCollection.getAvgDamageReceivedFromInvisibles(player, null)));
csv.add(overallRow);
// vehicle stats
final List<String> vehiclesForPlayer = replayCollection.getVehiclesForPlayer(player);
for (final String vehicle : vehiclesForPlayer) {
final List<String> vehicleRow = new ArrayList<>();
vehicleRow.add(player);
vehicleRow.add(String.format("%s", replayCollection.getNumberOfGames(player, vehicle)));
vehicleRow.add(String.format("%s", vehicle));
vehicleRow.add(String.valueOf(replayCollection.getAvgDamageDealt(player, vehicle)));
vehicleRow.add(String.format("%.1f", replayCollection.getAvgKills(player, vehicle)));
vehicleRow.add(String.format("%.0f", 100 * replayCollection.getPenRate(player, vehicle)));
vehicleRow.add(String.format("%.0f", 100 * replayCollection.getHitRate(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgSpotAssist(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgTrackAssist(player, vehicle)));
vehicleRow.add(String.format("%.1f", replayCollection.getAvgSpots(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgBlocked(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgLifeTime(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgHitsReceived(player, vehicle)));
vehicleRow.add(String.format("%s", replayCollection.getAvgDamageReceived(player, vehicle)));
vehicleRow
.add(String.format("%s", replayCollection.getAvgDamageReceivedFromInvisibles(player, vehicle)));
csv.add(vehicleRow);
}
}
final StringBuilder sb = new StringBuilder();
for (final List<String> row : csv) {
row.forEach(cell -> sb.append(String.format("%s;", cell)));
sb.append(System.getProperty("line.separator"));
}
System.out.println("writing file " + csvFile.getAbsolutePath());
FileUtils.writeStringToFile(csvFile, sb.toString(), Charset.defaultCharset());
}
}
| {
"content_hash": "25d51f6543fc3fce0dbf3dee8cb97a39",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 106,
"avg_line_length": 47.26,
"alnum_prop": 0.747355057130766,
"repo_name": "enstun/rreader",
"id": "d19a808012d665327d9d082e93603c06c184cc59",
"size": "4726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rreader.model/src/main/java/de/replayreader/printer/CSVPrinter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "101"
},
{
"name": "Java",
"bytes": "102596"
}
],
"symlink_target": ""
} |
/*
File: network.cpp
Description: An OOP unix-only-compatible network library
Developer: Dionyziz
*/
#include "network.h"
Sock::Sock() {
int fileDescriptor;
// create a socket object
fileDescriptor = socket( PF_INET,
SOCK_STREAM /* communication with reliable TCP/IP connection */ ,
0 /* protocol decided by kernel based on type */ );
if ( fileDescriptor == -1 ) {
throw CadorException( "Sock: Could not create socket; socket() returned -1" );
}
this->Initialize( fileDescriptor );
}
Sock::Sock( const int fileDescriptor ) {
this->Initialize( fileDescriptor );
}
void Sock::Initialize( const int fileDescriptor ) {
int nonBlockApplied;
const int one = 1;
int sockopt;
this->mSock = fileDescriptor;
// set socket to non-blocking i/o
// forking/threading can be handled by the library user
nonBlockApplied = ioctl( this->mSock, FIONBIO, ( char * )&one );
if ( nonBlockApplied == -1 ) {
throw CadorException( "Sock: Failed to make socket non-blocking; ioctl() returned -1" );
}
sockopt = 1;
setsockopt( this->mSock, SOL_SOCKET, SO_LINGER, &sockopt, sizeof( sockopt ) );
setsockopt( this->mSock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof( sockopt ) );
}
int Sock::SocketId() {
return this->mSock;
}
Sock::~Sock() {
}
Communicator::Communicator() : Sock() { // for completeness; use Communicator( fileDescriptor, remoteinfo ) instead!
Warning << "Instanciating Communicator using empty constructor!";
}
Communicator::~Communicator() {
}
Communicator::Communicator( const int fileDescriptor, const struct sockaddr_in remoteinfo ) : Sock( fileDescriptor ) {
this->mConnected = true;
this->mCallbackOnReceiveDefined = false;
this->mCallbackOnCloseDefined = false;
this->mWaitingFor = false;
this->mRemoteIP = remoteinfo.sin_addr.s_addr;
this->SetId( 0 );
this->mSendBuffer = "";
this->mRecvBuffer = "";
}
bool Communicator::Connected() {
return this->mConnected;
}
void Communicator::Send( const string& s ) {
this->mSendBuffer += s;
this->SendBuffered();
}
void Communicator::Send( const char* s ) {
string S = s;
this->Send( S );
}
void Communicator::SetReceiveCallback( void ( *receiveCallback ) ( Communicator* ) ) {
this->mCallbackOnReceive = receiveCallback;
this->mCallbackOnReceiveDefined = true;
}
void Communicator::UnsetReceiveCallback() {
this->mCallbackOnReceiveDefined = false;
}
void Communicator::SetCloseCallback( void ( *closeCallback ) ( Communicator* ) ){
this->mCallbackOnClose = closeCallback;
this->mCallbackOnCloseDefined = true;
}
void Communicator::UnsetCloseCallback() {
this->mCallbackOnCloseDefined = false;
}
void Communicator::SendBuffered() {
int sent;
char* data;
if ( !this->mConnected ) {
return;
}
if ( this->mSendBuffer.length() ) {
data = ( char* )malloc( this->mSendBuffer.length() * sizeof( char ) );
for ( int i = 0; i < this->mSendBuffer.length(); ++i ) {
data[ i ] = this->mSendBuffer[ i ];
}
Trace << this->Id() << ": Sending " << this->mSendBuffer.length() << " bytes";
sent = send( this->mSock, data, this->mSendBuffer.length(), 0 );
if ( sent == -1 ) { // disconnected?
Notice << this->Id() << ": Failed to send buffered data";
return;
}
this->mSendBuffer = this->mSendBuffer.substr( sent );
}
}
void Communicator::CheckForNewData() {
int ret;
char buf[ 512 ];
ret = recv( this->mSock, buf, sizeof( buf ), 0 );
switch ( ret ) {
case 0:
// connection was closed
this->Disconnected();
return;
case -1:
// error
// Trace( errno );
break;
default:
Trace << this->Id() << ": Incoming data from client";
this->mRecvBuffer.append( buf, ret );
this->HandleWaits();
if ( this->mRecvBuffer.size() && !this->mWaitingFor ) {
if ( this->mCallbackOnReceiveDefined ) {
( this->mCallbackOnReceive )( this );
}
else {
Notice << this->Id() << ": Unhandled data received from Communicator";
}
}
}
}
string Communicator::RemoteHost() {
struct in_addr address;
string s;
address.s_addr = this->mRemoteIP;
s = inet_ntoa( address );
return s;
}
void Communicator::Close() {
close( this->mSock );
this->Disconnected();
}
void Communicator::Disconnected() {
Trace << this->Id() << ": Connection closed by client";
this->mConnected = false;
this->mWaitingFor = false;
if ( this->mCallbackOnCloseDefined ) {
( this->mCallbackOnClose ) ( this );
}
}
void Communicator::Run() {
// TODO: Run me periodically
if ( this->mConnected ) {
this->CheckForNewData();
this->SendBuffered();
}
}
string Communicator::Id() {
return this->mId;
}
void Communicator::SetId( const int id ) {
char s[ 50 ];
sprintf( s, "%s/%i", this->RemoteHost().c_str(), id );
this->mId = s;
}
void Communicator::WaitFor( const int numberofbytes, const int timeout, void ( *CallbackOnDone )( Communicator* C, const bool, string ) ) {
Trace << this->Id() << ": Waiting for " << numberofbytes << " bytes";
if ( this->mWaitingFor ) {
throw CadorException( "Communicator: Already waiting for data arrival" );
}
this->mWaitingFor = true;
this->mWaitingForString = false;
this->mWaitMaximumNumberOfBytes = numberofbytes;
this->mWaitTimeout = timeout;
this->mWaitStartedAt = clock();
this->mWaitCallback = CallbackOnDone;
}
void Communicator::WaitUntil( const string s, const int maximumnumberofbytes, const int timeout, void ( *CallbackOnDone )( Communicator* C, const bool, string ) ) {
Trace << this->Id() << ": Waiting for sequence termination string of length " << s.length() << " or a maximum of " << maximumnumberofbytes << " bytes";
if ( this->mWaitingFor ) {
Warning << this->Id() << ": Already waiting for data arrival; skipping";
return;
}
assert( s.length() <= maximumnumberofbytes );
this->mWaitingFor = true;
this->mWaitingForString = true;
this->mWaitMaximumNumberOfBytes = maximumnumberofbytes;
this->mWaitTimeout = timeout;
this->mWaitStartedAt = clock();
this->mWaitCallback = CallbackOnDone;
this->mWaitForString = s;
}
bool Communicator::HandleStringWaits() {
string data;
int pos;
if ( this->mRecvBuffer.length() >= this->mWaitForString.length() ) {
// TODO: Optimize this using KMP
pos = this->mRecvBuffer.find( this->mWaitForString );
if ( pos == string::npos ) {
Trace << this->Id() << ": Termination sequence not found";
// termination sequence not found, check if we have exceeded the given limit
if ( this->mRecvBuffer.length() > this->mWaitMaximumNumberOfBytes ) {
if ( this->mRecvBuffer.length() > this->mWaitMaximumNumberOfBytes + this->mWaitForString.length() ) {
Notice << this->Id() << ": Maximum data length hard limit exceeded; skipping";
this->mWaitingFor = false;
( this->mWaitCallback )( this, false, "" ); // this might modify mWaitingFor
return false;
}
// soft limit has been exceeded, but the termination sequence might exceed that limit if the actual data does not
// check for marginal case
data = this->mRecvBuffer.substr( this->mWaitMaximumNumberOfBytes );
if ( this->mWaitForString.substr( 0, data.length() ) != data ) {
Notice << this->Id() << ": Maximum data length soft limit exceeded with invalid identifier; skipping";
this->mWaitingFor = false;
( this->mWaitCallback )( this, false, "" ); // this might modify mWaitingFor
return false;
}
Trace << this->Id() << ": Soft limit exceeded within allowed bounds";
}
// not found yet, wait for next round
return true;
}
// else
Trace << this->Id() << ": Termination sequence found";
// found, check if we're within the allows hard limit
if ( pos > this->mWaitMaximumNumberOfBytes ) {
Notice << this->Id() << ": Position of termination identifier exceeds maximum data length hard limit; skipping";
this->mWaitingFor = false;
( this->mWaitCallback )( this, false, "" );
return false;
}
// else
Trace << this->Id() << ": Limits not exceeded";
// if we got here, we're good
data = this->mRecvBuffer.substr( 0, pos );
this->mRecvBuffer = this->mRecvBuffer.substr( pos + this->mWaitForString.length() );
this->mWaitingFor = false;
( this->mWaitCallback )( this, true, data ); // this might modify mWaitingFor
return false;
}
// else // not yet received enough data to check for sentinel
return true;
}
bool Communicator::HandleLengthWaits() {
string data;
if ( this->mRecvBuffer.length() >= this->mWaitMaximumNumberOfBytes ) {
data = this->mRecvBuffer.substr( 0, this->mWaitMaximumNumberOfBytes );
this->mRecvBuffer = this->mRecvBuffer.substr( this->mWaitMaximumNumberOfBytes );
this->mWaitingFor = false;
( this->mWaitCallback )( this, true, data ); // this might modify mWaitingFor
return false;
}
// else // still haven't received the required number of bytes
return true;
}
void Communicator::HandleWaits() {
while ( this->mWaitingFor ) {
if ( this->mWaitingForString ) {
if ( this->HandleStringWaits() ) {
break;
}
}
else {
if ( this->HandleLengthWaits() ) {
break;
}
}
}
}
Server::Server() : Sock() {
this->mListening = false;
this->mPort = 0;
this->mBacklog = 10;
this->mCallbackOnAcceptDefined = false;
this->mNumClients = 0;
}
Server::~Server() {
this->StopListening();
}
void Server::Listen() {
int bound;
if ( this->mListening ) {
// already listening for connections
return;
}
assert( this->mPort > 0 );
this->mLocalAddress.sin_family = AF_INET; // host byte order
this->mLocalAddress.sin_port = htons( this->mPort ); // network byte order
this->mLocalAddress.sin_addr.s_addr = htonl( INADDR_ANY ); // allow connections from any host
memset( &( this->mLocalAddress.sin_zero ), '\0', 8 ); // nullify the rest of the struct
bound = bind( this->mSock,
( struct sockaddr * )&this->mLocalAddress,
sizeof( struct sockaddr ) );
if ( bound == -1 ) {
throw CadorException( "Server: Could not bind socket to name; bind() returned -1" );
}
listen( this->mSock, this->mBacklog ); // listen for connections
Trace << "Listening for connections new connetions on port " << this->mPort;
this->mListening = true;
}
void Server::StopListening() {
if ( !this->mListening ) {
// not listening
return;
}
Trace << "Stopped listening for connections";
close( this->mSock );
this->mListening = false;
}
void Server::SetPort( const int port ) {
assert( port > 0 );
assert( port < 65536 );
if ( this->mPort != port ) {
this->mPort = port;
this->Reset();
}
}
void Server::SetBacklog( const int backlog ) {
assert( backlog >= 1 );
assert( backlog < 100 );
if ( this->mBacklog != backlog ) {
this->mBacklog = backlog;
this->Reset();
}
}
void Server::SetAcceptCallback( void ( *acceptCallback ) ( Server*, Communicator* ) ) {
this->mCallbackOnAccept = acceptCallback;
this->mCallbackOnAcceptDefined = true;
}
void Server::UnsetAcceptCallback() {
this->mCallbackOnAcceptDefined = false;
}
void Server::Reset() {
if ( this->mListening ) {
this->StopListening();
this->Listen();
}
}
void Server::CheckForConnectionRequests() {
socklen_t sin_size;
struct sockaddr_in remoteinfo;
int accepted;
sin_size = sizeof( struct sockaddr_in );
// Either fork()ing or branching to new thread can be handled by the user after the callback
// releases immediately
accepted = accept( this->mSock, ( struct sockaddr* )&remoteinfo, &sin_size );
if ( accepted == -1 ) {
// no connection currently present
return;
}
this->Accepted( accepted, remoteinfo );
}
void Server::Accepted( const int fileDescriptor, const struct sockaddr_in remoteinfo ) {
Communicator* thisClient;
thisClient = new Communicator( fileDescriptor, remoteinfo );
thisClient->SetId( ++this->mNumClients );
Trace << thisClient->Id() << ": New connection request";
if ( this->mCallbackOnAcceptDefined ) {
( this->mCallbackOnAccept )( this, thisClient );
}
else {
Notice << "Unhandled connection request";
}
}
void Server::Run() {
// TODO: run this method periodically
this->CheckForConnectionRequests();
}
/*
Client::Connect() {
assert( this->mPort > 0 );
// TODO
}
*/
| {
"content_hash": "96c12a9f2df6c0b749b7d625ef64cd02",
"timestamp": "",
"source": "github",
"line_count": 432,
"max_line_length": 164,
"avg_line_length": 32.363425925925924,
"alnum_prop": 0.5786424433159287,
"repo_name": "dionyziz/cador",
"id": "5fc30fdbe0d8cfee979691136e66f7923200ca8e",
"size": "13981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "network.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4986"
},
{
"name": "C++",
"bytes": "81596"
}
],
"symlink_target": ""
} |
/**
* Provides a Edit Tree component for the Family Tree Project
*
* @module components/editTree/editTree
* @requires knockout, config, text!./editTree.html
*/
define("components/editTree/editTree", ["knockout", "config", "text!./editTree.html"], function (ko, config, htmlString) {
function editTreeViewModel(props) {
var self = this;
self.resx = config.resx;
self.dialogTitle = props.dialogTitle;
self.isVisible = props.isVisible;
self.onSuccess = props.onSuccess;
self.treeId = ko.observable(props.treeId());
self.newTreeId = props.newTreeId;
if (self.treeId() === -1) {
self.name = ko.observable("");
self.title = ko.observable("");
self.description = ko.observable("");
} else {
self.name = props.name;
self.title = props.title;
self.description = props.description;
}
self.widget = ko.observable();
self.cancel = function() {
self.widget().dialog("close");
}
self.close = function () {
}
self.saveTree = function () {
var params = {
treeId: self.treeId(),
name: self.name(),
title: self.title(),
description: self.description()
};
config.treeService().post("SaveTree",
params,
function (data) {
self.newTreeId(data.treeId);
self.cancel();
self.onSuccess();
}
);
}
}
// Return component definition
return { viewModel: editTreeViewModel, template: htmlString };
}); | {
"content_hash": "5237610e344c9258b8931866b11cb62f",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 122,
"avg_line_length": 27.265625,
"alnum_prop": 0.5191977077363897,
"repo_name": "cnurse/FamilyTreeProject.Dnn",
"id": "02fe95a0a89b0fb89493c19259f33b069aba3e2e",
"size": "1948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FamilyTreeProject.Dnn/ClientScripts/components/editTree/editTree.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "86"
},
{
"name": "C#",
"bytes": "71092"
},
{
"name": "CSS",
"bytes": "14998"
},
{
"name": "HTML",
"bytes": "31410"
},
{
"name": "JavaScript",
"bytes": "159967"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>lambda: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.1 / lambda - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
lambda
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-20 21:15:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-20 21:15:45 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/lambda"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Lambda"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: pure lambda-calculus" "keyword: confluence" "keyword: parallel-moves lemma" "keyword: Lévy's Cube Lemma" "keyword: Church-Rosser" "keyword: residual" "keyword: Prism theorem" "category: Computer Science/Lambda Calculi" ]
authors: [ "Gérard Huet" ]
bug-reports: "https://github.com/coq-contribs/lambda/issues"
dev-repo: "git+https://github.com/coq-contribs/lambda.git"
synopsis: "Residual Theory in Lambda-Calculus"
description: """
We present the complete development in Gallina of the
residual theory of beta-reduction in pure lambda-calculus. The main
result is the Prism Theorem, and its corollary Lévy's Cube Lemma, a
strong form of the parallel-moves lemma, itself a key step towards the
confluence theorem and its usual corollaries (Church-Rosser,
uniqueness of normal forms)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/lambda/archive/v8.7.0.tar.gz"
checksum: "md5=4e91d279a4dd2565b76c3da824fb8022"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-lambda.8.7.0 coq.8.11.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1).
The following dependencies couldn't be met:
- coq-lambda -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-lambda.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "34e3777c5feda2dd179a7d1810784bcb",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 322,
"avg_line_length": 42.708333333333336,
"alnum_prop": 0.5537282229965157,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "cda418e969f69103a081a7d155768a43aea5e327",
"size": "7203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.11.1/lambda/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import os
import torch
import numpy as np
from datetime import datetime
from faster_rcnn import network
from faster_rcnn.faster_rcnn import FasterRCNN, RPN
from faster_rcnn.utils.timer import Timer
import faster_rcnn.roi_data_layer.roidb as rdl_roidb
from faster_rcnn.roi_data_layer.layer import RoIDataLayer
from faster_rcnn.datasets.factory import get_imdb
from faster_rcnn.fast_rcnn.config import cfg, cfg_from_file
try:
from termcolor import cprint
except ImportError:
cprint = None
try:
from pycrayon import CrayonClient
except ImportError:
CrayonClient = None
def log_print(text, color=None, on_color=None, attrs=None):
if cprint is not None:
cprint(text, color=color, on_color=on_color, attrs=attrs)
else:
print(text)
# hyper-parameters
# ------------
imdb_name = 'voc_2007_trainval'
cfg_file = 'experiments/cfgs/faster_rcnn_end2end.yml'
pretrained_model = 'data/pretrained_model/VGG_imagenet.npy'
output_dir = 'models/saved_model3'
start_step = 0
end_step = 100000
lr_decay_steps = {60000, 80000}
lr_decay = 1./10
rand_seed = 1024
_DEBUG = True
use_tensorboard = True
remove_all_log = False # remove all historical experiments in TensorBoard
exp_name = None # the previous experiment name in TensorBoard
# ------------
if rand_seed is not None:
np.random.seed(rand_seed)
# load config
cfg_from_file(cfg_file)
lr = cfg.TRAIN.LEARNING_RATE
momentum = cfg.TRAIN.MOMENTUM
weight_decay = cfg.TRAIN.WEIGHT_DECAY
disp_interval = cfg.TRAIN.DISPLAY
log_interval = cfg.TRAIN.LOG_IMAGE_ITERS
# load data
imdb = get_imdb(imdb_name)
rdl_roidb.prepare_roidb(imdb)
roidb = imdb.roidb
data_layer = RoIDataLayer(roidb, imdb.num_classes)
# load net
net = FasterRCNN(classes=imdb.classes, debug=_DEBUG)
network.weights_normal_init(net, dev=0.01)
network.load_pretrained_npy(net, pretrained_model)
# model_file = '/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5'
# model_file = 'models/saved_model3/faster_rcnn_60000.h5'
# network.load_net(model_file, net)
# exp_name = 'vgg16_02-19_13-24'
# start_step = 60001
# lr /= 10.
# network.weights_normal_init([net.bbox_fc, net.score_fc, net.fc6, net.fc7], dev=0.01)
net.cuda()
net.train()
params = list(net.parameters())
# optimizer = torch.optim.Adam(params[-8:], lr=lr)
optimizer = torch.optim.SGD(params[8:], lr=lr, momentum=momentum, weight_decay=weight_decay)
if not os.path.exists(output_dir):
os.mkdir(output_dir)
# tensorboad
use_tensorboard = use_tensorboard and CrayonClient is not None
if use_tensorboard:
cc = CrayonClient(hostname='127.0.0.1')
if remove_all_log:
cc.remove_all_experiments()
if exp_name is None:
exp_name = datetime.now().strftime('vgg16_%m-%d_%H-%M')
exp = cc.create_experiment(exp_name)
else:
exp = cc.open_experiment(exp_name)
# training
train_loss = 0
tp, tf, fg, bg = 0., 0., 0, 0
step_cnt = 0
re_cnt = False
t = Timer()
t.tic()
for step in range(start_step, end_step+1):
# get one batch
blobs = data_layer.forward()
im_data = blobs['data']
im_info = blobs['im_info']
gt_boxes = blobs['gt_boxes']
gt_ishard = blobs['gt_ishard']
dontcare_areas = blobs['dontcare_areas']
# forward
net(im_data, im_info, gt_boxes, gt_ishard, dontcare_areas)
loss = net.loss + net.rpn.loss
if _DEBUG:
tp += float(net.tp)
tf += float(net.tf)
fg += net.fg_cnt
bg += net.bg_cnt
train_loss += loss.data[0]
step_cnt += 1
# backward
optimizer.zero_grad()
loss.backward()
network.clip_gradient(net, 10.)
optimizer.step()
if step % disp_interval == 0:
duration = t.toc(average=False)
fps = step_cnt / duration
log_text = 'step %d, image: %s, loss: %.4f, fps: %.2f (%.2fs per batch)' % (
step, blobs['im_name'], train_loss / step_cnt, fps, 1./fps)
log_print(log_text, color='green', attrs=['bold'])
if _DEBUG:
log_print('\tTP: %.2f%%, TF: %.2f%%, fg/bg=(%d/%d)' % (tp/fg*100., tf/bg*100., fg/step_cnt, bg/step_cnt))
log_print('\trpn_cls: %.4f, rpn_box: %.4f, rcnn_cls: %.4f, rcnn_box: %.4f' % (
net.rpn.cross_entropy.data.cpu().numpy()[0], net.rpn.loss_box.data.cpu().numpy()[0],
net.cross_entropy.data.cpu().numpy()[0], net.loss_box.data.cpu().numpy()[0])
)
re_cnt = True
if use_tensorboard and step % log_interval == 0:
exp.add_scalar_value('train_loss', train_loss / step_cnt, step=step)
exp.add_scalar_value('learning_rate', lr, step=step)
if _DEBUG:
exp.add_scalar_value('true_positive', tp/fg*100., step=step)
exp.add_scalar_value('true_negative', tf/bg*100., step=step)
losses = {'rpn_cls': float(net.rpn.cross_entropy.data.cpu().numpy()[0]),
'rpn_box': float(net.rpn.loss_box.data.cpu().numpy()[0]),
'rcnn_cls': float(net.cross_entropy.data.cpu().numpy()[0]),
'rcnn_box': float(net.loss_box.data.cpu().numpy()[0])}
exp.add_scalar_dict(losses, step=step)
if (step % 10000 == 0) and step > 0:
save_name = os.path.join(output_dir, 'faster_rcnn_{}.h5'.format(step))
network.save_net(save_name, net)
print('save model: {}'.format(save_name))
if step in lr_decay_steps:
lr *= lr_decay
optimizer = torch.optim.SGD(params[8:], lr=lr, momentum=momentum, weight_decay=weight_decay)
if re_cnt:
tp, tf, fg, bg = 0., 0., 0, 0
train_loss = 0
step_cnt = 0
t.tic()
re_cnt = False
| {
"content_hash": "0104f71d3b6ce25f33ada2da2cc958ad",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 117,
"avg_line_length": 30.693989071038253,
"alnum_prop": 0.632544062666904,
"repo_name": "TheRevanchist/rcnn_for_relab",
"id": "a2af0c552f715e91e3e831947df85a21622f83f0",
"size": "5617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "train.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "17316"
},
{
"name": "C++",
"bytes": "744"
},
{
"name": "Cuda",
"bytes": "13073"
},
{
"name": "Python",
"bytes": "500306"
},
{
"name": "Shell",
"bytes": "434"
}
],
"symlink_target": ""
} |
package com.rudolfschmidt.alkun.sockets;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ServerSocketConnection {
public static void open() throws IOException {
ExecutorService executorService = Executors.newCachedThreadPool();
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
ClientConnection clientConnection = new ClientConnection(clientSocket);
executorService.execute(clientConnection);
}
}
}
| {
"content_hash": "c9c35a795dcafbc456fdf3ddea5a1a06",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 83,
"avg_line_length": 35.26315789473684,
"alnum_prop": 0.7328358208955223,
"repo_name": "rudolfschmidt/alkun",
"id": "e41b46a47f1bd91dba3e0e1617c5f01408abece3",
"size": "670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "legacy/sockets/ServerSocketConnection.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "44198"
},
{
"name": "Shell",
"bytes": "132"
}
],
"symlink_target": ""
} |