问:
Difference between Game Engine vs Physics Engine vs Geometric modeling kernel
"The rendering engine generates animated 3D graphics by any of a number of methods (rasterization, ray-tracing etc.).

Instead of being programmed and compiled to be executed on the CPU or GPU directly, most often rendering engines are built upon one or multiple rendering application programming interfaces (APIs), such as Direct3D, OpenGL, or Vulkan which provide a software abstraction of the graphics processing unit (GPU). Low-level libraries such as DirectX, Simple DirectMedia Layer (SDL), and OpenGL are also commonly used in games as they provide hardware-independent access to other computer hardware such as input devices (mouse, keyboard, and joystick), network cards, and sound cards." - Game Engine

"UNISURF was a pioneering surface CAD/CAM system, designed to assist with car body design and tooling. It was developed by French engineer Pierre Bézier for Renault in 1968, and entered full use at the company in 1975.[1][2] By 1999, around 1,500 Renault employees made use of UNISURF for car design and manufacture." Advent of CAD/CAM Systems

"A geometric modeling kernel is a 3D solid modeling software component used in computer-aided design packages" Geometric Modeling Kernel

I am struggling to understand an underlying architecture of a geometric modeling kernels compared to the game engines and physics engines.

Questions:

Am I understand it correctly, that the geometric modeling kernels, are actually the low-level APIs, more specifically, a kernel loadable extensions, used specifically to handle the rendering of a geometric operations, like creating a boundary representation of an objects on the screen?

How are the geometric modeling kernels differ from the OpenGL-derived APIs? Are they also written in C++, or an older languages, since, I believe, they have appeared earlier?

Am I understand correctly, that the geometric modeling kernels, like ACIS, Parasolid are continuing to use it's own, proprietary, low-level modules, instead of OpenCL/OpenGL, or they are kind of mixed?

What is the architecture of the physics engine, in terms of an APIs. Is it using the OpenGL or other derived low-level graphics APIs? Let's say, Havoc, is it relying on other low-level API, say Direct3D?

答:
Geometric modeling kernel is a modeling kernel, it allows constructing or modifying geometry and has nothing to do with displaying this geometry on the screen. It also differs from model sculpturing applications, because the latter ones are used by artists, while modeling kernels are used by engineers, and hence, has very different inputs, even when constructing visually similar model.

Modern modeling kernels are usually accompanied by 3D renderer for displaying models. But this functionality is usually put into dedicated components within the framework. Platforms have only limited set of hardware accelerated graphics libraries like OpenGL, Vulkan and Direct3D, so that 3D graphics engine coming with modeling kernel usually relies on one of lower-level libraries. Historically, OpenGL was used by majority of industrial applications (in contrast to Games), but this might be not the same today.

The language in which modeling kernel is written might differ, but I believe the most are written in C++. As modeling kernels were started to be written in older days, they might inherit some intermediate languages, like CDL in OCCT (remnants have been removed since OCCT 7.0.0) or code originating from other languages (like from FORTRAN, popular in the past) - the modeling kernels most likely don't use these languages, but it might be figured out from source code, that C++ code of some algorithms was converted from FORTRAN at some step (but of course, you cannot check this point with proprietary kernels).

If you take a look onto components structure of Open CASCADE Technology, an open source solid modeling kernel, you will find that Visualization component implements interactive services for displaying models using OpenGL or other low-level graphic library, but OCCT-based application does not have to use it, and may consider displaying shapes using other libraries.

In attempt to generalize:

Graphics engine implements services for rendering existing geometry and implemented on top of low-level APIs like OpenGL. This includes implementation of shading/material model (Phong, PBR metallic-roughness), Camera definition and a bunch of other tools, not coming with low-level APIs.

Geometric modeling kernel implements data structures (like Boundary Representation or CSG), complex math for model construction by engineers (including primitives, fillets, Boolean operations) on exact geometry represented by B-Splines and similar (in contrast to artists-orientated tools which usually works on polygonal geometry). The framework may provide other tools, including graphics engine, but they usually separated from geometry kernel. Graphics engines usually do not work directly with B-Spline geometry, so that Geometry modeling kernel has to generate triangulation for rendering the geomery.

Physics engine implements only services related to physics simulation. Physics engine includes collision detection module. The project may also contains samples using some graphics library, but the kernel should not depend on any.

Game engine combines Graphics engine, Physics engine, Audio engine, and usually also provides some scripting language and other tools for simplifying game development.


来源: stackexchange

问:
Writing 1K images to disk using Task.async_stream in Elixir
I am downloading images through HTTP request with which I am getting a binary image, and writing it to a file such as

```<code>File.write(image_with_dir, image, [:binary]) |> File.close
</code>```

this whole operation of getting HTTP request and then writing it to disk is done in

```<code>|> List.flatten()
|> Enum.sort()
|> Task.async_stream(&(inline_process.(&1, images_directory)), max_concurrency: System.schedulers_online() * 2, timeout: :infinity)
|> Stream.run
</code>```

When decreasing max_concurrency the process got slow approx 2 minutes, also results of System.schedulers_online() is 8

but with current max_concurrency it faster but with this. Disk IO starts touching the limits

Purpose of writing those files is to send them to Dropbox with a batch of 1000 as dropbox upload session supports 1000 images at a time.

Is there any better way to write images to disk? maybe in memory but I don't know, any help would be wonderful also this operation is being done on Cuda GPU machine but I am not sure how I can use GPU for such purpose.

This process is user defined. user can ask for less/more than 1000 images and those can be one or multiple Task.async_stream's

答:
A Possible Elixir Approach

I am a newbie in Elixir, but you may try to use the ETS table to write them temporally into memory, but don't forget to wrap it with a GenServer as per the link recommendations. So the tutorial is for key/value cache, that I think it will be easy for you to adapt for your use case.

The Disk Approach

Is there any better way to write images to disk?

Linux OS have ram disks:

RAM disk is also known as RAM drive. It’s a portion of your RAM that are formated with a file system. You can mount it to a directory on your Linux system and use it as a disk partition.

How to Create a RAM Disk in Any Linux Distro

From the linked article I have extracted the main steps for you...

Create a dir:

```<code>sudo mkdir /tmp/ramdisk
</code>```

Mount it with the device name myramdisk and using the tmpfs file system with 10GB of ram disk space:

```<code>sudo mount -t tmpfs -o size=10G myramdisk /tmp/ramdisk
</code>```

NOTE: Adjust the 10G to your needs and available memory on your server.

Check it's mounted:

```<code>mount | tail -n 1
</code>```

You can unmout it at any time to reclaim the the memory:

```<code>sudo umount /tmp/ramdisk/
</code>```

Auto mount it on system boot by adding to /etc/fstab:

```<code>myramdisk  /tmp/ramdisk  tmpfs  defaults,size=10G,x-gvfs-show  0  0
</code>```

Benchmark it

Test write speed with:

```<code>sudo dd if=/dev/zero of=/tmp/ramdisk/zero bs=4k count=100000
</code>```

Test read speed with:

```<code>sudo dd if=/tmp/ramdisk/zero of=/dev/null bs=4k count=100000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am downloading images through HTTP request with which I am getting a binary image, and writing it to a file such as

File.write(image_with_dir, image, [:binary]) |> File.close

this whole operation of getting HTTP request and then writing it to disk is done in

|> List.flatten()
|> Enum.sort()
|> Task.async_stream(&(inline_process.(&1, images_directory)), max_concurrency: System.schedulers_online() * 2, timeout: :infinity)
|> Stream.run

When decreasing max_concurrency the process got slow approx 2 minutes, also results of System.schedulers_online() is 8

but with current max_concurrency it faster but with this. Disk IO starts touching the limits

Purpose of writing those files is to send them to Dropbox with a batch of 1000 as dropbox upload session supports 1000 images at a time.

Is there any better way to write images to disk? maybe in memory but I don't know, any help would be wonderful also this operation is being done on Cuda GPU machine but I am not sure how I can use GPU for such purpose.

This process is user defined. user can ask for less/more than 1000 images and those can be one or multiple Task.async_stream's

Body:
A Possible Elixir Approach

I am a newbie in Elixir, but you may try to use the ETS table to write them temporally into memory, but don't forget to wrap it with a GenServer as per the link recommendations. So the tutorial is for key/value cache, that I think it will be easy for you to adapt for your use case.

The Disk Approach

Is there any better way to write images to disk?

Linux OS have ram disks:

RAM disk is also known as RAM drive. It’s a portion of your RAM that are formated with a file system. You can mount it to a directory on your Linux system and use it as a disk partition.

How to Create a RAM Disk in Any Linux Distro

From the linked article I have extracted the main steps for you...

Create a dir:

sudo mkdir /tmp/ramdisk

Mount it with the device name myramdisk and using the tmpfs file system with 10GB of ram disk space:

sudo mount -t tmpfs -o size=10G myramdisk /tmp/ramdisk

NOTE: Adjust the 10G to your needs and available memory on your server.

Check it's mounted:

mount | tail -n 1

You can unmout it at any time to reclaim the the memory:

sudo umount /tmp/ramdisk/

Auto mount it on system boot by adding to /etc/fstab:

myramdisk  /tmp/ramdisk  tmpfs  defaults,size=10G,x-gvfs-show  0  0

Benchmark it

Test write speed with:

sudo dd if=/dev/zero of=/tmp/ramdisk/zero bs=4k count=100000

Test read speed with:

sudo dd if=/tmp/ramdisk/zero of=/dev/null bs=4k count=100000


问:
Cannot run program "mvn" although maven on path
Before marking this as duplicate please read carefully.
A gradle task (kotlin dsl) I am executing is executing a maven command in a sub directory. The weird thing is I have maven on the PATH variable both on System and User. If I navigate into that directory using the CMD or git bash I can execute any maven command.
So it can't be the issue of it simply not being in the environment variables. I actually had that issue in every project where a mvn command is executed by code.

fun cmd(vararg args: String, directory: File, printToStdout: Boolean = false): Pair<Int, String?> {
    val p = ProcessBuilder()
            .command(*args)
            .redirectErrorStream(true)
            .directory(directory)
            .start()
    val output = p.inputStream.bufferedReader().use {
        val lines = LinkedList<String>()
        it.lines().peek(lines::add).forEach { line ->
                println(line)
        }
        lines.joinToString(separator = "\n")
    }
    val exit = p.waitFor()
    return exit to output
}

```

