Lookup basic phone number information or send SMS messages
773195
def CLI(ctx, config, list_lookups):
    """"""
    loglevel = 'info'
    verbosity = getattr(logging, loglevel.upper(), 'INFO')
    #verbosity = logging.DEBUG
    ctx.obj = {
        'verbosity': verbosity,
        'logfile': None,
        'config': {'lookups': {}},
    }
    #logfmt = '%(levelname)-8s | %(message)s'
    logfmt = '%(message)s'
    logging.basicConfig(format=logfmt, level=verbosity)
    debug('CLI >  CWD="{0}"'.format(os.getcwd()))
    with open(CONFIG_FILE, 'ab+') as phonedb:
        phonedb.seek(0)
        rawdata = phonedb.read()
        if rawdata:
            data = json.loads(rawdata, object_pairs_hook=OrderedDict)
            debug(data)
            ctx.obj['config'] = data
            if 'lookups' not in ctx.obj['config']:
                ctx.obj['config']['lookups'] = {}

    if 'sms_gateways' not in ctx.obj['config']:
        """
        gwsorted = sorted(ctx.obj['config']['sms_gateways'].items())
        gwordered = OrderedDict()
        for (k, v) in gwsorted:
            gwordered[k] = v
        ctx.obj['config']['sms_gateways'] = gwordered
        """
        info('loading SMS gateways...')
        sms_gateways = {}
        with open('carrier-gateways', 'rb') as gateways:
            gwdata = gateways.read()
            import re
            re_carrier = r'(?P<carrier>\w+[\w\&\(\)\-\'\s]*[\w\)\(]+)\s+'
            re_gateway = r'10digitphonenumber(?P<gateway>\@\w[\w\.]*\w)\s+'
            gwre = re.compile(re_carrier + re_gateway)
            gws = gwre.findall(gwdata)
            for gw in gwre.finditer(gwdata):
                gwinfo = gw.groupdict()
                debug(gw.groupdict())
                sms_gateways[gwinfo['carrier']] = gwinfo['gateway']
            num_lines = len([l for l in gwdata.split('\n') if len(l)])
            debug('lines={0} ({1} / 2)'.format(num_lines/2, num_lines))
            debug('matches={0}'.format(len(data)))
        ctx.obj['config']['sms_gateways'] = sms_gateways
        with open(CONFIG_FILE, 'wb') as cfg:
            cfg.write(json.dumps(ctx.obj['config'], indent=2))
        info('SMS gateways written to config')

    if list_lookups:
        sms_updated = False
        from fuzzywuzzy import fuzz
        from fuzzywuzzy import process
        lookups = ctx.obj['config']['lookups']
        info('cached lookups:')
        for number, pinfo in lookups.iteritems():
            owner = pinfo['comment']
            common = pinfo['body']['national_format']
            carrier = pinfo['body']['carrier']['name']
            pntype = pinfo['body']['carrier']['type']
            info('  {0}: {1}'.format(owner, common))
            info('    - carrier: {0}'.format(carrier))
            info('    - type: {0}'.format(pntype))
            debug('    - unformatted: {0}'.format(number))
            if 'sms' not in lookups[number]:
                carriers = ctx.obj['config']['sms_gateways'].keys()
                fuzzy = process.extract(carrier, carriers)
                fuzz_max = 0
                result = []
                gateway_key = None
                for f in fuzzy:
                    if f[1] >= fuzz_max:
                        fuzz_max = f[1]
                        result.append(f[0])
                debug(result)
                if len(result) > 1:
                    if len(sorted(result)[0]) <= len(carrier):
                        gateway_key = sorted(result)[0]
                    else:
                        gateway_key = result[0]
                else:
                    gateway_key = result[0]
                gw_suffix = ctx.obj['config']['sms_gateways'][gateway_key]
                ctx.obj['config']['lookups'][number]['sms'] = '{0}{1}'.format(
                    number, gw_suffix)
                sms_updated = True
            info('    - SMS gateway: {0}'.format(
                ctx.obj['config']['lookups'][number]['sms']))
        if sms_updated:
            with open(CONFIG_FILE, 'wb') as cfg:
                cfg.write(json.dumps(ctx.obj['config'], indent=2))
        ctx.exit()
