小编Mar*_*icu的帖子

从XHR请求获取BLOB数据

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://static.reddit.com/reddit.com.header.png', true);

xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  if (this.status == 200) {
    var uInt8Array = new Uint8Array(this.response);
    var byte3 = uInt8Array[4]; 

    var bb = new WebKitBlobBuilder();
    bb.append(xhr.response);
    var blob = bb.getBlob('image/png'); 
    var base64 = window.btoa(blob);
    alert(base64);

  }
};

xhr.send();
Run Code Online (Sandbox Code Playgroud)

基本上,我在这里尝试做的是检索图像,并将其转换为base64.

通过阅读这里的评论,它说"当然.在将资源作为ArrayBuffer获取后,从中创建一个blob.一旦你有了,你可以直接对文件/ blob进行base64编码(window.btoa())或FileReader. readAsDataURL()".

然而,window.btoa()只是[对象blob],而我需要从图像中获取二进制文件,以便我可以将其转换为base64并使用数据将其显示在img标记中:

谁知道如何实现这一目标?

先感谢您!

javascript webkit blob xmlhttprequest

35
推荐指数
4
解决办法
8万
查看次数

Python词法分析 - 逻辑行和复合语句

如果这是一个愚蠢的问题,请提前道歉,但我似乎无法理解以下内容

所以我理解:

逻辑行的结尾由令牌NEWLINE表示

这意味着定义Python语法的方式是结束逻辑行的唯一方法是使用\n令牌.