<p>Calling it like so:</p>

<pre class="lang-kotlin prettyprint-override"><code>cmd("mvn", "install:install-file", "-q", "-Dfile=${project.projectDir.resolve("work/1.15.2-mojang-mapped.jar").absolutePath}", "-Dpackaging=jar", "-DgroupId=me.minidigger", "-DartifactId=minecraft-server", "-Dversion=\"$minecraftversion-SNAPSHOT\"", directory = project.projectDir)
</code>```

It results in:

```<code>java.io.IOException: Cannot run program "mvn" (in directory "....."): CreateProcess error=2, Das System kann die angegebene Datei nicht finden
</code>```

Edit: It shouldn't be the code, as others dont have this issue.
I am btw using windows 10

Update: so it appears that while "mvn" works when calling it manually, it has to be "mvn.bat" if called from code. Being forced to manually change and check that in the code does not seem like an optimal solution though. Especially because some of the code calling mvn is downloaded in the task and can't be edited manually before

答: Check what your ProcessBuilder.environment shows as available variables. You may have to define these variables yourself.

Body:
Before marking this as duplicate please read carefully.
A gradle task (kotlin dsl) I am executing is executing a maven command in a sub directory. The weird thing is I have maven on the PATH variable both on System and User. If I navigate into that directory using the CMD or git bash I can execute any maven command.
So it can't be the issue of it simply not being in the environment variables. I actually had that issue in every project where a mvn command is executed by code.

fun cmd(vararg args: String, directory: File, printToStdout: Boolean = false): Pair<Int, String?> {
    val p = ProcessBuilder()
            .command(*args)
            .redirectErrorStream(true)
            .directory(directory)
            .start()
    val output = p.inputStream.bufferedReader().use {
        val lines = LinkedList<String>()
        it.lines().peek(lines::add).forEach { line ->
                println(line)
        }
        lines.joinToString(separator = "\n")
    }
    val exit = p.waitFor()
    return exit to output
}

Calling it like so:

cmd("mvn", "install:install-file", "-q", "-Dfile=${project.projectDir.resolve("work/1.15.2-mojang-mapped.jar").absolutePath}", "-Dpackaging=jar", "-DgroupId=me.minidigger", "-DartifactId=minecraft-server", "-Dversion=\"$minecraftversion-SNAPSHOT\"", directory = project.projectDir)

It results in:

java.io.IOException: Cannot run program "mvn" (in directory "....."): CreateProcess error=2, Das System kann die angegebene Datei nicht finden

Edit: It shouldn't be the code, as others dont have this issue.
I am btw using windows 10

Update: so it appears that while "mvn" works when calling it manually, it has to be "mvn.bat" if called from code. Being forced to manually change and check that in the code does not seem like an optimal solution though. Especially because some of the code calling mvn is downloaded in the task and can't be edited manually before


问:
Numpy import failed
On an RPi2, I upgraded all my packages with pip-review and numpy does not work anymore.

I tried to uninstall and reinstall numpy though pip and apt but I'm getting no luck.

Apt installs numpy 1.12.1, if I try to install that it does not install through pip.

Pip installs numpy 1.16.4 fine, but when I go to run it I get the error below.

I have already run: sudo apt install libc6 libatlas-base-dev

Any help is appreciated.

```<code>Python 3.7.3 (default, May  8 2019, 18:07:21)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/numpy/core/__init__.py", line 40, in <module>
    from . import multiarray
  File "/usr/local/lib/python3.7/site-packages/numpy/core/multiarray.py", line 12, in <module>
    from . import overrides
  File "/usr/local/lib/python3.7/site-packages/numpy/core/overrides.py", line 6, in <module>
    from numpy.core._multiarray_umath import (
ImportError: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by /usr/local/lib/python3.7/site-packages/numpy/core/_multiarray_umath.cpython-37m-arm-linux-gnueabihf.so)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/usr/local/lib/python3.7/site-packages/numpy/core/__init__.py", line 71, in <module>
    raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
  your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
  1. Check that you are using the Python you expect (you're using /usr/local/bin/python3),
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy versions you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

     Note: this error has many possible causes, so please don't comment on
     an existing issue about this - open a new one instead.

Original error was: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by /usr/local/lib/python3.7/site-packages/numpy/core/_multiarray_umath.cpython-37m-arm-linux-gnueabihf.so)
</code>```

答: pip install numpy --global-option="-mfloat-abi=hard" --force-reinstall was the only answer that worked for me . The explanation is given in a thread on a slightly different problem see this link</p>

Title: Numpy import failed

Body:
On an RPi2, I upgraded all my packages with pip-review and numpy does not work anymore.

I tried to uninstall and reinstall numpy though pip and apt but I'm getting no luck.

Apt installs numpy 1.12.1, if I try to install that it does not install through pip.

Pip installs numpy 1.16.4 fine, but when I go to run it I get the error below.

I have already run: sudo apt install libc6 libatlas-base-dev

Any help is appreciated.

Python 3.7.3 (default, May  8 2019, 18:07:21)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/numpy/core/__init__.py", line 40, in <module>
    from . import multiarray
  File "/usr/local/lib/python3.7/site-packages/numpy/core/multiarray.py", line 12, in <module>
    from . import overrides
  File "/usr/local/lib/python3.7/site-packages/numpy/core/overrides.py", line 6, in <module>
    from numpy.core._multiarray_umath import (
ImportError: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by /usr/local/lib/python3.7/site-packages/numpy/core/_multiarray_umath.cpython-37m-arm-linux-gnueabihf.so)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/usr/local/lib/python3.7/site-packages/numpy/core/__init__.py", line 71, in <module>
    raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
  your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
  1. Check that you are using the Python you expect (you're using /usr/local/bin/python3),
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy versions you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

     Note: this error has many possible causes, so please don't comment on
     an existing issue about this - open a new one instead.

Original error was: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by /usr/local/lib/python3.7/site-packages/numpy/core/_multiarray_umath.cpython-37m-arm-linux-gnueabihf.so)


问:
Hive query: select a column based on the condition another columns values match some specific values, then create the match result as a new column
I have to some query and creat columns operations in HiveQL.

For example,

```<code>app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?
</code>```

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

```<code>app      keyword

app1     anybody, love
app4     I don't like this one
app6     damn you.
app8     xxx
app10    don't, love
app11    xxx
</code>```

It seems that I have to use nested query.

The logic is kind of like selecting the matched result rows and setting a matched results which should be saved in a list or something like this as a new column.

But I am not familiar enough with the HiveQL.

Could anyone help me?

Thanks in advances.

答:
In Hive you can use stack UDTF:

```<code>with keywords as (
select stack(4, --the number of tuples
'anybody', 'you', 'xxx', 'don\'t'
) as keyword
)

select t.app, k.keyword
from  mytable t
inner join keywords k
    on t.col1 like concat('%', k.keyword, '%')