233478
private void loadData() {
		contacts.add(makeContact("Larry", "Streepy", "123 Some St.", "Apt. #26C", "New York", "NY", "10010",
				ContactType.BUSINESS, "Lorem ipsum..."));
		contacts.add(makeContact("Keith", "Donald", "456 WebFlow Rd.", "2", "Cooltown", "NY", "10001",
				ContactType.BUSINESS, "Lorem ipsum..."));
		contacts.add(makeContact("Steve", "Brothers", "10921 The Other Street", "", "Denver", "CO", "81234-2121",
				ContactType.PERSONAL, "Lorem ipsum..."));
		contacts.add(makeContact("Carlos", "Mencia", "4321 Comedy Central", "", "Hollywood", "CA", "91020",
				ContactType.PERSONAL, "Lorem ipsum..."));
		contacts.add(makeContact("Jim", "Jones", "1001 Another Place", "", "Dallas", "TX", "71212",
				ContactType.PERSONAL, "Lorem ipsum..."));
		contacts.add(makeContact("Jenny", "Jones", "1001 Another Place", "", "Dallas", "TX", "75201",
				ContactType.PERSONAL, "Lorem ipsum..."));
		contacts.add(makeContact("Greg", "Jones", "9 Some Other Place", "Apt. 12D", "Chicago", "IL", "60601",
				ContactType.PERSONAL, "Lorem ipsum..."));
	}
1137682
def send_messages(self, sms_messages):
        
        if not sms_messages:
            return
        
        num_sent = 0
        for message in sms_messages:
            if self._send(message):
                num_sent += 1
        return num_sent
254580
def phones(text):
    ''''''
    return imap(lambda m: m.group(0).replace('-', ''),
                REGEX_PHONE.finditer(text))
485302
def basic_info(user, keys):
    """"""

    table = formatting.KeyValueTable(['Title', 'Basic Information'])
    table.align['Title'] = 'r'
    table.align['Basic Information'] = 'l'

    table.add_row(['Id', user.get('id', '-')])
    table.add_row(['Username', user.get('username', '-')])
    if keys:
        for key in user.get('apiAuthenticationKeys'):
            table.add_row(['APIKEY', key.get('authenticationKey')])
    table.add_row(['Name', "%s %s" % (user.get('firstName', '-'), user.get('lastName', '-'))])
    table.add_row(['Email', user.get('email')])
    table.add_row(['OpenID', user.get('openIdConnectUserName')])
    address = "%s %s %s %s %s %s" % (
        user.get('address1'), user.get('address2'), user.get('city'), user.get('state'),
        user.get('country'), user.get('postalCode'))
    table.add_row(['Address', address])
    table.add_row(['Company', user.get('companyName')])
    table.add_row(['Created', user.get('createDate')])
    table.add_row(['Phone Number', user.get('officePhone')])
    if user.get('parentId', False):
        table.add_row(['Parent User', utils.lookup(user, 'parent', 'username')])
    table.add_row(['Status', utils.lookup(user, 'userStatus', 'name')])
    table.add_row(['PPTP VPN', user.get('pptpVpnAllowedFlag', 'No')])
    table.add_row(['SSL VPN', user.get('sslVpnAllowedFlag', 'No')])
    for login in user.get('unsuccessfulLogins', {}):
        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
        table.add_row(['Last Failed Login', login_string])
        break
    for login in user.get('successfulLogins', {}):
        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
        table.add_row(['Last Login', login_string])
        break

    return table
535242
def respond_to_contact_info(self, message):
        """"""
        contacts = self.load("contact_info", {})
        context = {
            "contacts": contacts,
        }
        contact_html = rendered_template("contact_info.html", context)
        self.say(contact_html, message=message)
593801
public static Intent newSmsIntent(Context context, String body, String[] phoneNumbers) {
        Uri smsUri;
        if (phoneNumbers == null || phoneNumbers.length==0) {
            smsUri = Uri.parse("smsto:");
        } else {
            smsUri = Uri.parse("smsto:" + Uri.encode(TextUtils.join(",", phoneNumbers)));
        }

        Intent intent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent = new Intent(Intent.ACTION_SENDTO, smsUri);
            intent.setPackage(Telephony.Sms.getDefaultSmsPackage(context));
        } else {
            intent = new Intent(Intent.ACTION_VIEW, smsUri);
        }

        if (body!=null) {
            intent.putExtra("sms_body", body);
        }

        return intent;
    }
89594
function SmsBatch (smsc, callback, smsarray) {
    var idx=0;

    // when message is processed move to next one otherwise call user applicationCB
    function InternalCB (data) {

        // [good or bad] let's notify user application
        if (data.status != 0) callback (data);

        // it's time to move to next message
        if (data.status <= 0) {
            if (++idx < smsarray.length) {
                new SmsRequest (smsc, InternalCB, smsarray [idx]);
            } else {
                callback ({status: 0});
            }
        }
    }

    // let's start by sending 1st SMS of the array
    new SmsRequest(smsc, InternalCB, smsarray [idx]);
}
1082858
def send_sms(body, from_phone, to, flash=False, fail_silently=False,
             auth_user=None, auth_password=None, connection=None):
    
    from sendsms.message import SmsMessage
    connection = connection or get_connection(
        username = auth_user,
        password = auth_password,
        fail_silently = fail_silently
    )
    return SmsMessage(body=body, from_phone=from_phone, to=to, \
        flash=flash, connection=connection).send()
