MakeFloat(CodeContext ctx, object obj) { try { return Converter.ConvertToDouble(obj); } catch { // one of the following fallbacks *might* work } if ((!Builtin.isinstance(obj, TypeCache.PythonType)) && Builtin.hasattr(ctx, obj, "__int__")) { object probablyInt = PythonCalls.Call(TypeCache.Int32, new object[] {obj}); return MakeFloat(ctx, probablyInt); } if ((!Builtin.isinstance(obj, TypeCache.PythonType)) && Builtin.hasattr(ctx, obj, "__long__")) { object probablyLong = PythonCalls.Call(TypeCache.BigInteger, new object[] {obj}); return MakeFloat(ctx, probablyLong); } throw PythonOps.TypeError("could not make number sufficiently floatesque"); }
/// <summary> /// Initializes the module for it's first usage. By default this calls PerformModuleReload with the /// the dictionary. /// </summary> /// <param name="codeContext">The CodeContext for the module.</param> /// <param name="optimizedGlobals">A list of globals which have optimize access. Contains at least all of the global variables reutrned by GetGlobalVariableNames.</param> protected internal virtual void Initialize(CodeContext/*!*/ codeContext, Dictionary<string/*!*/, PythonGlobal/*!*/>/*!*/ optimizedGlobals) { ContractUtils.RequiresNotNull(codeContext, "codeContext"); ContractUtils.RequiresNotNull(optimizedGlobals, "globals"); _codeContext = codeContext; PerformModuleReload(); }
public static object get_osfhandle(CodeContext context, int fd) { PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd); FileStream stream = pfile._stream as FileStream; if (stream != null) { return stream.Handle.ToPython(); } return -1; }
MakeUnsignedBigInteger(CodeContext ctx, object obj) { BigInteger result = MakeBigInteger(ctx, obj); if (result < 0) { throw PythonOps.TypeError("cannot make {0} unsigned", result); } return result; }
public static int setmode(CodeContext context, int fd, int flags) { PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd); int oldMode; if (flags == PythonNT.O_TEXT) { oldMode = pfile.SetMode(context, true) ? PythonNT.O_TEXT : PythonNT.O_BINARY; } else if (flags == PythonNT.O_BINARY) { oldMode = pfile.SetMode(context, false) ? PythonNT.O_TEXT : PythonNT.O_BINARY; } else { throw PythonOps.ValueError("unknown mode: {0}", flags); } return oldMode; }
public string __repr__(CodeContext context) { var attrs = from attr in PythonOps.GetAttrNames(context, this) where !attr.ToString().StartsWith("_") select string.Format("{0}={1}", attr, PythonOps.Repr(context, PythonOps.GetBoundAttr(context, this, attr.ToString())) ); return string.Format("{0}({1})", PythonOps.GetPythonTypeName(this), string.Join(",", attrs.ToArray()) ); }
public static PythonSocket.ssl sslwrap( CodeContext context, PythonSocket.socket socket, bool server_side, [DefaultParameterValue(null)] string keyfile, [DefaultParameterValue(null)] string certfile, [DefaultParameterValue(PythonSsl.CERT_NONE)]int certs_mode, [DefaultParameterValue(-1)]int protocol, [DefaultParameterValue(null)]string cacertsfile) { return new PythonSocket.ssl( context, socket, server_side, keyfile, certfile, certs_mode, protocol, cacertsfile ); }
private void BindParameters(CodeContext context, IDictionary args, int num_params_needed) { for(int i = 1; i <= num_params_needed; ++i) { string binding_name = Sqlite3.sqlite3_bind_parameter_name(this.st, i); if(string.IsNullOrEmpty(binding_name)) throw PythonSQLite.MakeProgrammingError("Binding {0} has no name, but you supplied a dictionary (which has only names).".Format(i)); // remove the leading colon binding_name = binding_name.Substring(1); if(args.Contains(binding_name)) BindParameter(context, i, maybeAdapt(context, args[binding_name])); else throw PythonSQLite.MakeProgrammingError("You did not supply a value for binding {0}.".Format(i)); } }
internal static PythonDictionary CertificateToPython(CodeContext context, X509Certificate cert, bool complete) { var dict = new CommonDictionaryStorage(); dict.AddNoLock("notAfter", ToPythonDateFormat(cert.GetExpirationDateString())); dict.AddNoLock("subject", IssuerToPython(context, cert.Subject)); if (complete) { dict.AddNoLock("notBefore", ToPythonDateFormat(cert.GetEffectiveDateString())); dict.AddNoLock("serialNumber", SerialNumberToPython(cert)); dict.AddNoLock("version", cert.GetCertHashString()); dict.AddNoLock("issuer", IssuerToPython(context, cert.Issuer)); } return new PythonDictionary(dict); }
internal static PythonType SSLError(CodeContext/*!*/ context) { return (PythonType)PythonContext.GetContext(context).GetModuleState("SSLError"); }
private static Exception ErrorDecoding(CodeContext context, params object[] args) { return PythonExceptions.CreateThrowable(SSLError(context), ArrayUtils.Insert("Error decoding PEM-encoded file ", args)); }
internal static X509Certificate2 ReadCertificate(CodeContext context, string filename) { string[] lines; try { lines = File.ReadAllLines(filename); } catch (IOException) { throw PythonExceptions.CreateThrowable(SSLError(context), "Can't open file ", filename); } X509Certificate2 cert = null; RSACryptoServiceProvider key = null; try { for (int i = 0; i < lines.Length; i++) { if (lines[i] == "-----BEGIN CERTIFICATE-----") { var certStr = ReadToEnd(lines, ref i, "-----END CERTIFICATE-----"); try { cert = new X509Certificate2(Convert.FromBase64String(certStr.ToString())); } catch (Exception e) { throw ErrorDecoding(context, filename, e); } } else if (lines[i] == "-----BEGIN RSA PRIVATE KEY-----") { var keyStr = ReadToEnd(lines, ref i, "-----END RSA PRIVATE KEY-----"); try { var keyBytes = Convert.FromBase64String(keyStr.ToString()); key = ParsePkcs1DerEncodedPrivateKey(context, filename, keyBytes); } catch (Exception e) { throw ErrorDecoding(context, filename, e); } } } } catch (InvalidOperationException e) { throw ErrorDecoding(context, filename, e.Message); } if (cert != null) { if (key != null) { try { cert.PrivateKey = key; } catch(CryptographicException e) { throw ErrorDecoding(context, filename, "cert and private key are incompatible", e); } } return cert; } throw ErrorDecoding(context, filename, "certificate not found"); }
public object CallParamsWithContext(CodeContext context, params object[] arg) { return ParamsMethodWithContext(context, arg); }
internal int Recompile(CodeContext context, object parameters) { sqlite3_stmt new_st = null; string tail = null; int rc = Sqlite3.sqlite3_prepare(this.db, this.sql, -1, ref new_st, ref tail); if(rc == Sqlite3.SQLITE_OK) { Statement new_stmt = new Statement(this.st.db, new_st, this.sql, tail); new_stmt.BindParameters(context, parameters); Sqlite3.sqlite3_finalize(this.st); this.st = new_st; } return rc; }
public object __le__(CodeContext context, [NotNull] ClosureCell other) => PythonOps.RichCompare(context, Value, other.Value, PythonOperationKind.LessThanOrEqual);
public string /*!*/ __repr__(CodeContext /*!*/ context) => $"<cell at 0x{IdDispenser.GetId(this):X}: {GetContentsRepr()}>";
public string /*!*/ __repr__(CodeContext /*!*/ context) { return(string.Format("<function {0} at {1}>", __name__, PythonOps.HexId(this))); }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = instance == null ? (object)this : new Method(this, instance, owner); return(true); }
public object __call__(CodeContext /*!*/ context, [ParamDictionary] IDictionary <object, object> dict, params object[] args) { return(PythonCalls.CallWithKeywordArgs(context, this, args, dict)); }
public object __call__(CodeContext /*!*/ context, params object[] args) { return(PythonCalls.Call(context, this, args)); }
public string /*!*/ __repr__(CodeContext /*!*/ context) { return(string.Format("slice({0}, {1}, {2})", PythonOps.Repr(context, start), PythonOps.Repr(context, stop), PythonOps.Repr(context, step))); }
private void BindParameter(CodeContext context, int index, object arg) { int rc; if(arg == null) rc = Sqlite3.sqlite3_bind_null(st, index); else if(arg is int) rc = Sqlite3.sqlite3_bind_int(st, index, (int)arg); else if(arg is bool) rc = Sqlite3.sqlite3_bind_int(st, index, (bool)arg ? 1 : 0); else if(arg is long) rc = Sqlite3.sqlite3_bind_int64(st, index, (long)arg); else if(arg is Microsoft.Scripting.Math.BigInteger) rc = Sqlite3.sqlite3_bind_int64(st, index, ((Microsoft.Scripting.Math.BigInteger)arg).ToInt64()); #if FEATURE_NUMERICS else if (arg is System.Numerics.BigInteger) rc = Sqlite3.sqlite3_bind_int64(st, index, (long)((System.Numerics.BigInteger)arg)); #endif else if(arg is float) rc = Sqlite3.sqlite3_bind_double(st, index, (float)arg); else if(arg is double) rc = Sqlite3.sqlite3_bind_double(st, index, (double)arg); else if(arg is string) rc = Sqlite3.sqlite3_bind_text(st, index, (string)arg, -1, Sqlite3.SQLITE_TRANSIENT); else if(arg is byte[]) rc = Sqlite3.sqlite3_bind_blob(this.st, index, (byte[])arg, -1, Sqlite3.SQLITE_TRANSIENT); else if(arg is PythonBuffer) { //TODO: see if there is a better way to do this PythonBuffer buffer = (PythonBuffer)arg; string s = buffer.__getslice__(0, null).ToString(); byte[] bytes = PythonSQLite.Latin1.GetBytes(s); rc = Sqlite3.sqlite3_bind_blob(this.st, index, bytes, -1, Sqlite3.SQLITE_TRANSIENT); } else throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0} - unsupported type {1}".Format(index, arg.GetType())); if(rc != Sqlite3.SQLITE_OK) throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0}: {1}".Format(index, Sqlite3.sqlite3_errmsg(db))); }
private bool needsAdaptation(CodeContext context, object value) { // TODO The check for primitive types could probably be cached like pysqlite does if(value == null || value is int || value is bool || value is long || value is Microsoft.Scripting.Math.BigInteger || value is float || value is double || value is string || value is byte[] || value is PythonBuffer) { object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol)); object type = DynamicHelpers.GetPythonType(value); object key = new PythonTuple(new[] { type, proto }); return PythonSQLite.adapters.ContainsKey(key); } else { return true; } }
public object __gt__(CodeContext context, [NotNull] ClosureCell other) => PythonOps.RichCompare(context, Value, other.Value, PythonOperationKind.GreaterThan);
public virtual object ParamsIntMethodWithContext(CodeContext context, params int[] args) { Debug.Assert(this != null && this is StrangeOverrides); return args; }
public object Call(CodeContext /*!*/ context, [ParamDictionary] IDictionary <object, object> kwArgs, params object[] args) { return(context.LanguageContext.CallWithKeywords(this, args, kwArgs)); }
public string __repr__(CodeContext context) { return(String.Format("<memory at {0}>", PythonOps.Id(this))); }
public void SetMemberAfter(CodeContext context, string name, object value) { TypeCache.Method.SetMember(context, this, name, value); }
private static RSACryptoServiceProvider ParsePkcs1DerEncodedPrivateKey(CodeContext context, string filename, byte[] x) { // http://tools.ietf.org/html/rfc3447#appendix-A.1.2 // RSAPrivateKey ::= SEQUENCE { // version Version, // modulus INTEGER, -- n // publicExponent INTEGER, -- e // privateExponent INTEGER, -- d // prime1 INTEGER, -- p // prime2 INTEGER, -- q // exponent1 INTEGER, -- d mod (p-1) // exponent2 INTEGER, -- d mod (q-1) // coefficient INTEGER, -- (inverse of q) mod p // otherPrimeInfos OtherPrimeInfos OPTIONAL // } // read header for sequence if ((x[0] & ClassMask) != ClassUniversal) { throw ErrorDecoding(context, filename, "failed to find universal class"); } else if ((x[0] & NumberMask) != UnivesalSequence) { throw ErrorDecoding(context, filename, "failed to read sequence header"); } // read length of sequence int offset = 1; int len = ReadLength(x, ref offset); // read version int version = ReadUnivesalInt(x, ref offset); if (version != 0) { // unsupported version throw new InvalidOperationException(String.Format("bad vesion: {0}", version)); } // read in parameters and initialize provider RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); RSAParameters parameters = new RSAParameters(); parameters.Modulus = ReadUnivesalIntAsBytes(x, ref offset); parameters.Exponent = ReadUnivesalIntAsBytes(x, ref offset); parameters.D = ReadUnivesalIntAsBytes(x, ref offset); parameters.P = ReadUnivesalIntAsBytes(x, ref offset); parameters.Q = ReadUnivesalIntAsBytes(x, ref offset); parameters.DP = ReadUnivesalIntAsBytes(x, ref offset); parameters.DQ = ReadUnivesalIntAsBytes(x, ref offset); parameters.InverseQ = ReadUnivesalIntAsBytes(x, ref offset); provider.ImportParameters(parameters); return provider; }
public void DeleteMember(CodeContext context, string name) { TypeCache.Method.DeleteMember(context, this, name); }
public object Call(CodeContext /*!*/ context, params object[] args) { return(context.LanguageContext.CallSplat(this, args)); }
private static PythonInvokeBinder GetSelfBinder(Binding.PythonInvokeBinder binder, CodeContext context) { return(context.LanguageContext.Invoke( new CallSignature(ArrayUtils.Insert(new Argument(ArgumentType.Simple), binder.Signature.GetArgumentInfos())) )); }
public static PythonDictionary _test_decode_cert(CodeContext context, string filename, [DefaultParameterValue(false)]bool complete) { var cert = ReadCertificate(context, filename); return CertificateToPython(context, cert, complete); }
public static PythonModule /*!*/ __new__(CodeContext /*!*/ context, PythonType /*!*/ cls, [ParamDictionary] IDictionary <object, object> kwDict0, params object[] /*!*/ args\u00F8) { return(__new__(context, cls, args\u00F8)); }
public void BindParameters(CodeContext context, object parameters) { if(bound) this.ClearParameters(); int num_params_needed = Sqlite3.sqlite3_bind_parameter_count(this.st); if(parameters == null) { if(num_params_needed > 0) throw PythonSQLite.MakeProgrammingError("parameters are required but not specified."); else return; } if(parameters is IDictionary) BindParameters(context, (IDictionary)parameters, num_params_needed); else if(parameters is IList) BindParameters(context, (IList)parameters, num_params_needed); else throw PythonSQLite.MakeProgrammingError("unknown parameter type"); bound = true; }
IList <object> IPythonMembersList.GetMemberNames(CodeContext context) { return(new List <object>(__dict__.Keys)); }
private void BindParameters(CodeContext context, IList args, int num_params_needed) { if(num_params_needed != args.Count) throw PythonSQLite.MakeProgrammingError("Incorrect number of bindings supplied."); for(int i = 0; i < args.Count; ++i) { BindParameter(context, i + 1, maybeAdapt(context, args[i])); } }
public static object __new__(CodeContext context, PythonType type, [NotNull] IReversible o) { return(o.__reversed__()); }
private object maybeAdapt(CodeContext context, object value) { return needsAdaptation(context, value) ? adaptValue(context, value) : value; }
public object view(CodeContext context, string view_name, object model) { var view = View(view_name, model); return view; }
private object adaptValue(CodeContext context, object value) { object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol)); object type = DynamicHelpers.GetPythonType(value); object key = new PythonTuple(new[] { type, proto }); object adapter; if(PythonSQLite.adapters.TryGetValue(key, out adapter)) { object adapted = PythonCalls.Call(context, adapter, value); return adapted; } // TODO: Use proto? Any value whatsoever? object conform; if(context.LanguageContext.Operations.TryGetMember(value, "__conform__", out conform)) { object adapted = PythonCalls.Call(context, conform, proto); if(adapted != null) { return adapted; } } return value; }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { owner = CheckGetArgs(context, instance, owner); value = new Method(_func, owner, DynamicHelpers.GetPythonType(owner)); return(true); }
public virtual object SomeMethodWithContext(CodeContext context, object arg) { Debug.Assert(this != null && this is StrangeOverrides); return arg; }
private static PythonTuple IssuerToPython(CodeContext context, string issuer) { var split = issuer.Split(','); object[] res = new object[split.Length]; for(int i = 0; i<split.Length; i++) { res[i] = PythonTuple.MakeTuple( IssuerFieldToPython(context, split[i].Trim()) ); } return PythonTuple.MakeTuple(res); }
public object CallWithContext(CodeContext context, object arg) { return SomeMethodWithContext(context, arg); }
private static PythonTuple IssuerFieldToPython(CodeContext context, string p) { if (String.Compare(p, 0, "CN=", 0, 3) == 0) { return PythonTuple.MakeTuple("commonName", p.Substring(3)); } else if (String.Compare(p, 0, "OU=", 0, 3) == 0) { return PythonTuple.MakeTuple("organizationalUnitName", p.Substring(3)); } else if (String.Compare(p, 0, "O=", 0, 2) == 0) { return PythonTuple.MakeTuple("organizationName", p.Substring(2)); } else if (String.Compare(p, 0, "L=", 0, 2) == 0) { return PythonTuple.MakeTuple("localityName", p.Substring(2)); } else if (String.Compare(p, 0, "S=", 0, 2) == 0) { return PythonTuple.MakeTuple("stateOrProvinceName", p.Substring(2)); } else if (String.Compare(p, 0, "C=", 0, 2) == 0) { return PythonTuple.MakeTuple("countryName", p.Substring(2)); } else if (String.Compare(p, 0, "E=", 0, 2) == 0) { return PythonTuple.MakeTuple("email", p.Substring(2)); } throw PythonExceptions.CreateThrowable(SSLError(context), "Unknown field: ", p); }
public object CallIntParamsWithContext(CodeContext context, params int[] arg) { return ParamsIntMethodWithContext(context, arg); }
Binding.FastBindResult <T> Binding.IFastInvokable.MakeInvokeBinding <T>(CallSite <T> site, Binding.PythonInvokeBinder binder, CodeContext context, object[] args) { // TODO: We can process any signature that isn't * or ** args for the 1st argument if (binder.Signature.IsSimple) { BaseMethodBinding binding = null; if (__self__ == null) { if (args.Length != 0) { binding = GetMethodBinding <T>(binder, GetTypeArgsSelfless <T>(), binding); if (binding != null) { return(new FastBindResult <T>( (T)(object)binding.GetSelflessTarget(), true )); } } } else { var selfBinder = GetSelfBinder(binder, context); if (args.Length == 0) { binding = new MethodBinding(selfBinder); } else { binding = GetMethodBinding <T>(selfBinder, GetTypeArgs <T>(), binding); } if (binding != null) { return(new FastBindResult <T>( (T)(object)binding.GetSelfTarget(), true )); } } } return(new Binding.FastBindResult <T>()); }
public object view(CodeContext context) { var view = View(); return view; }
public static object __new__(CodeContext context, [NotNull] PythonType cls, [NotNull] string @string) { throw PythonOps.TypeError("string argument without an encoding"); }