</code>```

Also for older versions of hive join using like will not work, use cross join with stack and filter in the WHERE:

```<code>from  mytable t
cross join keywords k
where t.col1 like concat('%', k.keyword, '%')
</code>```

Body:
I have to some query and creat columns operations in HiveQL.

For example,

app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

app      keyword

app1     anybody, love
app4     I don't like this one
app6     damn you.
app8     xxx
app10    don't, love
app11    xxx

It seems that I have to use nested query.

The logic is kind of like selecting the matched result rows and setting a matched results which should be saved in a list or something like this as a new column.

But I am not familiar enough with the HiveQL.

Could anyone help me?

Thanks in advances.

Body:
In Hive you can use stack UDTF:

with keywords as (
select stack(4, --the number of tuples
'anybody', 'you', 'xxx', 'don\'t'
) as keyword
)

select t.app, k.keyword
from  mytable t
inner join keywords k
    on t.col1 like concat('%', k.keyword, '%')

Also for older versions of hive join using like will not work, use cross join with stack and filter in the WHERE:

from  mytable t
cross join keywords k
where t.col1 like concat('%', k.keyword, '%')


问:
Remove label from material input on focus and when leave focus
I am using angular material input with placeholder. When I focus on field I remove placeholder, but if I leave focus and field is empty I see transform animation, that I want to remove too.
in this image placeholder that has to be when field is empty.

And in this image I leave focus:

```<code><mat-form-field class="al-subscribe-form-field">
        <input formControlName="email" matInput type="email">
        <mat-placeholder  class="al-placeholder">{{'SHARED.ENTER_YOUR_EMAIL' | translate}}</mat-placeholder>
</mat-form-field>

.mat-focused .al-placeholder, .mat-form-field-invalid .al-placeholder {
    display: none!important;
}
</code>```

答:
```<code>    .mat-form-field-should-float .mat-form-field-label-wrapper {
        display: none!important;
    }
    .mat-focused .al-subscribe-form-placeholder,
    .mat-form-field-invalid .al-subscribe-form-placeholder {
        display: none!important;
}

<mat-from-field floatLabel="never"></mat-form-field>
</code>```

It solves my problem

Body:
I am using angular material input with placeholder. When I focus on field I remove placeholder, but if I leave focus and field is empty I see transform animation, that I want to remove too.
in this image placeholder that has to be when field is empty.

And in this image I leave focus:

<mat-form-field class="al-subscribe-form-field">
        <input formControlName="email" matInput type="email">
        <mat-placeholder  class="al-placeholder">{{'SHARED.ENTER_YOUR_EMAIL' | translate}}</mat-placeholder>
</mat-form-field>

.mat-focused .al-placeholder, .mat-form-field-invalid .al-placeholder {
    display: none!important;
}

Body:
    .mat-form-field-should-float .mat-form-field-label-wrapper {
        display: none!important;
    }
    .mat-focused .al-subscribe-form-placeholder,
    .mat-form-field-invalid .al-subscribe-form-placeholder {
        display: none!important;
}

<mat-from-field floatLabel="never"></mat-form-field>

It solves my problem


问:
How to set the one value with where condition
I have dataframe(df) like this

```<code>   key            name value
0    0          master     0
1    1           basic     0
2    2           clear     0
3    3            debu     0
</code>```

What I want to do is like this below

```<code>items = [master,master,basic,clear]

for i in items:   # loop the items
    df[where('name==@i')].value += 1     # increment each item
</code>```

Final output should be

```<code>   key            name value
0    0          master     2
1    1           basic     1
2    2           clear     1
3    3            debu     0
</code>```

How can I fetch the one value and increment ???

答:
Another way of doing it but not with as may options as @jezrael</p>

```<code>items = ['master','master','basic','clear']
l={i:items.count(i) for i in items}
df['value']=df['name'].map(l).fillna(0).astype(int)
df

key name    value
0   0   master  2
1   1   basic   1
2   2   clear   1
3   3   debu    0
</code>```

Body:
I have dataframe(df) like this

   key            name value
0    0          master     0
1    1           basic     0
2    2           clear     0
3    3            debu     0

What I want to do is like this below

items = [master,master,basic,clear]

for i in items:   # loop the items
    df[where('name==@i')].value += 1     # increment each item

Final output should be

   key            name value
0    0          master     2
1    1           basic     1
2    2           clear     1
3    3            debu     0

How can I fetch the one value and increment ???

Body:
Another way of doing it but not with as may options as @jezrael

items = ['master','master','basic','clear']
l={i:items.count(i) for i in items}
df['value']=df['name'].map(l).fillna(0).astype(int)
df

key name    value
0   0   master  2
1   1   basic   1
2   2   clear   1
3   3   debu    0


问:
how do make this show/hide more concise?
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

```<code>jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});
</code>```

Each show/hide uses its own ID, so I simply group ids like so:

```<code>jQuery('#show-hide1, #show-hide2').hide();
</code>```

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

```<code>jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});
</code>```

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

答:
Like Andy's but slightly different, to allow a different structure of ID's

HTML

```<code><a href="#div1" class="toggleLink">1</a>
<a href="#div2" class="toggleLink">2</a>
<a href="#div3" class="toggleLink">3</a>
<a href="#div4" class="toggleLink">4</a>

<div id="div1">div 1</div>
<div id="div2">div 2</div>
<div id="div3">div 3</div>
<div id="div4">div 4</div>
</code>```

JS

```<code>$(function(){
    $('.toggleLink').click(function(ev){
       $($(this).attr('href')).toggle(400);
       ev.preventDefault();
    });
});
</code>```

Example at JSFiddle

ContentLicense: CC BY-SA 3.0

Body:
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});

Each show/hide uses its own ID, so I simply group ids like so:

jQuery('#show-hide1, #show-hide2').hide();

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

Body:
Like Andy's but slightly different, to allow a different structure of ID's

HTML

<a href="#div1" class="toggleLink">1</a>
<a href="#div2" class="toggleLink">2</a>
<a href="#div3" class="toggleLink">3</a>
<a href="#div4" class="toggleLink">4</a>

<div id="div1">div 1</div>
<div id="div2">div 2</div>
<div id="div3">div 3</div>
<div id="div4">div 4</div>

JS

$(function(){
    $('.toggleLink').click(function(ev){
       $($(this).attr('href')).toggle(400);
       ev.preventDefault();
    });
});

Example at JSFiddle


问:
× TypeError: Cannot read property 'map' of undefined. found error
Can anyone pls help me out with this problem?

const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />
  } else {
    return (

        {users.map((user) => (
          <UserItem key={users.id} user={user} />
        ))}

    )
  }
}
```

答:
use conditional operator && on before map

```<code>const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />
  } else {
    return (
      <div style={userStyle}>
        {users && users.map((user) => (
          <UserItem key={user.id} user={user} />
        ))}
      </div>
    )
  }
}
</code>```

Body:
use conditional operator && on before map

const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />
  } else {
    return (
      <div style={userStyle}>
        {users && users.map((user) => (
          <UserItem key={user.id} user={user} />
        ))}
      </div>
    )
  }
}


问:
How to tell teamcity agent, which aws account to run terraform to
I spun up TeamCity into a Kubernetes cluster. I have one deployment for the TeamCity server and one deployment for the TeamCity build agent. When I run Terraform on the TeamCity build agent, it creates resources in the same AWS account as the EC2 instance which is hosting TeamCity Kubernetes cluster.

I would like to run a build, which creates AWS resources in a separate AWS account. My thinking is to assign an AWS access key and secret key to the TeamCity server and pass them to the TeamCity build agent, but I don't know how the work flow is going to be.

Currently, I have declared AWS access key and secret keys as environment variables on the build but they are not getting passed to agent. My build steps only contains 3 lines

```<code>terraform init
terraform plan
terraform apply -auto-approve
</code>```

答:
My agent.yml file looks like this when i want to add two annotations for 2 separate accounts

spec:
  replicas: 1
  selector:
    matchLabels:
      app: agent-pod
  template:
    metadata:
      annotations:
        iam.amazonaws.com/role: arn:aws:iam::account:role/accoun1-s3-role
        iam.amazonaws.com/role: arn:aws:iam::account:role/account2-pods-s3-role

but as soon as i put two annotation, my sts assume role for pod only shows me second role. and when i run the build from teamcity i get this error
no valid credential sources found for aws provider

Body:
I spun up TeamCity into a Kubernetes cluster. I have one deployment for the TeamCity server and one deployment for the TeamCity build agent. When I run Terraform on the TeamCity build agent, it creates resources in the same AWS account as the EC2 instance which is hosting TeamCity Kubernetes cluster.

I would like to run a build, which creates AWS resources in a separate AWS account. My thinking is to assign an AWS access key and secret key to the TeamCity server and pass them to the TeamCity build agent, but I don't know how the work flow is going to be.

Currently, I have declared AWS access key and secret keys as environment variables on the build but they are not getting passed to agent. My build steps only contains 3 lines

terraform init
terraform plan
terraform apply -auto-approve


问:
ListView disable Insert and Edit buttons based on role
I've a requirement to disable edit/create buttons in ListView.Could anyone please show me how to enable or disable  Edit/Create buttons in ListView from code behind, please.

Not sure if this is possible.

```<code><InsertItemTemplate>
    <tr>
        <td>
            <asp:Button ID="InsertButton" runat="server" CommandName="Insert"
                Text="Insert" CssClass="button"
                ValidationGroup="InsertValidation" CausesValidation="true" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
                Text="Clear" CssClass="button" />
        </td>
    </tr>
</InsertItemTemplate>
</code>```

答:
Use RolePrincipal.IsInRole.