685001
def smsc(self, smscNumber):
        
        if smscNumber != self._smscNumber:
            if self.alive:
                self.write('AT+CSCA="{0}"'.format(smscNumber))
            self._smscNumber = smscNumber
794339
def _number_type_helper(national_number, metadata):
    """"""
    if not _is_number_matching_desc(national_number, metadata.general_desc):
        return PhoneNumberType.UNKNOWN
    if _is_number_matching_desc(national_number, metadata.premium_rate):
        return PhoneNumberType.PREMIUM_RATE
    if _is_number_matching_desc(national_number, metadata.toll_free):
        return PhoneNumberType.TOLL_FREE
    if _is_number_matching_desc(national_number, metadata.shared_cost):
        return PhoneNumberType.SHARED_COST
    if _is_number_matching_desc(national_number, metadata.voip):
        return PhoneNumberType.VOIP
    if _is_number_matching_desc(national_number, metadata.personal_number):
        return PhoneNumberType.PERSONAL_NUMBER
    if _is_number_matching_desc(national_number, metadata.pager):
        return PhoneNumberType.PAGER
    if _is_number_matching_desc(national_number, metadata.uan):
        return PhoneNumberType.UAN
    if _is_number_matching_desc(national_number, metadata.voicemail):
        return PhoneNumberType.VOICEMAIL

    if _is_number_matching_desc(national_number, metadata.fixed_line):
        if metadata.same_mobile_and_fixed_line_pattern:
            return PhoneNumberType.FIXED_LINE_OR_MOBILE
        elif _is_number_matching_desc(national_number, metadata.mobile):
            return PhoneNumberType.FIXED_LINE_OR_MOBILE
        return PhoneNumberType.FIXED_LINE

    # Otherwise, test to see if the number is mobile. Only do this if certain
    # that the patterns for mobile and fixed line aren't the same.
    if (not metadata.same_mobile_and_fixed_line_pattern and
        _is_number_matching_desc(national_number, metadata.mobile)):
        return PhoneNumberType.MOBILE
    return PhoneNumberType.UNKNOWN
800822
def domestic_mobile_phone_number(value):
    

    try:
        parsed = phonenumbers.parse(value, 'GB')
    except NumberParseException:
        pass
    else:
        is_mobile = carrier._is_mobile(number_type(parsed))
        if is_mobile and phonenumbers.is_valid_number(parsed):
            return None
    raise ValidationError(MESSAGE_INVALID_PHONE_NUMBER)
178970
def message(from, to, body, callback_url=nil)
      callback = callback_url ? {:StatusCallback => callback_url} : {}
      Twilio.post("/SMS/Messages", :body => {:From => from, :To => to, :Body => body}.merge(callback))
    end
161011
public function checkPhone() {
    if (empty($this->phone)) {
      return ['result' => false, 'message' => 'Please specify a phone number.'];
    }

    $stripToDigits = preg_replace('/\D/', '', $this->phone);
    if (!preg_match('/\d{10}/', $stripToDigits)) {
      return [
        'result' => false,
        'message' =>
          'Phone must contain 10 digits, but formatting does not matter.'
      ];
    }
    $selector = ['&',
        'strict' => ['phone', $stripToDigits]
      ];
    if (isset($this->guid)) {
      $selector['!guid'] = $this->guid;
    }
    $test = Nymph::getEntity(
        ['class' => '\Tilmeld\Entities\User', 'skip_ac' => true],
        $selector
    );
    if (isset($test->guid)) {
      return ['result' => false, 'message' => 'Phone number is in use.'];
    }

    return [
      'result' => true,
      'message' => (
        isset($this->guid) ? 'Phone number is valid.' : 'Phone number is valid!'
      )
    ];
  }
1087856
def phonenumber_validation(data):
    
    from phonenumber_field.phonenumber import to_python
    phone_number = to_python(data)
    if not phone_number:
        return data
    elif not phone_number.country_code:
        raise serializers.ValidationError(_("Phone number needs to include valid country code (E.g +37255555555)."))
    elif not phone_number.is_valid():
        raise serializers.ValidationError(_('The phone number entered is not valid.'))

    return data
720461
def verify_sms_code(phone_number, code):
    
    params = {
        'mobilePhoneNumber': phone_number,
    }
    leancloud.client.post('/verifySmsCode/{0}'.format(code), params=params)
    return True
314892
def handle_inform(self, msg):
        """"""
        try:
            for func in self._inform_hooks.get(msg.name, []):
                func(msg)
        except Exception:
            self._logger.warning('Call to function "{0}" with message "{1}".'
                                 .format(func, msg), exc_info=True)
        super(_InformHookDeviceClient, self).handle_inform(msg)