物理线也是如此(相当于EOL,这是您在编写文件时使用的平台的EOL,但仍然\n通过Python 转换为通用.

逻辑行可以或不可以等同于一个或多个物理行,但通常它是一个,并且大多数情况下,如果您编写干净的代码,它就是一个.

在某种意义上说:

foo = 'some_value'  # 1 logical line = 1 physical  
foo, bar, baz = 'their', 'corresponding', 'values'  # 1 logical line = 1 physical
some_var, another_var = 10, 10; print(some_var, another_var); some_fn_call()

# the above is still still 1 logical line = 1 physical line
# because ; is not a terminator per se but a delimiter
# since Python doesn't use EBNF exactly but rather …
Run Code Online (Sandbox Code Playgroud)

python bnf python-3.x python-internals

8
推荐指数
1
解决办法
512
查看次数

为什么读取整个文件占用的 RAM 大于其在磁盘上的大小?

警告

This is NOT a duplicate of this. I'm not interested in finding out my memory consumption or the matter, as I'm already doing that below. The question is WHY the memory consumption is like this.

Also, even if I did need a way to profile my memory do note that guppy (the suggested Python memory profiler in the aforementioned link does not support Python 3 and the alternative guppy3 does not give accurate results whatsoever yielding in results …

python storage psutil

7
推荐指数
1
解决办法
980
查看次数

为什么代理对象反映的变化超出了目标对象?

我想对Proxy对象进行一些试验,并得到了一些意外的结果,如下所示:

测试脚本

function Person(first, last, age) {
  this.first = first;
  this.last = last;
  this.age = age;
}

Person.prototype.greeting = function () {
  return `Hello my name is ${this.first} and I am ${this.age} years old`;
};
Run Code Online (Sandbox Code Playgroud)

因此,在跟踪prototype对象的修改方式时,我添加了以下包装器:

let validator = {
    set: function(target, key, value) {
        console.log(`The property ${key} has been updated with ${value}`);
        target[key] = value;
        return true;
    }
};

Person.prototype = new Proxy(Person.prototype, validator);

let george = new Person('George', 'Clooney', 55);

Person.prototype.farewell = function () …
Run Code Online (Sandbox Code Playgroud)

javascript prototype function-prototypes javascript-objects

7
推荐指数
1
解决办法
93
查看次数

组合 Sklearn Pipeline 中的功能

我想使用包括 aTfidfVectorizer和 a 的管道SVC。然而,在这之间,我想将从非文本数据中提取的一些特征连接到TfidfVectorizer.

我尝试创建一个自定义类(基于本教程的方法)来执行此操作,但这似乎不起作用。

这是我到目前为止所尝试过的:

pipeline = Pipeline([
    ('tfidf', TfidfVectorizer()),
    ('transformer', CustomTransformer(one_hot_feats)),
    ('clf', MultinomialNB()),
])

parameters = {
    'tfidf__min_df': (5, 10, 15, 20, 25, 30),
    'tfidf__max_df': (0.8, 0.9, 1.0),
    'tfidf__ngram_range': ((1, 1), (1, 2)),
    'tfidf__norm': ('l1', 'l2'),
    'clf__alpha': np.linspace(0.1, 1.5, 15),
    'clf__fit_prior': [True, False],
}

grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1)
grid_search.fit(df["short description"], labels)
Run Code Online (Sandbox Code Playgroud)

这是CustomTransformer班级

class CustomTransformer(TransformerMixin):
"""Class that concatenates the one hot encode category feature with the …
Run Code Online (Sandbox Code Playgroud)

python scikit-learn

6
推荐指数
1
解决办法
5528
查看次数

Django:HTML表单操作指向使用2个参数查看(或url?)

大约一周前开始学习django并碰壁.真的很感激任何启蒙......

models.py

class data(models.Model):
    course = models.CharField(max_length = 250)

    def __str__(self):
        return self.course
Run Code Online (Sandbox Code Playgroud)

HTML

将models.course中的对象转换为schlist

<link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %}  method="GET">
      <div>
        <h4 style="font-family:verdana;">First Course: </h4>
        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% endfor %}
        </select>
      </div>
      </br>
      <div>
        <h4 style="font-family:verdana;">Second Course:</h4>
        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% …
Run Code Online (Sandbox Code Playgroud)

html django django-urls django-forms django-views

5
推荐指数
2
解决办法
2万
查看次数

如何扩展 PythonOperator

我正在尝试定制我的 PythonOperator 并将其放置在 $AIRFLOW_HOME/plugins 下,如下所示:

class MyPythonOperator(PythonOperator):

    def my_callable(param1, param2, param3):
        # do something

    @apply_defaults
    def __init__(self, task_id, *args, **kwargs):

        super(MyPythonOperator, self).__init__(
            task_id=task_id,  
            python_callable = self.my_callable,
            provide_context = True,
            *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

然后我定义了一个airflow dag代码,非常简单,只有两个任务:

args = {
    'owner': 'airflow',
    'start_date': airflow.utils.dates.days_ago(2),
}

dag = DAG(
    dag_id='example_workflow',
    default_args=args,
    schedule_interval='0 0 * * *',
    dagrun_timeout=timedelta(minutes=60),
)


task1 = MyPythonOperator(
    task_id='task1',
    params={'param1': 'param1_value',
            'param2': 'param2_value',
            'param3': 'param3_value'},
    dag=dag
)

task2 = MyPythonOperator(
    task_id='task2',
    params={'param1': 'param1_value',
            'param2': 'param2_value',
            'param2': 'param3_value'},
    dag=dag
)

task1 >> task2 …
Run Code Online (Sandbox Code Playgroud)

python airflow

5
推荐指数
1
解决办法
3139
查看次数

您是否应该在Python的非库代码中将下划线_用作“访问修饰符指示符”?

介绍


因此,我已经对下划线字符(_)进行了一些研究。我知道它的大多数用例及其语义,因此我将它们放到下面作为回顾,最后我将得出一个问题,该问题更多是关于两个用例的概念性问题。

用例


  1. 要将最后的评估存储在解释器中(在解释器之外,它没有特殊的语义,并且未定义为单个字符)
  2. 在国际化上下文中,您将在其中导入诸如gettext别名为_
  3. 在十进制分组中以提高可见性(特别是进行3组分组,例如1_000_000)- 请注意,仅从Python 3.6开始可用

    例:

    1_000_000 == 10**6  # equals True
    x = 1_000
    print(x)  # yields 1000
    
    Run Code Online (Sandbox Code Playgroud)
  4. 为了“忽略”某些值,尽管我不会将其称为“忽略”,因为这些值仍会_像常规标识符一样进行评估和绑定。通常,我会找到比这更好的设计,因为我发现这是一种代码味道。多年来,我很少使用这种方法,因此,我想每当您认为需要使用它时,肯定可以改进设计以不使用它。

    例:

    for _ in range(10):
        # do stuff without _
        ping_a_server()
    
    # outside loop that still exists and it still has the last evaluated value
    print(_)  # would yield 9
    
    Run Code Online (Sandbox Code Playgroud)
  5. 尾随一个标识符(习惯上是为了避免名称与内置标识符或保留字冲突):

    class Automobile:
    
        def __init__(self, type_='luxury', class_='executive'):
            self.car_type = type_
            self.car_class …
    Run Code Online (Sandbox Code Playgroud)

python semantics

4
推荐指数
1
解决办法
135
查看次数

仅限getter的JavaScript ES6类

我想问一下,在ES6中如何才能在没有setter(readOnly)属性的情况下使用getter?为什么Webstorm告诉我这是一个错误?

这是我的代码:

class BasePunchStarter {

    constructor(id,name,manufacturer,description,genres,targetPrice) {
        if (new.target==BasePunchStarter) {
            throw new TypeError("BasePunchStarter class cannot be instantiated directly!");
        }
        if (typeof id =="number") {
            // noinspection JSUnresolvedVariable
            this.id = id;
        } else throw new TypeError("ID must be a number!");
        if (typeof name=="string") {
            // noinspection JSUnresolvedVariable
            this.name = name;
        } else throw new TypeError("Name must be a string!");
        if(typeof manufacturer=="string") {
            // noinspection JSUnresolvedVariable
            this.manufacturer = manufacturer;
        } else throw new TypeError("Manufacturer must be a string!");
        if (typeof description=="string") { …
Run Code Online (Sandbox Code Playgroud)

javascript getter getter-setter ecmascript-6 es6-class

3
推荐指数
1
解决办法
2952
查看次数

如何在数据集中的python中通过加权概率获得均匀分布?

我已经看过这个问题并且知道numpy.random.choice,但是我的问题略有不同。

鉴于此,我有一个数据集,如下所示:

dict ={"Number of polyps":[10,8,3,1,2,6,13],
        "Right ":[3,2,3,1,0,3,3],
        "Left":[2,2,4,15,6,7,1] }

dt = pd.DataFrame(dict)
Run Code Online (Sandbox Code Playgroud)

因此,它是:

Number of polyps  Right   Left
            10       3     2
             8       2     2
             3       3     4
             1       1    15
             2       0     6
             6       3     7
            13       3     1
Run Code Online (Sandbox Code Playgroud)

我需要按以下要求重新填充RightLeft

  1. 的总和Right,并Left等于Number of polyps
  2. 的值RightLeft来自加权概率它们的当前

例如,对于给定的行,如下所示:

Number of polyps  Right   Left
            10       3     2
Run Code Online (Sandbox Code Playgroud)

因此,对于此行,可能如下所示。这里0.6= 3/(3+2)0.4= 2/(3+2): …

python numpy probability pandas uniform-distribution

2
推荐指数
1
解决办法
66
查看次数