The code should be similiar to the following:

```<code>void listView_ItemDataBound(...)
{
    Button targetButton = (Button) e.Item.FindControl("TargetButtonName");

    targetButton.Enabled = User.IsInRole("Administrators");
}
</code>```

Refer to how to enable and disable button based on user role?

Body:
I've a requirement to disable edit/create buttons in ListView.Could anyone please show me how to enable or disable  Edit/Create buttons in ListView from code behind, please.

Not sure if this is possible.

<InsertItemTemplate>

            <asp:Button ID="InsertButton" runat="server" CommandName="Insert"
                Text="Insert" CssClass="button"
                ValidationGroup="InsertValidation" CausesValidation="true" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
                Text="Clear" CssClass="button" />

</InsertItemTemplate>

Body:
Use RolePrincipal.IsInRole.

The code should be similiar to the following:

void listView_ItemDataBound(...)
{
    Button targetButton = (Button) e.Item.FindControl("TargetButtonName");

    targetButton.Enabled = User.IsInRole("Administrators");
}

Refer to how to enable and disable button based on user role?


问:
Laravel - How to consume and refresh external api into db using Guzzle
I am having this model in my Laravel-5.8 project:

Employee

```<code>class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }

}
</code>```

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

```<code>https://api.employees.net/allemployees
</code>```

I have viewed it with postman get request and I have something like this:

```<code> {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },
</code>```

and so on... this continues

Already I have created this function:

```<code> use App\Employee;
 use App\Department;

 public function index()
 {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }
</code>```

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change from the source.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

答:
I could do something like this:

use App\Employee;
use App\Department;

public function index()
{
      $client = new GuzzleHttp\Client();
      $res = $client->request('GET','https://api.employees.net/allemployees');
      $clientdatas = json_decode($res->getBody()->getContents(), true);

      foreach($clientdatas as $clientdata)
      {
            $employee = Employee::firstOrNew(['id' => $clientdata['ID']]);
            $employee->staff_code = $clientdata['StaffCode'];
            $employee->first_name = $clientdata['FirstName'];
            $employee->last_name = $clientdata['LastName'];
            $employee->save();
      }
}
```

Every time you will make an API call, create an instance of the employee model, or get the associated model if the ID exists. Then assign the new values and save your model. This way, you will be able to either create or update the models in a single loop without any complexities.

Body:
I am having this model in my Laravel-5.8 project:

Employee

class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }

}

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

https://api.employees.net/allemployees

I have viewed it with postman get request and I have something like this:

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },

and so on... this continues

Already I have created this function:

 use App\Employee;
 use App\Department;

 public function index()
 {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change from the source.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

Body:
I could do something like this:

use App\Employee;
use App\Department;

public function index()
{
      $client = new GuzzleHttp\Client();
      $res = $client->request('GET','https://api.employees.net/allemployees');
      $clientdatas = json_decode($res->getBody()->getContents(), true);

      foreach($clientdatas as $clientdata)
      {
            $employee = Employee::firstOrNew(['id' => $clientdata['ID']]);
            $employee->staff_code = $clientdata['StaffCode'];
            $employee->first_name = $clientdata['FirstName'];
            $employee->last_name = $clientdata['LastName'];
            $employee->save();
      }
}

Every time you will make an API call, create an instance of the employee model, or get the associated model if the ID exists. Then assign the new values and save your model. This way, you will be able to either create or update the models in a single loop without any complexities.


问:
Priority Queue using heap, values with same key don't follow FIFO (first in first out)
So I'm trying to create this priority queue to handle my "Order" objects, I'm running into a problem where an object containing the same key/priority will be placed at an early earlier position than others initialized first. I have provided the expected and received output alongside the 83 lines of code of how I constructed my heap with notes</p>

```<code>#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    bool operator <(Order const& RHS) { return priority < RHS.priority; }
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});

    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}
</code>```

```<code>
/*
        Expected Output

    Value           key(priority)
    1                   3
    3                   3
    8                   3
    23                  3
    2                   2
    6                   2
    7                   2
    5                   1
    9                   1

    Recieved/wrong Output

    value            key(priority)
    1                   3
    23                  3
    3                   3
    8                   3
    2                   2
    6                   2
    7                   2
    5                   1

*/
</code>```

答:
In general, heap does not have FIFO property until you implement something that helps doing so. In your order class, you are only comparing using the priority value. In your Order class, you are comparing two Orders by only their priority value. You need a additional variable that serves as the purpose for recording the timing when that value was inserted, and compare according to that.

If you are using the variable value for that purpose, you need to specify in your overloaded < method, what do you want to do when two Order's priority values are equal. Currently, you are only using the priority variable to compare. You are not specifying what do you want to do when the priority of two Orders are equal. You have to specify what do you want to do when the priority value of two variables are equal. Maybe compare a timing variable.

Body:
So I'm trying to create this priority queue to handle my "Order" objects, I'm running into a problem where an object containing the same key/priority will be placed at an early earlier position than others initialized first. I have provided the expected and received output alongside the 83 lines of code of how I constructed my heap with notes

#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    bool operator <(Order const& RHS) { return priority < RHS.priority; }
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});

    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}

/*
        Expected Output

    Value           key(priority)
    1                   3
    3                   3
    8                   3
    23                  3
    2                   2
    6                   2
    7                   2
    5                   1
    9                   1

    Recieved/wrong Output

    value            key(priority)
    1                   3
    23                  3
    3                   3
    8                   3
    2                   2
    6                   2
    7                   2
    5                   1

*/


问:
How to plot a chart in the terminal
I'm researching ML/Theano, and recently came across this script:  https://gist.github.com/notmatthancock/68d52af2e8cde7fbff1c9225b2790a7f which was cool to play with. And like all ML researchers, I recently upgraded to a server, and while it's more powerful, it also presented me with a problem.

The script is very long, but it ends with this code:

```<code>def plot_stuff(inputs, outputs, losses, net_func, n_hidden):
fig,axes = plt.subplots(1,2,figsize=(12,6))

    axes[0].plot(np.arange(losses.shape[0])+1, losses)
    axes[0].set_xlabel('iteration')
    axes[0].set_ylabel('loss')
    axes[0].set_xscale('log')
    axes[0].set_yscale('log')

    x,y = np.mgrid[inputs[:,0].min():inputs[:,0].max():51j, inputs[:,1].min():inputs[:,1].max():51j]
    z = net_func( np.c_[x.flatten(), y.flatten()] ).reshape(x.shape)

    axes[1].contourf(x,y,z, cmap=plt.cm.RdBu, alpha=0.6)
    axes[1].plot(inputs[outputs==0,0], inputs[outputs==0,1], 'or')
    axes[1].plot(inputs[outputs==1,0], inputs[outputs==1,1], 'sb')
    axes[1].set_title('Percent missclassified: %0.2f%%' % (((net_func(inputs)>0.5) != outputs.astype(np.bool)).mean()*100))

    fig.suptitle('Shallow net with %d hidden units'%n_hidden)
    plt.show()

if __name__=='__main__':
    n_hidden = 40
    inputs, outputs = gen_data(n_samples_per_class=100)
    losses, net_func = train_neural_network(inputs=inputs, outputs=outputs, n_hidden=n_hidden, n_iters=int(2000), learning_rate=0.1)
    plot_stuff(inputs, outputs, losses, net_func, n_hidden)
</code>```

Which generates this chart:

And when I tried to run it on the server, which being a sever has no screen only a command line, I predictably got this error:

```<code>fedora@ip-173-33-18-911:~/scripting/spiral$ python spiral.py
Iteration 2000 / 2000, Loss: 0.172083
Traceback (most recent call last):
  File "spiral.py", line 133, in <module>
    plot_stuff(inputs, outputs, losses, net_func, n_hidden)
  File "spiral.py", line 110, in plot_stuff
    fig,axes = plt.subplots(1,2,figsize=(12,6))
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1046, in subplots
    fig = figure(**fig_kw)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 423, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
</code>```

Is there a way/method/function to display charts and graphs in the command line?

答:
It is possible to plot raster images in terminals and terminal emulators:

import matplotlib
matplotlib.use('module://matplotlib-sixel')
from pylab import *
plt.plot(sin(arange(100) / 10))
show()
```

This particular example uses matplotlib-sixel, a library that uses Xterm emulating a Sixel compatible terminal and ImageTrick. Similar technology could be implemented in the Linux terminal (through the Framebuffer) or emulators (kitty or iTerm2). The FOSS community has given great solutions in the last years (like libsixel).

Another option would be using X11 forwarding or using a Sixel-based printer like lsix. But all these options would happens outside the Python shell itself.

Of course, you are probably better off running a Jupyter Notebook in the server than trying to shoehorn an image in a terminal. It is probably not worth it.

Title: How to plot a chart in the terminal

Body:
I'm researching ML/Theano, and recently came across this script:  https://gist.github.com/notmatthancock/68d52af2e8cde7fbff1c9225b2790a7f which was cool to play with. And like all ML researchers, I recently upgraded to a server, and while it's more powerful, it also presented me with a problem.

