prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
<|fim_middle|>
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | invalid.append(p)
continue |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
<|fim_middle|>
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
<|fim_middle|>
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | invalid.append(p)
continue |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
<|fim_middle|>
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | invalid.append(p) |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
<|fim_middle|>
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | return [] |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
<|fim_middle|>
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | found = True |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
<|fim_middle|>
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | missing.add("%s->%s" % (k, mgr.resource_type.service))
continue |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
<|fim_middle|>
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | continue |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
<|fim_middle|>
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set)) |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
<|fim_middle|>
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | all_invalid.append((k, perm_set)) |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
<|fim_middle|>
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing)))) |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
<|fim_middle|>
<|fim▁end|> | raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid))))) |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def <|fim_middle|>(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def test_iam_permissions_validity(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | check_permissions |
<|file_name|>test_iamgen.py<|end_file_name|><|fim▁begin|># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch.filter(perm_db[s], a):
invalid.append(p)
continue
elif a not in perm_db[s]:
invalid.append(p)
if not invalid:
return []
return [(path, invalid)]
def <|fim_middle|>(self):
cfg = Config.empty()
missing = set()
all_invalid = []
perms = load_data('iam-actions.json')
for k, v in manager.resources.items():
p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
invalid = []
# if getattr(mgr, 'permissions', None):
# print(mgr)
found = False
for s in (mgr.resource_type.service,
getattr(mgr.resource_type, 'permission_prefix', None)):
if s in perms:
found = True
if not found:
missing.add("%s->%s" % (k, mgr.resource_type.service))
continue
invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k))
for n, a in v.action_registry.items():
p['actions'] = [n]
invalid.extend(
self.check_permissions(
perms, a({}, mgr).get_permissions(),
"{k}.actions.{n}".format(k=k, n=n)))
for n, f in v.filter_registry.items():
if n in ('or', 'and', 'not', 'missing'):
continue
p['filters'] = [n]
invalid.extend(
self.check_permissions(
perms, f({}, mgr).get_permissions(),
"{k}.filters.{n}".format(k=k, n=n)))
if invalid:
for k, perm_set in invalid:
perm_set = [i for i in perm_set
if not i.startswith('elasticloadbalancing')]
if perm_set:
all_invalid.append((k, perm_set))
if missing:
raise ValueError(
"resources missing service %s" % ('\n'.join(sorted(missing))))
if all_invalid:
raise ValueError(
"invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
<|fim▁end|> | test_iam_permissions_validity |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling <|fim▁hole|> status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()<|fim▁end|> | def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0: |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
<|fim_middle|>
<|fim▁end|> | pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled() |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
<|fim_middle|>
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries)) |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
<|fim_middle|>
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json()) |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
<|fim_middle|>
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
<|fim_middle|>
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
<|fim_middle|>
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
<|fim_middle|>
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json() |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
<|fim_middle|>
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json() |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
<|fim_middle|>
<|fim▁end|> | solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled() |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
<|fim_middle|>
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json()) |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
<|fim_middle|>
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | raise exception.solverError(json.dumps(status["errors"])) |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
<|fim_middle|>
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | return self.getSolution(solverId) |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
<|fim_middle|>
raise exception.UserCancelled()
<|fim▁end|> | raise exception.InternalError("Timed out waiting for solver") |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def <|fim_middle|>(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | __init__ |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def <|fim_middle|>(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | validateReply |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def <|fim_middle|>(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | create |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def <|fim_middle|>(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | delete |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def <|fim_middle|>(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | stop |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def <|fim_middle|>(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | getStatus |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def <|fim_middle|>(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def createAndWait(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | getSolution |
<|file_name|>kangrouter.py<|end_file_name|><|fim▁begin|>import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_factor=0.75)
self.session = requests.Session()
self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT,
HTTPAdapter(max_retries=retries))
def validateReply(self,req):
if req.status_code >= 400 and req.status_code <= 500:
try:
j = req.json()
except ValueError:
raise exception.InternalError(req.text,req.status_code)
raise exception.jsonToException(req.json())
def create(self,problem,**kwargs):
path = self.pathbase
payload=json.dumps(problem)
params = self.params.copy()
params.update(kwargs)
req = self.session.post(path,
params=params,
headers=self.headers,
data=payload)
self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def stop(self,solverId):
path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
def getSolution(self,solverId):
path = "{base}/{solverId}/solution".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return req.json()
# polling
def <|fim_middle|>(self,problem,cancel,**kwargs):
solverId = self.create(problem,**kwargs)
timeout = 300
while not cancel() and timeout>0:
status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
<|fim▁end|> | createAndWait |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage<|fim▁hole|> def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())<|fim▁end|> | def get_node(self):
return self.node
def get_children(self):
return self.children |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
<|fim_middle|>
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n" |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
<|fim_middle|>
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
<|fim_middle|>
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.node |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
<|fim_middle|>
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.children |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
<|fim_middle|>
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | self.node = node |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
<|fim_middle|>
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | self.children = children |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
<|fim_middle|>
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.references |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
<|fim_middle|>
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.slotted |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
<|fim_middle|>
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | self.slotted = slotted |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
<|fim_middle|>
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.emailMessage |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
<|fim_middle|>
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n" |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
<|fim_middle|>
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
<|fim_middle|>
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
<|fim_middle|>
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference] |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
<|fim_middle|>
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
<|fim_middle|>
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info()) |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
<|fim_middle|>
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | verbose = "true" |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
<|fim_middle|>
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
<|fim_middle|>
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | continue |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
<|fim_middle|>
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | continue |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
<|fim_middle|>
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId) |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
<|fim_middle|>
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | references = msg['references']
referenceIds = re.findall("<(.*)>", references) |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def <|fim_middle|>(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | __init__ |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def <|fim_middle|>(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | get_node |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def <|fim_middle|>(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | get_children |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def <|fim_middle|>(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | set_node |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def <|fim_middle|>(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | set_children |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def <|fim_middle|>(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | get_references |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def <|fim_middle|>(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | is_slotted |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def <|fim_middle|>(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | set_slotted |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def <|fim_middle|>(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | get_message |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def <|fim_middle|>(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | __repr__ |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def <|fim_middle|>(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | handleNode |
<|file_name|>smart-patcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return patchMessageReferenceNode[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def <|fim_middle|>(patchMessageReferenceNode) :
ref_keys = patchMessageReferenceNode.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = patchMessageReferenceNode[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = patchMessageReferenceNode[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "--------------RESULT--------------")
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
<|fim▁end|> | makeChildren |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")<|fim▁end|> | import MySQLdb
class DatabaseHandler: |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
<|fim_middle|>
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit() |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
<|fim_middle|>
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | pass |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
<|fim_middle|>
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
<|fim_middle|>
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit() |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
<|fim_middle|>
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | isDeleteFlag = 0
break |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
<|fim_middle|>
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | print "Reserve " + tableName |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
<|fim_middle|>
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`") |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def <|fim_middle|>(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | __init__ |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def <|fim_middle|>(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | is_delete |
<|file_name|>DatabaseHandler.py<|end_file_name|><|fim▁begin|>import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def <|fim_middle|>(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', '[email protected]', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
<|fim▁end|> | Clean_Database |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)<|fim▁hole|> ['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
)
def downgrade():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
)
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount')<|fim▁end|> | op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity', |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
<|fim_middle|>
def downgrade():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
)
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount')
<|fim▁end|> | """Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)
op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity',
['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
) |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)
op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity',
['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
)
def downgrade():
<|fim_middle|>
<|fim▁end|> | """Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
)
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount') |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)
op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity',
['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
)
def downgrade():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
<|fim_middle|>
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount')
<|fim▁end|> | op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
) |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def <|fim_middle|>():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)
op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity',
['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
)
def downgrade():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
)
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount')
<|fim▁end|> | upgrade |
<|file_name|>97bbc733896c_create_oauthclient_tables.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'extra_data',
sqlalchemy_utils.JSONType(),
nullable=False),
sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'client_id')
)
op.create_table(
'oauthclient_useridentity',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('method', sa.String(length=255), nullable=False),
sa.Column('id_user', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ),
sa.PrimaryKeyConstraint('id', 'method')
)
op.create_index(
'useridentity_id_user_method', 'oauthclient_useridentity',
['id_user', 'method'], unique=True
)
op.create_table(
'oauthclient_remotetoken',
sa.Column('id_remote_account', sa.Integer(), nullable=False),
sa.Column('token_type', sa.String(length=40), nullable=False),
sa.Column(
'access_token',
sqlalchemy_utils.EncryptedType(),
nullable=False),
sa.Column('secret', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(
['id_remote_account'], [u'oauthclient_remoteaccount.id'],
name='fk_oauthclient_remote_token_remote_account'
),
sa.PrimaryKeyConstraint('id_remote_account', 'token_type')
)
def <|fim_middle|>():
"""Downgrade database."""
ctx = op.get_context()
insp = Inspector.from_engine(ctx.connection.engine)
op.drop_table('oauthclient_remotetoken')
for fk in insp.get_foreign_keys('oauthclient_useridentity'):
if fk['referred_table'] == 'accounts_user':
op.drop_constraint(
op.f(fk['name']),
'oauthclient_useridentity',
type_='foreignkey'
)
op.drop_index(
'useridentity_id_user_method',
table_name='oauthclient_useridentity')
op.drop_table('oauthclient_useridentity')
op.drop_table('oauthclient_remoteaccount')
<|fim▁end|> | downgrade |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()<|fim▁hole|><|fim▁end|> | if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
<|fim_middle|>
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
<|fim▁end|> | pass |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
<|fim_middle|>
<|fim▁end|> | """
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
<|fim_middle|>
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
<|fim▁end|> | raise GCMError(response.reason) |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
<|fim_middle|>
return True
<|fim▁end|> | raise GCMError(repr(body)) |
<|file_name|>android.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def <|fim_middle|>(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
<|fim▁end|> | send |
<|file_name|>ar1TestScript.py<|end_file_name|><|fim▁begin|>from pybrain.rl.environments.timeseries.maximizereturntask import DifferentialSharpeRatioTask
from pybrain.rl.environments.timeseries.timeseries import AR1Environment, SnPEnvironment
from pybrain.rl.learners.valuebased.linearfa import Q_LinFA
from pybrain.rl.agents.linearfa import LinearFA_Agent
from pybrain.rl.experiments import ContinuousExperiment
from matplotlib import pyplot
"""
This script aims to create a trading model that trades on a simple AR(1) process
"""
env=AR1Environment(2000)
task=DifferentialSharpeRatioTask(env)
learner = Q_LinFA(2,1)
agent = LinearFA_Agent(learner)
exp = ContinuousExperiment(task,agent)
from decimal import Decimal
ts=env.ts.tolist()
exp.doInteractionsAndLearn(1999)
actionHist=env.actionHistory
pyplot.plot(ts[0])
pyplot.plot(actionHist)
pyplot.show()
#snp_rets=env.importSnP().tolist()[0]
#print(snp_rets.tolist()[0])
#pyplot.plot(snp_rets)
#pyplot.show()
<|fim▁hole|>#cumret= cumsum(multiply(ts,actionHist))
#exp.doInteractions(200)<|fim▁end|> | |
<|file_name|>node.py<|end_file_name|><|fim▁begin|># Ant
#
# Copyright (c) 2012, Gustav Tiger <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<|fim▁hole|># 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.
import collections
import threading
import logging
import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start()
def new_channel(self, ctype):
channel = Channel(0, self, self.ant)
self.channels[0] = channel
channel._assign(ctype, 0x00)
return channel
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(('burst', channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(('broadcast', channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == 'broadcast':
self.channels[channel].on_broadcast_data(data)
elif data_type == 'burst':
self.channels[channel].on_burst_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()<|fim▁end|> | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
<|file_name|>node.py<|end_file_name|><|fim▁begin|># Ant
#
# Copyright (c) 2012, Gustav Tiger <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
import collections
import threading
import logging
import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
<|fim_middle|>
<|fim▁end|> | def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start()
def new_channel(self, ctype):
channel = Channel(0, self, self.ant)
self.channels[0] = channel
channel._assign(ctype, 0x00)
return channel
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(('burst', channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(('broadcast', channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == 'broadcast':
self.channels[channel].on_broadcast_data(data)
elif data_type == 'burst':
self.channels[channel].on_burst_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join() |
<|file_name|>node.py<|end_file_name|><|fim▁begin|># Ant
#
# Copyright (c) 2012, Gustav Tiger <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
import collections
import threading
import logging
import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
def __init__(self):
<|fim_middle|>
def new_channel(self, ctype):
channel = Channel(0, self, self.ant)
self.channels[0] = channel
channel._assign(ctype, 0x00)
return channel
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(('burst', channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(('broadcast', channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == 'broadcast':
self.channels[channel].on_broadcast_data(data)
elif data_type == 'burst':
self.channels[channel].on_burst_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()
<|fim▁end|> | self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start() |
<|file_name|>node.py<|end_file_name|><|fim▁begin|># Ant
#
# Copyright (c) 2012, Gustav Tiger <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
import collections
import threading
import logging
import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start()
def new_channel(self, ctype):
<|fim_middle|>
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(('burst', channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(('broadcast', channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == 'broadcast':
self.channels[channel].on_broadcast_data(data)
elif data_type == 'burst':
self.channels[channel].on_burst_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()
<|fim▁end|> | channel = Channel(0, self, self.ant)
self.channels[0] = channel
channel._assign(ctype, 0x00)
return channel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.