The script is very long, but it ends with this code:

def plot_stuff(inputs, outputs, losses, net_func, n_hidden):
fig,axes = plt.subplots(1,2,figsize=(12,6))

    axes[0].plot(np.arange(losses.shape[0])+1, losses)
    axes[0].set_xlabel('iteration')
    axes[0].set_ylabel('loss')
    axes[0].set_xscale('log')
    axes[0].set_yscale('log')

    x,y = np.mgrid[inputs[:,0].min():inputs[:,0].max():51j, inputs[:,1].min():inputs[:,1].max():51j]
    z = net_func( np.c_[x.flatten(), y.flatten()] ).reshape(x.shape)

    axes[1].contourf(x,y,z, cmap=plt.cm.RdBu, alpha=0.6)
    axes[1].plot(inputs[outputs==0,0], inputs[outputs==0,1], 'or')
    axes[1].plot(inputs[outputs==1,0], inputs[outputs==1,1], 'sb')
    axes[1].set_title('Percent missclassified: %0.2f%%' % (((net_func(inputs)>0.5) != outputs.astype(np.bool)).mean()*100))

    fig.suptitle('Shallow net with %d hidden units'%n_hidden)
    plt.show()

if __name__=='__main__':
    n_hidden = 40
    inputs, outputs = gen_data(n_samples_per_class=100)
    losses, net_func = train_neural_network(inputs=inputs, outputs=outputs, n_hidden=n_hidden, n_iters=int(2000), learning_rate=0.1)
    plot_stuff(inputs, outputs, losses, net_func, n_hidden)

Which generates this chart:

And when I tried to run it on the server, which being a sever has no screen only a command line, I predictably got this error:

fedora@ip-173-33-18-911:~/scripting/spiral$ python spiral.py
Iteration 2000 / 2000, Loss: 0.172083
Traceback (most recent call last):
  File "spiral.py", line 133, in <module>
    plot_stuff(inputs, outputs, losses, net_func, n_hidden)
  File "spiral.py", line 110, in plot_stuff
    fig,axes = plt.subplots(1,2,figsize=(12,6))
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1046, in subplots
    fig = figure(**fig_kw)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 423, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

Is there a way/method/function to display charts and graphs in the command line?

Body:
It is possible to plot raster images in terminals and terminal emulators:

import matplotlib
matplotlib.use('module://matplotlib-sixel')
from pylab import *
plt.plot(sin(arange(100) / 10))
show()

This particular example uses matplotlib-sixel, a library that uses Xterm emulating a Sixel compatible terminal and ImageTrick. Similar technology could be implemented in the Linux terminal (through the Framebuffer) or emulators (kitty or iTerm2). The FOSS community has given great solutions in the last years (like libsixel).

Another option would be using X11 forwarding or using a Sixel-based printer like lsix. But all these options would happens outside the Python shell itself.

Of course, you are probably better off running a Jupyter Notebook in the server than trying to shoehorn an image in a terminal. It is probably not worth it.


问:
Why cast after an instanceOf?
In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but only if those 2 are of compatible types.

```<code>if (p1 instanceof Square) {c1 = (Square) p1;}
</code>```

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it.  If it's a Square, why cast?

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...

Edit:

How would the compiler deal with:

```<code>if (p1 instanceof Square) {c1 = p1;}
</code>```

Edit2:

Is the issue that instanceof checks for the actual type rather than the apparent type?  And then that the cast changes the apparent type?

答:
Just to provide an update on this, Java 14 now provides pattern matching for instanceof, this allows you to check and cast in one fell swoop.

This (old way):

```<code>void outputValue(Object obj) {
    if (obj instanceof String) {                      // Compare
        String aString = (String) obj;                // New variable & explicit casting
        System.out.println(aString.toUpperCase());    // Access member
    }
}
</code>```

Can be simplified to this:

```<code>void outputValue(Object obj) {
    if (obj instanceof String aString) {              // Compare and cast (if true)
        System.out.println(aString.toUpperCase());    // Access member
    }
}
</code>```

Title: Why cast after an instanceOf?

Body:
In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but only if those 2 are of compatible types.

if (p1 instanceof Square) {c1 = (Square) p1;}

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it.  If it's a Square, why cast?

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...

Edit:

How would the compiler deal with:

if (p1 instanceof Square) {c1 = p1;}

Edit2:

Is the issue that instanceof checks for the actual type rather than the apparent type?  And then that the cast changes the apparent type?

Body:
Just to provide an update on this, Java 14 now provides pattern matching for instanceof, this allows you to check and cast in one fell swoop.

This (old way):

void outputValue(Object obj) {
    if (obj instanceof String) {                      // Compare
        String aString = (String) obj;                // New variable & explicit casting
        System.out.println(aString.toUpperCase());    // Access member
    }
}

Can be simplified to this:

void outputValue(Object obj) {
    if (obj instanceof String aString) {              // Compare and cast (if true)
        System.out.println(aString.toUpperCase());    // Access member
    }
}


问:
How to integrate rest api with front end website/app?
I already built out my restful api for logging in and registering, my question is how do I now use this api in my website? Isn't the point of an api to return json to consume? If i were to put a res.redirect() then wouldn't that make the api useless for later on when i want to use the api for say an iOS app? </p>

```<code>router.post('/login', async (request, response) => {

        // validate
        const {error} = loginValidation(request.body)
        if (error) return response.status(400).send(error.details[0].message)

        const {email, password} = request.body

        // check if email doesn't exist
        const user = await pool.query('SELECT id, email, password FROM users WHERE email = $1 LIMIT 1', [email])
        if(user.rowCount == 0) return response.status(400).send('Wrong email or password')

        // password is correct; move on to validating password
        const id = user.rows[0].id
        const storedEmail = user.rows[0].email
        const storedPassword = user.rows[0].password
        const validPass = await bcrypt.compare(request.body.password, storedPassword)
        if(!validPass) return response.status(400).send('Wrong email or password')

        // create and send token to client
        const token = jwt.sign({_id: id}, "SOMESECRET")
        response.header('auth-token', token).send(token)

    })
</code>```

答:
You could try these ways:

Make API calls from web clients(i.e. web browsers) with Javascript.

Set up a web server and make API calls from the server.

Body:
I already built out my restful api for logging in and registering, my question is how do I now use this api in my website? Isn't the point of an api to return json to consume? If i were to put a res.redirect() then wouldn't that make the api useless for later on when i want to use the api for say an iOS app?

router.post('/login', async (request, response) => {

        // validate
        const {error} = loginValidation(request.body)
        if (error) return response.status(400).send(error.details[0].message)

        const {email, password} = request.body

        // check if email doesn't exist
        const user = await pool.query('SELECT id, email, password FROM users WHERE email = $1 LIMIT 1', [email])
        if(user.rowCount == 0) return response.status(400).send('Wrong email or password')

        // password is correct; move on to validating password
        const id = user.rows[0].id
        const storedEmail = user.rows[0].email
        const storedPassword = user.rows[0].password
        const validPass = await bcrypt.compare(request.body.password, storedPassword)
        if(!validPass) return response.status(400).send('Wrong email or password')

        // create and send token to client
        const token = jwt.sign({_id: id}, "SOMESECRET")
        response.header('auth-token', token).send(token)

    })


问:
Finding those IDs that have retaken 3 distinct courses
(I'm new, and apologizes in advance if this is too simple)
So, I'm trying to find those Students who have retaken at least three distinct courses at least once.
I figured that I will have to operate on Takes, and student.

```<code>Takes(ID,course_id,sec_id,semester,year,grade)
student(ID,name,dept_name,tot_cred)
</code>```

Both IDs serve as primary keys

Here are the two solutions I have worked upon;

1

```<code>select student.*
from student, takes
where student.ID = takes.ID
group by takes.course_id
having count(distinct takes.course_id) <=3 ;
</code>```

2

```<code>select student.*
from student
where 2<= (select takes.ID from takes
        where takes.ID = student.ID
        group by course_id
        having count(distinct takes.course_id) <=3
        limit 1);
</code>```

I had to add that limiter because an error kept coming up

答:
Never use commas in the FROM clause.  Always use proper, explicit, standard, readable JOIN syntax.

Clarification: retaken in this context means; The student should have taken the course at least two times)

If you want students who have taken a single course at least three times, then use GROUP BY and HAVING:

```<code>select t.student_id, t.course_id
from takes t
group by t.student_id, t.course_id
having count(*) >= 3;
</code>```

You can use JOIN or IN or EXISTS to bring in more columns from students if you like.

Body:
(I'm new, and apologizes in advance if this is too simple)
So, I'm trying to find those Students who have retaken at least three distinct courses at least once.
I figured that I will have to operate on Takes, and student.

Takes(ID,course_id,sec_id,semester,year,grade)
student(ID,name,dept_name,tot_cred)

Both IDs serve as primary keys

Here are the two solutions I have worked upon;

1

select student.*
from student, takes
where student.ID = takes.ID
group by takes.course_id
having count(distinct takes.course_id) <=3 ;

2

select student.*
from student
where 2<= (select takes.ID from takes
        where takes.ID = student.ID
        group by course_id
        having count(distinct takes.course_id) <=3
        limit 1);

I had to add that limiter because an error kept coming up

Body:
Never use commas in the FROM clause.  Always use proper, explicit, standard, readable JOIN syntax.

Clarification: retaken in this context means; The student should have taken the course at least two times)

If you want students who have taken a single course at least three times, then use GROUP BY and HAVING:

select t.student_id, t.course_id
from takes t
group by t.student_id, t.course_id
having count(*) >= 3;

You can use JOIN or IN or EXISTS to bring in more columns from students if you like.


问:
Can I append a img to a img
So I tried out if I can append using jquery a image to an image and it works, but the image seems to be gone or visibility is hidden and display none or so it seems.

So my question is can this be done and can I use this image. Its for a project I am working on.

```<code><img src="img/map.png" style="width: 600px; height: 400px; z-index: -100;">

    <img src="img/dot.png" style="position: relative; width: 20px;
         height:34px; top: 200px; left: 200px; z-index: 100;
        display: block; visibility: visible;">

</img>
</code>```

thats what my code looks like after I use the append. and if you look at it in firebug you see that the child img looks like it is not displayed so I tried changing the visibility but still not luck.

so my question is can this be done or am I after the unattainable.

答:
That is not valid HTML. You can append an  as a sibling to another, but you shouldn't do it within an existing image.

To append after:

```<code>$(imageSelector).after('<img ... />'); // method 1
$('<img ... />').insertAfter(imageSelector); // method 2
</code>```

or before:

```<code>$(imageSelector).before('<img ... />'); // method 1
$('<img ... />').insertBefore(imageSelector); // method 2
</code>```

Title: Can I append a img to a img

Body:
So I tried out if I can append using jquery a image to an image and it works, but the image seems to be gone or visibility is hidden and display none or so it seems.

So my question is can this be done and can I use this image. Its for a project I am working on.

thats what my code looks like after I use the append. and if you look at it in firebug you see that the child img looks like it is not displayed so I tried changing the visibility but still not luck.

so my question is can this be done or am I after the unattainable.

Body:
That is not valid HTML. You can append an <img> as a sibling to another, but you shouldn't do it within an existing image.

To append after:

$(imageSelector).after('<img ... />'); // method 1
$('<img ... />').insertAfter(imageSelector); // method 2

or before:

$(imageSelector).before('<img ... />'); // method 1
$('<img ... />').insertBefore(imageSelector); // method 2


问:
Using ReportLab To Create A PDF Then Save It To A User Model
For a few days Ive been trying to get this working and, while I think im getting close, I still havent got it working yet.

I have a function which uses ReportLab to generate a SimpleDocTemplate pdf and I want to return it to the calling view so I can save it to the uesrs Profile model.

This is my code so far:

model.py

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_pdf = models.FileField(upload_to='pdfs/user_pdfs')
</code>```

the error message:

```<code>'HttpResponse' object has no attribute 'read'
</code>```

view

```<code>def final_question(request):
    if request.method == 'POST':
        # this is the final form they complete
        form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion)

        if form.is_valid():
            form.save()

            # generate pdf containing all answers to enrolment questions
            users_pdf = utils.generate_user_pdf(request)

            # here i get the users model
            # hard coded user_id for testing
            users_profile = Profile.objects.get(user_id=1)
            # then i get the field I want to save to
            pdf = users_profile.profile_pdf
            # then i save the generated pdf to the field
            pdf.save('user_1_pdf', users_pdf)
</code>```

my pdf generation function

```<code>def generate_user_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "test.pdf"'

    doc = SimpleDocTemplate(response)

    elements = []

    data= [
                 ['---TEST DATA---'],
                 ['test data'],
          ]

    [.. cont ..]

    doc.build(elements)

    return response
</code>```

Thank you.

--EDIT--

error:

```<code>argument should be a bytes-like object or ASCII string, not 'FileResponse'
</code>```

utils:

```<code>def generate_pdf(request):
    buffer = io.BytesIO()

    doc = SimpleDocTemplate('test')
    story = []

    doc.build(story)

    response = FileResponse(buffer.getvalue())

    return response
</code>```

views.py

```<code># generate pdf containing all answers
            user_pdf = utils.generate_pdf(request)

            # get users enrolment_pdf field
            # temp hard-coded
            user_profile = Profile.objects.get(user_id=1)
            field = user_profile.user_pdf

            # save the generated pdf to the user in the database
            file_data = ContentFile(base64.b64decode(user_pdf))
            field.save('test', file_data)
</code>```

Thank you

答:
Firstly, there is an answer.
In addition to this answers, you need to read this, just work with buffer.getvalue() bytes array and use ContentFile class to save this to model field.

To simplify your work with Response object, use FileResponse.

--EDIT--

You need to write your pdf to buffer:

doc = SimpleDocTemplate(buffer)
doc.build(story)
buffer.seek(0)
pdf: bytes = buffer.getvalue()
return FileResponse(pdf, filename='doc.pdf')
```

<p>And, I've found these instructions in docs.</p>

<p>To save pdf into <code>Profile</code>:</p>

<pre class="lang-py prettyprint-override"><code>file_data = ContentFile(pdf)
profile = Profile.objects.get(...)
profile.pdf_field.save('filename.pdf', file_data, save=False)
profile.save()
</code>```

Body:
For a few days Ive been trying to get this working and, while I think im getting close, I still havent got it working yet.

I have a function which uses ReportLab to generate a SimpleDocTemplate pdf and I want to return it to the calling view so I can save it to the uesrs Profile model.

This is my code so far:

model.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_pdf = models.FileField(upload_to='pdfs/user_pdfs')

the error message:

'HttpResponse' object has no attribute 'read'

view

def final_question(request):
    if request.method == 'POST':
        # this is the final form they complete
        form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion)

        if form.is_valid():
            form.save()

            # generate pdf containing all answers to enrolment questions
            users_pdf = utils.generate_user_pdf(request)

            # here i get the users model
            # hard coded user_id for testing
            users_profile = Profile.objects.get(user_id=1)
            # then i get the field I want to save to
            pdf = users_profile.profile_pdf
            # then i save the generated pdf to the field
            pdf.save('user_1_pdf', users_pdf)

my pdf generation function

def generate_user_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "test.pdf"'

    doc = SimpleDocTemplate(response)

    elements = []

    data= [
                 ['---TEST DATA---'],
                 ['test data'],
          ]

    [.. cont ..]

    doc.build(elements)

    return response

Thank you.

--EDIT--

error:

argument should be a bytes-like object or ASCII string, not 'FileResponse'

utils:

def generate_pdf(request):
    buffer = io.BytesIO()

    doc = SimpleDocTemplate('test')
    story = []

    doc.build(story)

    response = FileResponse(buffer.getvalue())

    return response

views.py

# generate pdf containing all answers
            user_pdf = utils.generate_pdf(request)

            # get users enrolment_pdf field
            # temp hard-coded
            user_profile = Profile.objects.get(user_id=1)
            field = user_profile.user_pdf

            # save the generated pdf to the user in the database
            file_data = ContentFile(base64.b64decode(user_pdf))
            field.save('test', file_data)

Thank you

Body:
Firstly, there is an answer.
In addition to this answers, you need to read this, just work with buffer.getvalue() bytes array and use ContentFile class to save this to model field.

To simplify your work with Response object, use FileResponse.

--EDIT--

You need to write your pdf to buffer:

doc = SimpleDocTemplate(buffer)
doc.build(story)
buffer.seek(0)
pdf: bytes = buffer.getvalue()
return FileResponse(pdf, filename='doc.pdf')

And, I've found these instructions in docs.

To save pdf into Profile:

file_data = ContentFile(pdf)
profile = Profile.objects.get(...)
profile.pdf_field.save('filename.pdf', file_data, save=False)
profile.save()


问:
How to configure Sublimes preferred "Open Containing Folder" tool
When right-clicking a file in an opened folder in Sublime3 I get the option to "Open Containing Folder".

But my Manjaro keeps trying to open the path with the archive manager.

How do I configure which tool will be used?

Why does Sublime try to use the Manjaro archive manager?

答:
Found it on the web.

https://forum.sublimetext.com/t/open-containing-folder-solved/8639

Citing a user there with the accepted answer:

"I had this problem and I believe it was a file association for directories. I changed it to dolphin. [..]"


问:
How to delete the line which matches the string shared in array
I have a file which consist of text like below

```<code>compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX
</code>```

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

```<code>#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done
</code>```

答:
Same as @tshiono suggested but using printf to construct pattern

```<code>printf -v pat '\%s\|' ${array[@]}
sed "/${pat%*'\|'}/d" copyright
</code>```

Body:
I have a file which consist of text like below

compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done

Body:
Same as @tshiono suggested but using printf to construct pattern

printf -v pat '\%s\|' ${array[@]}
sed "/${pat%*'\|'}/d" copyright


问:
ASP.NET MVC - Extending TextBoxFor without re-writing the method
Is there any possible way to extend the basic html helpers (TextBoxFor, TextAreaFor, etc) using extension methods on their output, instead of just re-writing the entire methods completely? For instance, adding in ...

@Html.TextBoxFor( model => model.Name ).Identity("idName")

I know I can achieve this using the following, already..

@Html.TextBoxFor( model => model.Name, new { @id = "idName" })

But that gets clunky and frustrating to manage when you have to start adding a lot of properties. Is there any way to add extensions to these inherently without just passing in htmlAttributes for every little detail?

答:
As @AaronShockley says, because TextBoxFor() returns an MvcHtmlString, your only option for developing a 'fluid API' style of amending the output would be to operate on the MvcHtmlStrings returned by the helper methods. A slightly different way of doing this which I think approaches what you're after would be to use a 'property builder' object, like this:

```<code>public class MvcInputBuilder
{
    public int Id { get; set; }

    public string Class { get; set; }
}
</code>```

...and to set up extension methods like this:

```<code>public static MvcHtmlString TextBoxFor<TModel, TProp>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProp>> expression,
    params Action<MvcInputBuilder>[] propertySetters)
{
    MvcInputBuilder builder = new MvcInputBuilder();

    foreach (var propertySetter in propertySetters)
    {
        propertySetter.Invoke(builder);
    }

    var properties = new RouteValueDictionary(builder)
        .Select(kvp => kvp)
        .Where(kvp => kvp.Value != null)
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

    return htmlHelper.TextBoxFor(expression, properties);
}
</code>```

You can then do stuff like this in your View:

```<code>@this.Html.TextBoxFor(
    model => model.Name,
    p => p.Id = 7,
    p => p.Class = "my-class")
</code>```

This gives you strong typing and intellisense for input properties, which you could customise for each extension method by adding properties to an appropriate MvcInputBuilder subclass.

Body:
As @AaronShockley says, because TextBoxFor() returns an MvcHtmlString, your only option for developing a 'fluid API' style of amending the output would be to operate on the MvcHtmlStrings returned by the helper methods. A slightly different way of doing this which I think approaches what you're after would be to use a 'property builder' object, like this:

public class MvcInputBuilder
{
    public int Id { get; set; }

    public string Class { get; set; }
}

...and to set up extension methods like this:

public static MvcHtmlString TextBoxFor<TModel, TProp>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProp>> expression,
    params Action<MvcInputBuilder>[] propertySetters)
{
    MvcInputBuilder builder = new MvcInputBuilder();

    foreach (var propertySetter in propertySetters)
    {
        propertySetter.Invoke(builder);
    }

    var properties = new RouteValueDictionary(builder)
        .Select(kvp => kvp)
        .Where(kvp => kvp.Value != null)
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

    return htmlHelper.TextBoxFor(expression, properties);
}

You can then do stuff like this in your View:

@this.Html.TextBoxFor(
    model => model.Name,
    p => p.Id = 7,
    p => p.Class = "my-class")

This gives you strong typing and intellisense for input properties, which you could customise for each extension method by adding properties to an appropriate MvcInputBuilder subclass.


问:
Vim stop comment continuation during abbrev expansion
If your Vim settings include 'r' in 'formatoptions' (default) it will automatically insert the current comment leader after hitting [Enter] in insert mode, but this can be undesirable for abbrevs that expand to a single-line comment in languages that don't have separate single/multi-line comment characters.

How do I stop getting this when I press [Enter] after typing the abbrev characters?

```<code># ========
#
</code>```

答:
This is what I did:

```<code>" Eat one character matching the given regex from the input stream, e.g. at
" the end of an abbr expansion.  (From :help abbreviations)
func Eatchar(pat)
    let c = nr2char(getchar(0))
    return (c =~ a:pat) ? '' : c
endfunc

set pastetoggle=<F12>
iabbr <silent> sep # ========<F12><CR><F12><C-R>=Eatchar('\r')<CR>
</code>```

This replaces the user's [Enter] key press with a generated one surrounded by generated key presses that turn paste mode off before and back on afterwards.  The final <C-R> completes the <C-R>= sequence.

Body:
If your Vim settings include 'r' in 'formatoptions' (default) it will automatically insert the current comment leader after hitting [Enter] in insert mode, but this can be undesirable for abbrevs that expand to a single-line comment in languages that don't have separate single/multi-line comment characters.

How do I stop getting this when I press [Enter] after typing the abbrev characters?

# ========
#

Body:
This is what I did:

" Eat one character matching the given regex from the input stream, e.g. at
" the end of an abbr expansion.  (From :help abbreviations)
func Eatchar(pat)
    let c = nr2char(getchar(0))
    return (c =~ a:pat) ? '' : c
endfunc

set pastetoggle=<F12>
iabbr <silent> sep # ========<F12><CR><F12><C-R>=Eatchar('\r')<CR>

This replaces the user's [Enter] key press with a generated one surrounded by generated key presses that turn paste mode off before and back on afterwards.  The final <C-R> completes the <C-R>= sequence.


问:
sklearn_extra installation issue
[in]:

from sklearn_extra.cluster import KMedoids
```
<p>[out]:</p>
```ModuleNotFoundError: No module named 'sklearn_extra'
```
<p>Then, I tried installing sklearn_extra via</p>
<p>[in]:</p>
<pre class="lang-py prettyprint-override"><code>python -m pip install sklearn_extra
</code>```

[out]:

ERROR: Could not find a version that satisfies the requirement sklearn_extra (from versions: none)
ERROR: No matching distribution found for sklearn_extra
```
<p>Then, I went to installation part of the website(https://scikit-learn-extra.readthedocs.io/en/latest/install.html) and did what it said:</p>
```Installation
Dependencies
scikit-learn-extra requires,

Python (>=3.5)

scikit-learn (>=0.21), and its dependencies

Cython (>0.28)

User installation
Latest development version can be installed with,

pip install https://github.com/scikit-learn-contrib/scikit-learn-extra/archive/master.zip
```
<p>[in]:</p>
<pre class="lang-py prettyprint-override"><code>pip install https://github.com/scikit-learn-contrib/scikit-learn-extra/archive/master.zip
</code>```

[out]:

```<code>  ERROR: Command errored out with exit status 1:
   command: 'c:\users\m\appdata\local\programs\python\python37\python.exe' 'c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\m\AppData\Local\Temp\pip-build-env-yopprv13\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.28' numpy==1.14.5
       cwd: None
  Complete output (14 lines):
  Traceback (most recent call last):
    File "c:\users\m\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)
    File "c:\users\m\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code
      exec(code, run_globals)
    File "c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip\__main__.py", line 16, in <module>
      from pip._internal.main import main as _main  # isort:skip # noqa
    File "c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\main.py", line 8, in <module>
      import locale
    File "c:\users\m\appdata\local\programs\python\python37\lib\locale.py", line 16, in <module>
      import re
    File "c:\users\m\appdata\local\programs\python\python37\lib\re.py", line 143, in <module>
      class RegexFlag(enum.IntFlag):
  AttributeError: module 'enum' has no attribute 'IntFlag'
</code>```

I checked versions of Cython,Python and sklearn they satisfy the required range.

Edit: the solution is to uninstall enum34 for me thanks to Balraj Ashwatt's comment.

pip uninstall -y enum34
```

Then I was able to install sklearn_extra

答:
Uninstalling enum34 worked for me and then I was able to install sklearn_extra

pip uninstall -y enum34
```

Title: sklearn_extra installation issue

Body:
[in]:

from sklearn_extra.cluster import KMedoids

[out]:

ModuleNotFoundError: No module named 'sklearn_extra'

Then, I tried installing sklearn_extra via

[in]:

python -m pip install sklearn_extra

[out]:

ERROR: Could not find a version that satisfies the requirement sklearn_extra (from versions: none)
ERROR: No matching distribution found for sklearn_extra

Then, I went to installation part of the website(https://scikit-learn-extra.readthedocs.io/en/latest/install.html) and did what it said:

Installation
Dependencies
scikit-learn-extra requires,

Python (>=3.5)

scikit-learn (>=0.21), and its dependencies

Cython (>0.28)

User installation
Latest development version can be installed with,

pip install https://github.com/scikit-learn-contrib/scikit-learn-extra/archive/master.zip

[in]:

pip install https://github.com/scikit-learn-contrib/scikit-learn-extra/archive/master.zip

[out]:

  ERROR: Command errored out with exit status 1:
   command: 'c:\users\m\appdata\local\programs\python\python37\python.exe' 'c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\m\AppData\Local\Temp\pip-build-env-yopprv13\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.28' numpy==1.14.5
       cwd: None
  Complete output (14 lines):
  Traceback (most recent call last):
    File "c:\users\m\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)
    File "c:\users\m\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code
      exec(code, run_globals)
    File "c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip\__main__.py", line 16, in <module>
      from pip._internal.main import main as _main  # isort:skip # noqa
    File "c:\users\m\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\main.py", line 8, in <module>
      import locale
    File "c:\users\m\appdata\local\programs\python\python37\lib\locale.py", line 16, in <module>
      import re
    File "c:\users\m\appdata\local\programs\python\python37\lib\re.py", line 143, in <module>
      class RegexFlag(enum.IntFlag):
  AttributeError: module 'enum' has no attribute 'IntFlag'

I checked versions of Cython,Python and sklearn they satisfy the required range.

Edit: the solution is to uninstall enum34 for me thanks to Balraj Ashwatt's comment.

pip uninstall -y enum34

Then I was able to install sklearn_extra


问:
WPF Overlay does not activate until after button has finished
I have a small sample WPF application using Caliburn Micro. In it, I have a rectangle overlay that says loading. I want this to appear whenever a large task is loading however it doesn't appear until after the method is finished. I have tried using Dispatch as well as other suggestions howver nothing works until after the button method is finished. Below is my current example

```<code>  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

</code>```

The overlay shows up only after LongMethod() is finished running. Is there a way to get it to show before the method runs?

答:
You haven't posted the implementation of LongMethod so it's impossible to say what it actually does, but I would guess that it isn't implemented as an asynchronous and blocks the UI thread.

You may try to execute it on a background thread using a Task:

```<code>public async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
    await Task.Run(LongMethod);
}
</code>```

A method isn't automatically asynchronous just because it returns a Task or a Task<T> and can be awaited.

Body:
I have a small sample WPF application using Caliburn Micro. In it, I have a rectangle overlay that says loading. I want this to appear whenever a large task is loading however it doesn't appear until after the method is finished. I have tried using Dispatch as well as other suggestions howver nothing works until after the button method is finished. Below is my current example

  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

The overlay shows up only after LongMethod() is finished running. Is there a way to get it to show before the method runs?

Body:
You haven't posted the implementation of LongMethod so it's impossible to say what it actually does, but I would guess that it isn't implemented as an asynchronous and blocks the UI thread.

You may try to execute it on a background thread using a Task:

public async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
    await Task.Run(LongMethod);
}

A method isn't automatically asynchronous just because it returns a Task or a Task<T> and can be awaited.


答:
According to the specification the  element cannot have content:

The IMG element has no content; it is
  usually replaced inline by the image
  designated by the src attribute, the
  exception being for left or
  right-aligned images that are
  "floated" out of line.

So trying to nest  tags would result into undefined behavior.

Title: Can I append a img to a img

Body:
According to the specification the <img> element cannot have content:

The IMG element has no content; it is
  usually replaced inline by the image
  designated by the src attribute, the
  exception being for left or
  right-aligned images that are
  "floated" out of line.

So trying to nest <img> tags would result into undefined behavior.


问:
Is there any software to autoformat the code written in Makefile?
Various software is used to auto-format the source code, written in different programming languages.

I mean exactly auto-formatting (not coloring) of the source code - add spaces, tabs, newlines, etc.

Is there any alternative way to do the same, but for the Makefiles?

I've tried to do it in "bash" with "grep", "sed", "awk" and I'm almost done.

P.S. As an example, please compare bad formatted Makefile.ugly:

```<code>CONFIG_ZERO=y
CONFIG_ONE=y
CONFIG_TWO=y

ifeq ($(CONFIG_ZERO),y)
list_of_targets += t1 t2 t4
ifeq ($(CONFIG_TWO),y)
list_of_targets += t5 t6 t7
endif
ifeq ($(CONFIG_ONE),y)
list_of_targets += t8 t9
endif
endif

.PHONY: all
all:
                $(info Using following targets: $(list_of_targets))
</code>```

with its well-formatted version (Makefile.formatted):

```<code>CONFIG_ZERO=y
CONFIG_ONE=y
CONFIG_TWO=y

ifeq ($(CONFIG_ZERO),y)
  list_of_targets += t1 t2 t4

  ifeq ($(CONFIG_TWO),y)
    list_of_targets += t5 t6 t7
  endif

  ifeq ($(CONFIG_ONE),y)
    list_of_targets += t8 t9
  endif
endif

.PHONY: all
all:
    $(info Using following targets: $(list_of_targets))
</code>```

答:
The horizontal layout of makefiles is relatively unchangeable: the leading tabulator for the recipe code (the shell code in a rule) is a syntactic element like in Python an can't be changed for the better (you can add more tabs, but the effect will likely be worse than nicer looking). Other code like variable definitions is only prependable by space characters, all spaces and tabs inside the body of such definitions and sometimes even the invisible spaces at the end serve a functional purpose and changing them has the chance to destroy their intended effect.

That leaves you with options for the vertical layout. Taking into consideration the two phases of execution of a makefile, you have two degrees of freedom: 1) variable definitions which don't have mutual dependecies and 2) the order of rules (with the exception of the first one which will serve as default target for a plain make call w/o arguments) are arbitary. This means you can move rules further to the back of the makefile iff the variables they use are not changing their contents in the course of the evaluation of the makefile - which in itself is not trivial to ascertain. A beautifier would have to construct the same internal data structures like make to decide if a source transformation is correct or not - and all that hassle for just a modest reordering of the rules.

TL;DR: make syntax is difficult to transform (under equivalence) and the resulting aesthetic will be hard to defend even among the same programming team, therefore it is seldomly done.

Body:
Various software is used to auto-format the source code, written in different programming languages.

I mean exactly auto-formatting (not coloring) of the source code - add spaces, tabs, newlines, etc.

Is there any alternative way to do the same, but for the Makefiles?

I've tried to do it in "bash" with "grep", "sed", "awk" and I'm almost done.

P.S. As an example, please compare bad formatted Makefile.ugly:

CONFIG_ZERO=y
CONFIG_ONE=y
CONFIG_TWO=y

ifeq ($(CONFIG_ZERO),y)
list_of_targets += t1 t2 t4
ifeq ($(CONFIG_TWO),y)
list_of_targets += t5 t6 t7
endif
ifeq ($(CONFIG_ONE),y)
list_of_targets += t8 t9
endif
endif

.PHONY: all
all:
                $(info Using following targets: $(list_of_targets))

with its well-formatted version (Makefile.formatted):

CONFIG_ZERO=y
CONFIG_ONE=y
CONFIG_TWO=y

ifeq ($(CONFIG_ZERO),y)
  list_of_targets += t1 t2 t4

  ifeq ($(CONFIG_TWO),y)
    list_of_targets += t5 t6 t7
  endif

  ifeq ($(CONFIG_ONE),y)
    list_of_targets += t8 t9
  endif
endif

.PHONY: all
all:
    $(info Using following targets: $(list_of_targets))


问:
Fastest way to convert a string into a Float32Array
How can I convert a string containing floats written out (not stored as JSON or something like that) into a Float32Array? I tried this but it doesn't work:

```<code>var str = "2.3 4.3 3.145";
var arr1 = parseFloat(str);
var arr2 = new Float32Array(arr1);
</code>```

答:
You have to split the values up, and then you can use Float32Array.from with the mapping callback:

```<code>const arr = Float32Array.from(str.split(" "), parseFloat);
</code>```

const str = "2.3 4.3 3.145";
const arr = Float32Array.from(str.split(" "), parseFloat);
console.log(arr);```
</div>
</div>
</p>

<hr>

<p>Note: Unlike <code>parseInt</code>, it's safe to use <code>parseFloat</code> the way it's used above, it ignores all but its first argument so it doesn't care that it gets called with more than one argument by <code>from</code>. If you had to do something like this to create (say) a <code>Uint8Array</code>, you couldn't use <code>parseInt</code> as above because it would be confused by the second argument it would receive. In that case, an arrow function is a simple way to fix it (and lets you be specific about the number base as well):</p>

```const arr = Uint8Array.from(str.split(" "), n => parseInt(n, 10));
```

Body:
How can I convert a string containing floats written out (not stored as JSON or something like that) into a Float32Array? I tried this but it doesn't work:

var str = "2.3 4.3 3.145";
var arr1 = parseFloat(str);
var arr2 = new Float32Array(arr1);

Body:
You have to split the values up, and then you can use Float32Array.from with the mapping callback:

const arr = Float32Array.from(str.split(" "), parseFloat);

const str = "2.3 4.3 3.145";
const arr = Float32Array.from(str.split(" "), parseFloat);
console.log(arr);

Note: Unlike parseInt, it's safe to use parseFloat the way it's used above, it ignores all but its first argument so it doesn't care that it gets called with more than one argument by from. If you had to do something like this to create (say) a Uint8Array, you couldn't use parseInt as above because it would be confused by the second argument it would receive. In that case, an arrow function is a simple way to fix it (and lets you be specific about the number base as well):

const arr = Uint8Array.from(str.split(" "), n => parseInt(n, 10));