问:
How to obtain correct size for a second colorbar in matplotlib plot?
I wish to create a "split plot", i.e. to use different colormaps in the left and the right half of my plot. Accordingly I will need two different colorbars. Unfortunately I have to set the position of the second colorbar by hand and modify everytime a label or title is included. Is there a way to automatise that?

I wondered if I could extract the rect parameter of the following minimal example from the right colorbar. That would help me as I only had shift it a bit. Any other (/better) idea is also welcome.

At the moment, whenever I change the labels or title a bit the manually set position of the left colorbar has to be modified again. This is very annoying. I include a running minimal example and a the output it produces:

```<code>import matplotlib as mpl
params = {
           'xtick.direction' : 'out',
           'ytick.direction' : 'out',
           'text.usetex'     : True,
         }

mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout': True})

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

extent_arr1 = [-1,0, -1,1]
extent_arr2 = [ 0,1, -1,1]
M = 501

# define test-data
data_arr1  = np.zeros((M, M))
data_arr2 = np.ones((M, M))

# define figure
fig = plt.figure()
ax = fig.add_subplot(111)

# left plot:
image1 = ax.imshow( data_arr1,  cmap='jet', interpolation='bilinear', extent=extent_arr1, \
                     origin='lower')
plt.title("Minimal example")
cbar1  = plt.colorbar(image1)

# right plot:
image2 = ax.imshow( data_arr2, cmap='gnuplot', interpolation='bilinear', extent=extent_arr2, \
                     origin='lower')

# define axes-labels:
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")

# define colour-bar at left side:
rect_loc = [0.0, 0.08, 0.03, 0.88]  # define position ---> how to automatise this?
cax2 = fig.add_axes(rect_loc)       # left | bottom | width | height
cbar2  = plt.colorbar(image2, cax=cax2)
cbar2.ax.yaxis.set_ticks_position('left')

# set limits:
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)

plt.show()
</code>```

output:

Thanks in advance!

答:
There are of course several ways to create a colorbar axes and put it next to a plot. I would recommend reading those questions:

positioning the colorbar

Matplotlib 2 Subplots, 1 Colorbar

Many of those concepts can be extended to a second colorbar. The solution I would personally prefer is the following, which uses an axes divider. The advantage is that the colorbar keeps the size of the axes.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

plt.rcParams.update({'figure.autolayout': True})

fig, ax = plt.subplots(figsize=(6,4))
im = ax.imshow(np.random.rand(10,10), extent=[-1,0,0,1], cmap="RdYlGn")
im2 = ax.imshow(np.random.rand(10,10), extent=[0,1,0,1], cmap="magma")
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_xlim(-1,1)
ax.set_ylim(0,1)

divider = make_axes_locatable(ax)
cax = divider.new_horizontal(size="5%", pad=0.2)
fig.add_axes(cax)
fig.colorbar(im2, cax=cax)

cax2 = divider.new_horizontal(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax2)
cb2 = fig.colorbar(im, cax=cax2)
cb2.ax.yaxis.set_ticks_position('left')
plt.show()
</code>```

Body:
I wish to create a "split plot", i.e. to use different colormaps in the left and the right half of my plot. Accordingly I will need two different colorbars. Unfortunately I have to set the position of the second colorbar by hand and modify everytime a label or title is included. Is there a way to automatise that?

I wondered if I could extract the rect parameter of the following minimal example from the right colorbar. That would help me as I only had shift it a bit. Any other (/better) idea is also welcome.

At the moment, whenever I change the labels or title a bit the manually set position of the left colorbar has to be modified again. This is very annoying. I include a running minimal example and a the output it produces:

import matplotlib as mpl
params = {
           'xtick.direction' : 'out',
           'ytick.direction' : 'out',
           'text.usetex'     : True,
         }

mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout': True})

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

extent_arr1 = [-1,0, -1,1]
extent_arr2 = [ 0,1, -1,1]
M = 501

# define test-data
data_arr1  = np.zeros((M, M))
data_arr2 = np.ones((M, M))

# define figure
fig = plt.figure()
ax = fig.add_subplot(111)

# left plot:
image1 = ax.imshow( data_arr1,  cmap='jet', interpolation='bilinear', extent=extent_arr1, \
                     origin='lower')
plt.title("Minimal example")
cbar1  = plt.colorbar(image1)

# right plot:
image2 = ax.imshow( data_arr2, cmap='gnuplot', interpolation='bilinear', extent=extent_arr2, \
                     origin='lower')

# define axes-labels:
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")

# define colour-bar at left side:
rect_loc = [0.0, 0.08, 0.03, 0.88]  # define position ---> how to automatise this?
cax2 = fig.add_axes(rect_loc)       # left | bottom | width | height
cbar2  = plt.colorbar(image2, cax=cax2)
cbar2.ax.yaxis.set_ticks_position('left')

# set limits:
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)

plt.show()

output:

Thanks in advance!

Body:
There are of course several ways to create a colorbar axes and put it next to a plot. I would recommend reading those questions:

positioning the colorbar

Matplotlib 2 Subplots, 1 Colorbar

Many of those concepts can be extended to a second colorbar. The solution I would personally prefer is the following, which uses an axes divider. The advantage is that the colorbar keeps the size of the axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

plt.rcParams.update({'figure.autolayout': True})

fig, ax = plt.subplots(figsize=(6,4))
im = ax.imshow(np.random.rand(10,10), extent=[-1,0,0,1], cmap="RdYlGn")
im2 = ax.imshow(np.random.rand(10,10), extent=[0,1,0,1], cmap="magma")
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_xlim(-1,1)
ax.set_ylim(0,1)

divider = make_axes_locatable(ax)
cax = divider.new_horizontal(size="5%", pad=0.2)
fig.add_axes(cax)
fig.colorbar(im2, cax=cax)

cax2 = divider.new_horizontal(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax2)
cb2 = fig.colorbar(im, cax=cax2)
cb2.ax.yaxis.set_ticks_position('left')
plt.show()


来源: stackexchange

问:
F# List.exists on two lists
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

```<code>let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]
</code>```

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

```<code>let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB
</code>```

答:
You can't write something like your example code because a plain for doesn't return a result, it just evaluates an expression for its side-effects.  You could write the code in a for comprehension:

```<code>let testIntersect listA listB =
    [for elem in listA do yield List.exists (fun x -> x = elem) listB]
</code>```

Of course, this then returns a bool list rather than a single bool.

```<code>val testIntersect :
  listA:seq<'a> -> listB:'a list -> bool list when 'a : equality

let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]

testIntersect listA listB
val it : bool list = [true; false; false]
</code>```

So, we can use the List.exists function to ensure that a true occurs at least once:

```<code>let testIntersect listA listB =
    [for elem in listA do yield List.exists (fun x -> x = elem) listB]
    |> List.exists id
</code>```

```<code>val testIntersect :
  listA:seq<'a> -> listB:'a list -> bool list when 'a : equality

val listA : string list = ["A"; "B"; "C"]
val listB : string list = ["D"; "E"; "A"]
val it : bool = false
</code>```

It's pretty inefficient to solve this problem using List though, it's better to use Set.  With Set, you can calculate intersection in O(log N * log M) time rather than O(N*M).

```<code>let testSetIntersect listA listB =
    Set.intersect (Set.ofList listA) (Set.ofList listB)
    |> Set.isEmpty
    |> not
</code>```

ContentLicense: CC BY-SA 3.0

Title: F# List.exists on two lists

Body:
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB

Body:
You can't write something like your example code because a plain for doesn't return a result, it just evaluates an expression for its side-effects.  You could write the code in a for comprehension:

let testIntersect listA listB =
    [for elem in listA do yield List.exists (fun x -> x = elem) listB]

Of course, this then returns a bool list rather than a single bool.

val testIntersect :
  listA:seq<'a> -> listB:'a list -> bool list when 'a : equality

let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]

testIntersect listA listB
val it : bool list = [true; false; false]

So, we can use the List.exists function to ensure that a true occurs at least once:

let testIntersect listA listB =
    [for elem in listA do yield List.exists (fun x -> x = elem) listB]
    |> List.exists id

val testIntersect :
  listA:seq<'a> -> listB:'a list -> bool list when 'a : equality

val listA : string list = ["A"; "B"; "C"]
val listB : string list = ["D"; "E"; "A"]
val it : bool = false

It's pretty inefficient to solve this problem using List though, it's better to use Set.  With Set, you can calculate intersection in O(log N * log M) time rather than O(N*M).

let testSetIntersect listA listB =
    Set.intersect (Set.ofList listA) (Set.ofList listB)
    |> Set.isEmpty
    |> not


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答: Yeah, definitely put a description in the alt tag.  It is really important for the visually impaired as this is what the screen readers will read when they come across an image.  The only potential catch with this is that the alt tag is treated as tool tip text by some browsers, however, you can override that behavior with setting title="".</p>

OwnerDisplayName: Brad

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brian Fisher


问:
How to call this kind of implementation in Java and how to change it to C#?
I have this piece of code:

```<code>protected class A
{
  protected void call1();
  protected void call2();
}

public class B
{
   protected A a = new A()
   {
      protected void call1(//modify);
   }
}
</code>```

Also, how can I translate this:

```<code>protected A a = new A()
{
  protected void call1(//modify);
;
</code>```

to C#?

答:
Sounds like you're after inheritance?</p>

```<code>public class B : A
{
   protected override void call1()
   {
      //new code here...
   }
}
</code>```

Body:
I have this piece of code:

protected class A
{
  protected void call1();
  protected void call2();
}

public class B
{
   protected A a = new A()
   {
      protected void call1(//modify);
   }
}

Also, how can I translate this:

protected A a = new A()
{
  protected void call1(//modify);
;

to C#?

Body:
Sounds like you're after inheritance?

public class B : A
{
   protected override void call1()
   {
      //new code here...
   }
}


问:
How can I install wordpress in the firebase hosting?
How can I install Wordpress in the Firebase Hosting ? I tried to find an article to help me to install but I didn't find one.</p>

答:
You can't install the dynamic version of Wordpress. Instead, you can create a static version of Wordpress using a plugin called Simply Static. Check it here: https://wordpress.org/plugins/simply-static/

It will export your site to html so the server won't need to support PHP or any database. It's great to use in simple websites that don't need to be updated frequently.


问:
Storing return values of functions in a tuple
Consider

```<code>#include <tuple>

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(f(0)...);
}

int foo(int) { return 5; }
int bar(int) { return 3; }

int main() {
    auto tuple = execute(foo, bar);
}
</code>```

What is a good workaround so that bar can return void?

I tried this, but it won't compile:

```<code>#include <tuple>

struct Void { };

template <typename T>
T check(T n) { return n; }

Void check(void) { return Void{}; }

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(check(f(0))...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}
</code>```

Update:  I have a tentative solution, but it only works if we know that the arguments passed is always int 0.  I'll try to make it work in any general setting.  Or perhaps use std::optional like Steve suggested.

```<code>#include <tuple>
#include <type_traits>

struct Void { };

template <typename F>
auto execute_h (F f, std::enable_if_t<!std::is_void_v<std::result_of_t<F(int)>>>* = nullptr) {
    const auto result = f(0);
    return result;
}

template <typename F>
auto execute_h (F f, std::enable_if_t<std::is_void_v<std::result_of_t<F(int)>>>* = nullptr) {
    f(0);
    return Void{};
}

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(execute_h(f)...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}
</code>```

答:
With abusing overload of operator , (as void(), T won't call custom operator,):

```<code>#include <tuple>

struct Void {};

template <typename T>
T&& operator , (T&& t, Void) { return std::forward<T>(t); }

template <typename... Fs>
auto execute (Fs... fs) {
    return std::make_tuple((f(0), Void{})...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar); // tuple<int, Void>
}
</code>```

Body:
Consider

#include <tuple>

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(f(0)...);
}

int foo(int) { return 5; }
int bar(int) { return 3; }

int main() {
    auto tuple = execute(foo, bar);
}

What is a good workaround so that bar can return void?

I tried this, but it won't compile:

#include <tuple>

struct Void { };

template <typename T>
T check(T n) { return n; }

Void check(void) { return Void{}; }

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(check(f(0))...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}

Update:  I have a tentative solution, but it only works if we know that the arguments passed is always int 0.  I'll try to make it work in any general setting.  Or perhaps use std::optional like Steve suggested.

#include <tuple>
#include <type_traits>

struct Void { };

template <typename F>
auto execute_h (F f, std::enable_if_t<!std::is_void_v<std::result_of_t<F(int)>>>* = nullptr) {
    const auto result = f(0);
    return result;
}

template <typename F>
auto execute_h (F f, std::enable_if_t<std::is_void_v<std::result_of_t<F(int)>>>* = nullptr) {
    f(0);
    return Void{};
}

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(execute_h(f)...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}

Body:
With abusing overload of operator , (as void(), T won't call custom operator,):

#include <tuple>

struct Void {};

template <typename T>
T&& operator , (T&& t, Void) { return std::forward<T>(t); }

template <typename... Fs>
auto execute (Fs... fs) {
    return std::make_tuple((f(0), Void{})...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar); // tuple<int, Void>
}


问:
How to analyse the trace file generated by ns2 using Visual Trace Analyser?
When i open a .tr file in NS-Visual-Trace-Analyser, it shows the all statistics and graphical results. But, when i add energy model to the nodes of the same network, Visual-Trace-Analyser shows no packet sent or received (not any event).

This is Tcl script i am trying..

```<code>`# This script is created by NSG2 beta1

 #===================================
 #     Simulation parameters setup
 #===================================
 set val(chan)   Channel/WirelessChannel ;# channel type

 set val(prop)   Propagation/TwoRayGround;# radio-propagation model

 set val(netif)  Phy/WirelessPhy    ;# network interface type

 set val(mac)    Mac/802_11         ;# MAC type

 set val(ifq)    Queue/DropTail/PriQueue;# interface queue type

 set val(ll)     LL                 ;# link layer type

 set val(ant)    Antenna/OmniAntenna;# antenna model

 set val(ifqlen) 50                 ;# max packet in ifq

 set val(nn)     2                  ;# number of mobilenodes

 set val(rp)     DSDV               ;# routing protocol

 set val(x)      968                ;# X dimension of topography

 set val(y)      450                ;# Y dimension of topography

 set val(stop)   20.0               ;# time of simulation end

 set opt(energymodel) EnergyModel   ;

 set opt(initialenergy) 30  ;

 #===================================
 #        Initialization
 #===================================

 #Create a ns simulator

 set ns [new Simulator]

 #Setup topography object

 set topo       [new Topography]

 $topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

#Open the NS trace file

set tracefile [open twonodes.tr w]

$ns trace-all $tracefile

#Open the NAM trace file

set namfile [open twonodes.nam w]

$ns namtrace-all $namfile

$ns namtrace-all-wireless $namfile $val(x) $val(y)

set chan [new $val(chan)];#Create wireless channel

#===================================
#     Mobile node parameter setup
#===================================
$ns node-config -adhocRouting  $val(rp) \

            -llType        $val(ll) \

            -macType       $val(mac) \

            -ifqType       $val(ifq) \

            -ifqLen        $val(ifqlen) \

            -antType       $val(ant) \

            -propType      $val(prop) \

            -phyType       $val(netif) \

            -channel       $chan \

            -topoInstance  $topo \

            -agentTrace    ON \

            -routerTrace   ON \

            -macTrace      ON\

            -movementTrace OFF \

            -energyModel $opt(energymodel) \

            -idlePower 1.0 \

            -rxPower 1.0 \

            -txPower 2.0 \

            -sleepPower 0.001 \

            -transitionPower 0.2 \

            -transitionTime 0.005 \

            -initialEnergy $opt(initialenergy)

$ns set WirelessNewTrace_ ON

#===================================
#        Nodes Definition
#===================================
#Create 2 nodes

set n0 [$ns node]

$n0 set X_ 383

$n0 set Y_ 309

$n0 set Z_ 0.0

$ns initial_node_pos $n0 20

set n1 [$ns node]

$n1 set X_ 568

$n1 set Y_ 350

$n1 set Z_ 0.0

$ns initial_node_pos $n1 20

#===================================
#        Generate movement
#================================

#===================================
#        Agents Definition
#===================================
#Setup a UDP connection

set tcp2 [new Agent/TCP]

$ns attach-agent $n0 $tcp2

set sink3 [new Agent/TCPSink]

$ns attach-agent $n1 $sink3

$ns connect $tcp2 $sink3

$tcp2 set packetSize_ 1500

#===================================
#        Applications Definition
#===================================
#Setup a CBR Application over UDP connection

set cbr1 [new Application/Traffic/CBR]

$cbr1 attach-agent $tcp2

$cbr1 set packetSize_ 1000

$cbr1 set rate_ 1.0Mb

$cbr1 set random_

$ns at 1.0 "$cbr1 start"

$ns at 20.0 "$cbr1 stop"

#===================================
#        Termination
#===================================
#Define a 'finish' procedure

proc finish {} {

    global ns tracefile namfile

    $ns flush-trace

    close $tracefile

    close $namfile

    exec nam twonodes.nam &

    exit 0

}

for {set i 0} {$i < $val(nn) } { incr i } {

    $ns at $val(stop) "\$n$i reset"

}

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "finish"

$ns at $val(stop) "puts \"done\" ; $ns halt"

$ns run
</code>```

'

答:
This happen to me too, and i solved it by disable printing of energy values from c++ to main trace file. Instead i printed energy values to a separate trace file

in cmu-trace.cc

```<code>if (thisnode) {
        if (thisnode->energy_model()) {
            // log detailed energy consumption
            // total energy and breakdown in idle, sleep, transmit and receive modes
            sprintf(pt_->buffer() + offset,
                "[energy %f ei %.3f es %.3f et %.3f er %.3f] ",
                thisnode->energy_model()->energy(),
                thisnode->energy_model()->ei(),
                thisnode->energy_model()->es(),
                thisnode->energy_model()->et(),
                thisnode->energy_model()->er());
        }
        }
</code>```

disable sprintf function.

Body:
When i open a .tr file in NS-Visual-Trace-Analyser, it shows the all statistics and graphical results. But, when i add energy model to the nodes of the same network, Visual-Trace-Analyser shows no packet sent or received (not any event).

This is Tcl script i am trying..

`# This script is created by NSG2 beta1

 #===================================
 #     Simulation parameters setup
 #===================================
 set val(chan)   Channel/WirelessChannel ;# channel type

 set val(prop)   Propagation/TwoRayGround;# radio-propagation model

 set val(netif)  Phy/WirelessPhy    ;# network interface type

 set val(mac)    Mac/802_11         ;# MAC type

 set val(ifq)    Queue/DropTail/PriQueue;# interface queue type

 set val(ll)     LL                 ;# link layer type

 set val(ant)    Antenna/OmniAntenna;# antenna model

 set val(ifqlen) 50                 ;# max packet in ifq

 set val(nn)     2                  ;# number of mobilenodes

 set val(rp)     DSDV               ;# routing protocol

 set val(x)      968                ;# X dimension of topography

 set val(y)      450                ;# Y dimension of topography

 set val(stop)   20.0               ;# time of simulation end

 set opt(energymodel) EnergyModel   ;

 set opt(initialenergy) 30  ;

 #===================================
 #        Initialization
 #===================================

 #Create a ns simulator

 set ns [new Simulator]

 #Setup topography object

 set topo       [new Topography]

 $topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

#Open the NS trace file

set tracefile [open twonodes.tr w]

$ns trace-all $tracefile

#Open the NAM trace file

set namfile [open twonodes.nam w]

$ns namtrace-all $namfile

$ns namtrace-all-wireless $namfile $val(x) $val(y)

set chan [new $val(chan)];#Create wireless channel

#===================================
#     Mobile node parameter setup
#===================================
$ns node-config -adhocRouting  $val(rp) \

            -llType        $val(ll) \

            -macType       $val(mac) \

            -ifqType       $val(ifq) \

            -ifqLen        $val(ifqlen) \

            -antType       $val(ant) \

            -propType      $val(prop) \

            -phyType       $val(netif) \

            -channel       $chan \

            -topoInstance  $topo \

            -agentTrace    ON \

            -routerTrace   ON \

            -macTrace      ON\

            -movementTrace OFF \

            -energyModel $opt(energymodel) \

            -idlePower 1.0 \

            -rxPower 1.0 \

            -txPower 2.0 \

            -sleepPower 0.001 \

            -transitionPower 0.2 \

            -transitionTime 0.005 \

            -initialEnergy $opt(initialenergy)

$ns set WirelessNewTrace_ ON

#===================================
#        Nodes Definition
#===================================
#Create 2 nodes

set n0 [$ns node]

$n0 set X_ 383

$n0 set Y_ 309

$n0 set Z_ 0.0

$ns initial_node_pos $n0 20

set n1 [$ns node]

$n1 set X_ 568

$n1 set Y_ 350

$n1 set Z_ 0.0

$ns initial_node_pos $n1 20

#===================================
#        Generate movement
#================================

#===================================
#        Agents Definition
#===================================
#Setup a UDP connection

set tcp2 [new Agent/TCP]

$ns attach-agent $n0 $tcp2

set sink3 [new Agent/TCPSink]

$ns attach-agent $n1 $sink3

$ns connect $tcp2 $sink3

$tcp2 set packetSize_ 1500

#===================================
#        Applications Definition
#===================================
#Setup a CBR Application over UDP connection

set cbr1 [new Application/Traffic/CBR]

$cbr1 attach-agent $tcp2

$cbr1 set packetSize_ 1000

$cbr1 set rate_ 1.0Mb

$cbr1 set random_

$ns at 1.0 "$cbr1 start"

$ns at 20.0 "$cbr1 stop"

#===================================
#        Termination
#===================================
#Define a 'finish' procedure

proc finish {} {

    global ns tracefile namfile

    $ns flush-trace

    close $tracefile

    close $namfile

    exec nam twonodes.nam &

    exit 0

}

for {set i 0} {$i < $val(nn) } { incr i } {

    $ns at $val(stop) "\$n$i reset"

}

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "finish"

$ns at $val(stop) "puts \"done\" ; $ns halt"

$ns run

'

Body:
This happen to me too, and i solved it by disable printing of energy values from c++ to main trace file. Instead i printed energy values to a separate trace file

in cmu-trace.cc

if (thisnode) {
        if (thisnode->energy_model()) {
            // log detailed energy consumption
            // total energy and breakdown in idle, sleep, transmit and receive modes
            sprintf(pt_->buffer() + offset,
                "[energy %f ei %.3f es %.3f et %.3f er %.3f] ",
                thisnode->energy_model()->energy(),
                thisnode->energy_model()->ei(),
                thisnode->energy_model()->es(),
                thisnode->energy_model()->et(),
                thisnode->energy_model()->er());
        }
        }

disable sprintf function.


答:
You can use std::enable_if and a wrapper function to return a Void object for functors that return void:

```<code>#include <tuple>
#include <type_traits>

struct Void { };

template <typename Func, typename... Args>
auto check(Func func, Args&&... args)
    -> std::enable_if_t<!std::is_void<decltype(func(std::forward<Args>(args)...))>::value, decltype(func(std::forward<Args>(args)...))>
{
    return func(std::forward<Args>(args)...);
}

template <typename Func, typename... Args>
auto check(Func func, Args&&... args)
    -> std::enable_if_t<std::is_void<decltype(func(std::forward<Args>(args)...))>::value, Void>
{
    func(std::forward<Args>(args)...); return Void{};
}

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(check(f, 0)...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}
</code>```

Live demo

It's a bit repetitive, but it gets the job done for any type of functor, any argument list, and any return type.

It's worth noting that there's a proposal floating around to make void a regular type that would let you avoid all of these hassles, but I'm not sure what the status of that is or if it will ever be accepted.

Title: Storing return values of functions in a tuple

Body:
You can use std::enable_if and a wrapper function to return a Void object for functors that return void:

#include <tuple>
#include <type_traits>

struct Void { };

template <typename Func, typename... Args>
auto check(Func func, Args&&... args)
    -> std::enable_if_t<!std::is_void<decltype(func(std::forward<Args>(args)...))>::value, decltype(func(std::forward<Args>(args)...))>
{
    return func(std::forward<Args>(args)...);
}

template <typename Func, typename... Args>
auto check(Func func, Args&&... args)
    -> std::enable_if_t<std::is_void<decltype(func(std::forward<Args>(args)...))>::value, Void>
{
    func(std::forward<Args>(args)...); return Void{};
}

template <typename... F>
auto execute (F... f) {
    return std::make_tuple(check(f, 0)...);
}

int foo(int) { return 5; }
void bar(int) { }

int main() {
    auto tuple = execute(foo, bar);
}

Live demo

It's a bit repetitive, but it gets the job done for any type of functor, any argument list, and any return type.

It's worth noting that there's a proposal floating around to make void a regular type that would let you avoid all of these hassles, but I'm not sure what the status of that is or if it will ever be accepted.


问:
Finite State Machine - Does each state have to be represented by a case in the switch statement?

Can this Finite State Machine be put into 4 cases? Or can this only be done with 3 cases since State D is not directly linked to State A with a certain bit.

```<code>while (true) {
    int bit2;
    if (state != D) {
        cout << "Enter a bit (1/0): ";
        int bit;
        cin >> bit;
        bit2 = bit;
    }

        switch (state) {
        case A:
            if (bit2 == 1) { state = B; }
            break;
        case B:
            if (bit2 == 0) { state = C; }
            break;
        case C:
            if (bit2 == 0) { state = D; }
            else { state = B; }
            break;
        case D:
            cout << "Done!" << endl;
            state = A;
            break;

    }
}

return 0;
</code>```

This is the code I used, and it works perfectly fine. Was just wondering if I have to address "State D"

答:
A naive implementation without boolean algebra taken into consideration might yield a switch statement that looks something like this:

char next(char state, int path) {
    switch (state) {
        case 'A': return path == 1 ? 'B' : 'A';
        case 'B': return path == 0 ? 'C' : 'B';
        case 'C': return path == 1 ? 'B' : 'D';
        case 'D':
        default: return 'A';
    }
}
```
<p>If you notice patterns like how a <code>path</code> of <code>1</code> leads to <code>B</code> except in case the case of <code>D</code> or in the indeterminate case, you can use less branches to achieve the same logic, so the short answer is no, you don't necessarily need 4 cases to handle 4 state transitions.</p>
<h3>Longer answer (Digital Logic Design Approach)</h3>
<p>Let's make a Karnaugh map to minimize the number of logical operations. The first two bits <code>SS</code> can represent the state:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>state</th>
<th>MSB</th>
<th>LSB</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>B</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>C</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>D</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Which we can achieve with:</p>
```SS = state - 'A';
```
<p>Here is the K-map for the given state machine:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><sub>path</sub> \ <sup>SS</sup></th>
<th>00</th>
<th>01</th>
<th>11</th>
<th>10</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>00</td>
<td>10</td>
<td>00</td>
<td>11</td>
</tr>
<tr>
<td>1</td>
<td>01</td>
<td>01</td>
<td>00</td>
<td>01</td>
</tr>
</tbody>
</table>
</div>
<p>This gives us the following sums of minterms for each bit of the next state:</p>
```MSB = path == 0 && (SS == 1 || SS == 2)
LSB = (path == 1 && (SS & 2) == 0) || SS == 2
```
<p>Putting that all together, that leaves us with the following implementation:</p>
<pre class="lang-cpp prettyprint-override"><code>char next(char state, int path) {
    int SS = state - 'A';
    int MSB = path == 0 && (SS == 1 || SS == 2);
    int LSB = (path == 1 && (SS & 2) == 0) || SS == 2;

    return 'A' + ((MSB << 1) | LSB);
}
</code>```

Body:
Can this Finite State Machine be put into 4 cases? Or can this only be done with 3 cases since State D is not directly linked to State A with a certain bit.

while (true) {
    int bit2;
    if (state != D) {
        cout << "Enter a bit (1/0): ";
        int bit;
        cin >> bit;
        bit2 = bit;
    }

        switch (state) {
        case A:
            if (bit2 == 1) { state = B; }
            break;
        case B:
            if (bit2 == 0) { state = C; }
            break;
        case C:
            if (bit2 == 0) { state = D; }
            else { state = B; }
            break;
        case D:
            cout << "Done!" << endl;
            state = A;
            break;

    }
}

return 0;

This is the code I used, and it works perfectly fine. Was just wondering if I have to address "State D"

Body:
A naive implementation without boolean algebra taken into consideration might yield a switch statement that looks something like this:

char next(char state, int path) {
    switch (state) {
        case 'A': return path == 1 ? 'B' : 'A';
        case 'B': return path == 0 ? 'C' : 'B';
        case 'C': return path == 1 ? 'B' : 'D';
        case 'D':
        default: return 'A';
    }
}

If you notice patterns like how a path of 1 leads to B except in case the case of D or in the indeterminate case, you can use less branches to achieve the same logic, so the short answer is no, you don't necessarily need 4 cases to handle 4 state transitions.

Longer answer (Digital Logic Design Approach)

Let's make a Karnaugh map to minimize the number of logical operations. The first two bits SS can represent the state:

state
MSB
LSB

A
0
0

B
0
1

C
1
0

D
1
1

Which we can achieve with:

SS = state - 'A';

Here is the K-map for the given state machine:

path \ SS
00
01
11
10

0
00
10
00
11

1
01
01
00
01

This gives us the following sums of minterms for each bit of the next state:

MSB = path == 0 && (SS == 1 || SS == 2)
LSB = (path == 1 && (SS & 2) == 0) || SS == 2

Putting that all together, that leaves us with the following implementation:

char next(char state, int path) {
    int SS = state - 'A';
    int MSB = path == 0 && (SS == 1 || SS == 2);
    int LSB = (path == 1 && (SS & 2) == 0) || SS == 2;

    return 'A' + ((MSB << 1) | LSB);
}

ContentLicense: CC BY-SA 4.0


问:
iterating through STRINGS in Python (3)
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

```<code>def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"
</code>```

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'

答:
You have unnecessarily complicated the problem with three nested loops, when a single loop is required.

Replace:

```<code>while counter < len(str2):
    for element in str1:
        for index in str2:
            newStr = newStr + element
            newStr = newStr + index
            counter += 1
return newStr
</code>```

With:

```<code>for index in range(len(str1)) :
    newStr = newStr + str1[index] + str2[index]

return newStr
</code>```

In the original code, if the string length was for example 6, your code says:

```<code> Repeat 6 times:
     for every character in str1
         for every character in str1
             do stuff
</code>```

so that do stuff is executed 6 x 6 x 6 times! You only want to execute it 6 times suggesting a single loop.

What you were doing wrong was not a python specific issue, but  rather an issue with your algorithmic and logical thinking.  Mathematically the problem suggests a single iteration, while you had three - nested.  In this case you might have manually walked through the code or used a debugger to step through it to demonstrate flaw in thinking here.

Title: iterating through STRINGS in Python (3)

Body:
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'

Body:
You have unnecessarily complicated the problem with three nested loops, when a single loop is required.

Replace:

while counter < len(str2):
    for element in str1:
        for index in str2:
            newStr = newStr + element
            newStr = newStr + index
            counter += 1
return newStr

With:

for index in range(len(str1)) :
    newStr = newStr + str1[index] + str2[index]

return newStr

In the original code, if the string length was for example 6, your code says:

 Repeat 6 times:
     for every character in str1
         for every character in str1
             do stuff

so that do stuff is executed 6 x 6 x 6 times! You only want to execute it 6 times suggesting a single loop.

What you were doing wrong was not a python specific issue, but  rather an issue with your algorithmic and logical thinking.  Mathematically the problem suggests a single iteration, while you had three - nested.  In this case you might have manually walked through the code or used a debugger to step through it to demonstrate flaw in thinking here.


问:
How to add different shipping price for additional item
In WooCommerce I am trying to have different shipping prices based on cart item count.

Example:

1 item $5

2 item $5 + $2

3 item $5 + (2 x 2$) … and so on …

So the first item will set a cost of $5 and all additional items will add 2$ for each of them.

Is this possible?

答:
Updated - Two steps:

1) Add this code that will make your shipping calculation cost based on cart items count (the total quantity of items):

```<code>add_filter( 'woocommerce_package_rates', 'progressive_flat_rate_cost_calculation', 10, 2 );
function progressive_flat_rate_cost_calculation( $rates, $package )
{
    // The cart count (total items in cart)
    $cart_count = WC()->cart->get_cart_contents_count();
    $taxes = array();

    $cost = 5; // Cost for the 1st item
    $other = 2; // Cost for additional items

    // Calculation
    if( $cart_count > 1 )
        $cost += ($cart_count - 1) * $other;

    // Iterating through each shipping rate
    foreach($rates as $rate_key => $rate_values){
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;
        // Targeting "Flat Rate" shipping method
        if ( 'flat_rate' === $method_id ) {
            // Set the new calculated rate cost
            $rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_id]->taxes as $key => $tax){
                if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
                    $taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
                    $has_taxes = true;
                } else {
                    $has_taxes = false;
                }
            }
            if( $has_taxes )
                $rates[$rate_id]->taxes = $taxes;
        }
    }
    return $rates;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

2) Now, In the general shipping settings, you will need to set a "Flat rate" shipping method for each Shipping Zones which cost will be set to 1 (in your WooCommerce shipping settings).

Sometimes you will need to refresh shipping zones caches (in woocommerce shipping settings for each zone):
 Disabling each Flat rate, then save, then enabling back this flat rate and save.

  Is better to start on a fresh new cart (so empty it before testing)

This code is tested on WooCommerce 3+ and works

Body:
Updated - Two steps:

1) Add this code that will make your shipping calculation cost based on cart items count (the total quantity of items):

add_filter( 'woocommerce_package_rates', 'progressive_flat_rate_cost_calculation', 10, 2 );
function progressive_flat_rate_cost_calculation( $rates, $package )
{
    // The cart count (total items in cart)
    $cart_count = WC()->cart->get_cart_contents_count();
    $taxes = array();

    $cost = 5; // Cost for the 1st item
    $other = 2; // Cost for additional items

    // Calculation
    if( $cart_count > 1 )
        $cost += ($cart_count - 1) * $other;

    // Iterating through each shipping rate
    foreach($rates as $rate_key => $rate_values){
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;
        // Targeting "Flat Rate" shipping method
        if ( 'flat_rate' === $method_id ) {
            // Set the new calculated rate cost
            $rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_id]->taxes as $key => $tax){
                if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
                    $taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
                    $has_taxes = true;
                } else {
                    $has_taxes = false;
                }
            }
            if( $has_taxes )
                $rates[$rate_id]->taxes = $taxes;
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

2) Now, In the general shipping settings, you will need to set a "Flat rate" shipping method for each Shipping Zones which cost will be set to 1 (in your WooCommerce shipping settings).

Sometimes you will need to refresh shipping zones caches (in woocommerce shipping settings for each zone):
 Disabling each Flat rate, then save, then enabling back this flat rate and save.

  Is better to start on a fresh new cart (so empty it before testing)

This code is tested on WooCommerce 3+ and works


问:
jquery: mouseout event firing even after I used a click event to hide the div
```<code>jQuery("#na").mouseover(function()
{
    jQuery("#na").animate({width:"325px", height:"203px", left:"-40px", top:"-25px"}, 200)
});

jQuery("#na").mouseout(function()
{
    jQuery("#na").stop()
    jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
});

jQuery("#na").click(function()
{
    jQuery("#na").hide()
    jQuery("#back").show()
});
</code>```

so thats my code, the problem is when the click event is triggered all is fine, na dissapears but the moment you move your mouse it reappers again. I figured the problem is that the mouseout event is being triggered, but for the life of me cant figure out how to fix it. any ideas?

答:
```<code>jQuery("#na").click(function(e)
{
    e.stopPropagation();
    jQuery("#na").hide()
    jQuery("#back").show()
});
</code>```

I am not sure if this would work.. Theoretically this should stop the propogation of the mous ent but i am not sure if it only stop the click event being propogated!

Body:
jQuery("#na").mouseover(function()
{
    jQuery("#na").animate({width:"325px", height:"203px", left:"-40px", top:"-25px"}, 200)
});

jQuery("#na").mouseout(function()
{
    jQuery("#na").stop()
    jQuery("#na").animate({width:"244px",height:"152px", left:0, top:0}, 200)
});

jQuery("#na").click(function()
{
    jQuery("#na").hide()
    jQuery("#back").show()
});

so thats my code, the problem is when the click event is triggered all is fine, na dissapears but the moment you move your mouse it reappers again. I figured the problem is that the mouseout event is being triggered, but for the life of me cant figure out how to fix it. any ideas?

Body:
jQuery("#na").click(function(e)
{
    e.stopPropagation();
    jQuery("#na").hide()
    jQuery("#back").show()
});

I am not sure if this would work.. Theoretically this should stop the propogation of the mous ent but i am not sure if it only stop the click event being propogated!


问:
How to update the list view using LINQ query (sharepoint 2007)
How to update the list view using LINQ query (sharepoint 2007):</p>

```<code>SPList taskList = SPContext.Current.Web.Lists["List1"];
SPList branchList = SPContext.Current.Web.Lists["List2"];

var taskListItems = from SPListItem tItem in taskList.Items
                    join SPListItem IItem in branchList.Items on tItem["Branch"].ToString().Split(new string[]{";#"},StringSplitOptions.None)[1] equals IItem.Title.ToString()
                    where IItem.Title.ToString() == "Kazan"
                    select tItem.Title;
</code>```

答:
SharePoint 2007 does not support Linq (.net 3.5) out of the box, i guess you are using a template??

You will need to follow a guide to get it setup:

http://www.zimmergren.net/archive/2008/09/22/how-to-get-up-and-running-with-net-3-5-in-your-sharepoint-environment.aspx

Then maybe this guide will help you build your query

http://www.zimmergren.net/archive/2008/09/24/how-to-use-linq-and-the-net-3-5-framework-with-sharepoint-to-retreive-sharepoint-list-items.aspx

Body:
How to update the list view using LINQ query (sharepoint 2007):

SPList taskList = SPContext.Current.Web.Lists["List1"];
SPList branchList = SPContext.Current.Web.Lists["List2"];

var taskListItems = from SPListItem tItem in taskList.Items
                    join SPListItem IItem in branchList.Items on tItem["Branch"].ToString().Split(new string[]{";#"},StringSplitOptions.None)[1] equals IItem.Title.ToString()
                    where IItem.Title.ToString() == "Kazan"
                    select tItem.Title;


问:
Mulesoft , Architectural suggession
I have following architectural issues .

I have two tomcat servers . Each running few services. One of the server is deployed at DMZ and other one is behind firewall ( inside application landscape). I am in the process of deploying another server Mule ESB. Consolidating all the services and deploying it on single Mule EE server.

My question is what would be the right security strategy for implementing the services running on DMZ and other set of service running behind the firewall. Since i am consolidating my services running on DMZ and behind the firewall , and deploying it on ESB which is hosted behind firewall , is there any security issues you can foresee. if i remove services from DMZ and deploying it on behind the firewall , do you foresee any other issues like performance etc

答:
There will not be any security issues, also there wont be any performance issues.

Can you confirm where this Mule ESB server will sit - It must be behind the firewall. If yes then you can install on-prem version of API Gateway in DMZ location which will give you more security policies (comes by default with mule api gateway ) without building those at the service level.

Note, you can build your own custom policies for the Services which can be added through API manager for API Gateways and this can be developed by YAML/XML files.

Title: Mulesoft , Architectural suggession


问:
C#, Regex, ASCII Escape Characters - won't match
```<code>string pat12 = @"\e\[36m(.+)";
line2parse = "[36mA Rocky Landing";
if (Regex.Match(line2parse,pat12).Success)
{
    Console.WriteLine("ROOM NAME: "+Regex.Match(line2parse,pat12).Groups[1].ToString().Trim());
}
</code>```

NOTE: You are unable to see the ESC sequence before the [36 in my variable "line2parse" but its there.  If I wanted to make it show up in Notepad++ I would hold down ALT and type "027" on the numpad. It then shows up as ESC in Notepad++.  In C# console it shows up as a left pointing arrow.  Ironically I can do "ALT + 27" and it shows that left arrow in Notepad++ (but if i add the 0, it does the ESC look instead of the arrow)

I am doing many Regex matches so the problem isn't with my Regex variable or anything like that.  I cannot get this to match properly despite it working at this site:  http://regexstorm.net/tester

At that site, this is the pattern:  "\e[36m(.+)" (without quotes) and this is the input: [36mA Rocky Landing (again you can't see the escape thing).  It then tells me $1 would be "A Rocky Landing" but in my actual code, it doesn't match.

What am I doing wrong?

I have looked through quite a few other, similar, posts and based on what they say, I believe this should work.  I even tried [^\x00-\x7F] as my escape char catch and it still wont match.

答:
Why do you think \e is the escape sequence for an escape character? You need to use \x1b instead.

```<code>string pat12 = @"\x1b\[36m(.+)";
</code>```

Body:
string pat12 = @"\e\[36m(.+)";
line2parse = "[36mA Rocky Landing";
if (Regex.Match(line2parse,pat12).Success)
{
    Console.WriteLine("ROOM NAME: "+Regex.Match(line2parse,pat12).Groups[1].ToString().Trim());
}

NOTE: You are unable to see the ESC sequence before the [36 in my variable "line2parse" but its there.  If I wanted to make it show up in Notepad++ I would hold down ALT and type "027" on the numpad. It then shows up as ESC in Notepad++.  In C# console it shows up as a left pointing arrow.  Ironically I can do "ALT + 27" and it shows that left arrow in Notepad++ (but if i add the 0, it does the ESC look instead of the arrow)

I am doing many Regex matches so the problem isn't with my Regex variable or anything like that.  I cannot get this to match properly despite it working at this site:  http://regexstorm.net/tester

At that site, this is the pattern:  "\e[36m(.+)" (without quotes) and this is the input: [36mA Rocky Landing (again you can't see the escape thing).  It then tells me $1 would be "A Rocky Landing" but in my actual code, it doesn't match.

What am I doing wrong?

I have looked through quite a few other, similar, posts and based on what they say, I believe this should work.  I even tried [^\x00-\x7F] as my escape char catch and it still wont match.

Body:
Why do you think \e is the escape sequence for an escape character? You need to use \x1b instead.

string pat12 = @"\x1b\[36m(.+)";


问:
JSON-Schema, basic sample doesn't validate
I have this following example schema:

```<code>{
    "id": "http://schema.acme.com/widgets",
    "$schema": "http://json-schema.org/draft-06/schema#",
    "definitions": {
        "bentWidget": {
            "type": "object",
            "required": ["angle", "baseWidget"],
            "properties": {
                "angle": {
                    "type": "number",
                    "minimum": 0,
                    "maximum": 90
                },
                "baseWidget": {
                    "$ref": "#/definitions/baseWidget"
                }
            }
        },
        "highPowerWidget": {
            "type": "object",
            "required": ["power", "baseWidget"],
            "properties": {
                "power": {
                    "type": "number",
                    "minimum": 101,
                    "maximum": 200
                },
                "baseWidget": {
                    "$ref": "#/definitions/baseWidget"
                }
            }
        },
        "color": {
            "description": "the color of a widget",
            "type": "string"
        },
        "baseWidget": {
            "description": "The base type for a widget",
            "type": "object",
            "required": [
                "title",
                "version",
                "colors"
            ],
            "properties": {
                "title": {
                    "type": "string",
                    "maximum": 100,
                    "minimum": 1,
                    "pattern": "^[a-zA-Z]+((_[a-zA-Z]+)*|([a-zA-Z]+_)*|_)"
                },
                "flanged": {
                    "type": "boolean"
                },
                "version": {
                    "type": "string",
                    "maximum": 64,
                    "minimum": 1
                },
                "colors": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/color"
                    }
                }
            }
        }
    },

    "anyOf": [
        { "$ref": "#/definitions/baseWidget" },
        { "$ref": "#/definitions/bentWidget" },
        { "$ref": "#/definitions/highPowerWidget" }
    ]
}
</code>```

and I want to test it, so I write this out to a file:

```<code>{
    "type": "highPowerWidget",
    "title": "foobar",
    "version": "foo"
}
</code>```

and then I run ajv on it from a shell

```<code>$ ajv -s widgetSchema.json -d widget-highPower.json
widget-highPower.json valid
</code>```

And it tells me that it is valid, which is incorrect, a highPowerWidget must have a power property, and the "inherited" version and colors property.

I was able to test my individual schemas by removing the anyOf section and putting in something like this:

```<code>"properties": {
    "testObject": {
        "type": "object",
        "oneOf": [
            { "$ref": "#/definitions/baseWidget" },
            { "$ref": "#/definitions/bentWidget" },
            { "$ref": "#/definitions/highPowerWidget" }
        ]
    }
},
"required": [ "testObject" ]
</code>```

and validating this JSON:

```<code>{
   "testObject": {
        "type" : "highPowerWidget",
        "title" : "title",
        "version" : "baz",
        "colors" : [ "red", "green", "blue"],
        "flanged" : true
   }

}
</code>```

But this seems wrong for two reasons.

I shouldn't have to have a "testObject" property

The oneOf only worked when I listed a single line, using multiple lines validate anything.

I think I have a basic misunderstanding of how I can write, or at least test, my schemas. My goal is to have an array of objects that all validate, and a set of files which all fail. This way I can unit test my schema.

答:
Your schema is valid.  As written this would be a valid highPowerWidget:

```<code>{
    "power": 150,
     "baseWidget":{
        "title": "SuperHighPower",
        "flanged":true,
        "version": "version 1",
        "colors":["blue"]
     }
}
</code>```

I think the misunderstanding is that JSONSchema doesn't support OO style inheritance.

Instead this schema is essentially asking for a "baseWidget" property on either the highPowerWidget or bentWidget.  Here's a sandbox plnkr for AJV you can test it with.

EDIT: Just thought about it and you could accomplish this removing the baseWidget property from bentWidget and highPowerWidget and instead add "allOf":[{"$ref":"#/definitions/baseWidget"}] to each of the subwidgets.  That would require them to pass baseWidget's schema.  So your schema would be:

```<code>{
  "id": "http://schema.acme.com/widgets",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "definitions": {
    "bentWidget": {
      "type": "object",
      "required": ["angle"],
      "properties": {
        "angle": {
          "type": "number",
          "minimum": 0,
          "maximum": 90
        }
      },
      allOf: [{
        "$ref": "#/definitions/baseWidget"
      }]
    },
    "highPowerWidget": {
      "type": "object",
      "required": ["power"],
      "properties": {
        "power": {
          "type": "number",
          "minimum": 101,
          "maximum": 200
        }
      },
      allOf: [{
        "$ref": "#/definitions/baseWidget"
      }]
    },
    "color": {
      "description": "the color of a widget",
      "type": "string"
    },
    "baseWidget": {
      "description": "The base type for a widget",
      "type": "object",
      "required": [
        "title",
        "version",
        "colors"
      ],
      "properties": {
        "title": {
          "type": "string",
          "maximum": 100,
          "minimum": 1,
          "pattern": "^[a-zA-Z]+((_[a-zA-Z]+)*|([a-zA-Z]+_)*|_)"
        },
        "flanged": {
          "type": "boolean"
        },
        "version": {
          "type": "string",
          "maximum": 64,
          "minimum": 1
        },
        "colors": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/color"
          }
        }
      }
    }
  },

  "anyOf": [{
    "$ref": "#/definitions/baseWidget"
  }, {
    "$ref": "#/definitions/bentWidget"
  }, {
    "$ref": "#/definitions/highPowerWidget"
  }]
}
</code>```

Body:
I have this following example schema:

{
    "id": "http://schema.acme.com/widgets",
    "$schema": "http://json-schema.org/draft-06/schema#",
    "definitions": {
        "bentWidget": {
            "type": "object",
            "required": ["angle", "baseWidget"],
            "properties": {
                "angle": {
                    "type": "number",
                    "minimum": 0,
                    "maximum": 90
                },
                "baseWidget": {
                    "$ref": "#/definitions/baseWidget"
                }
            }
        },
        "highPowerWidget": {
            "type": "object",
            "required": ["power", "baseWidget"],
            "properties": {
                "power": {
                    "type": "number",
                    "minimum": 101,
                    "maximum": 200
                },
                "baseWidget": {
                    "$ref": "#/definitions/baseWidget"
                }
            }
        },
        "color": {
            "description": "the color of a widget",
            "type": "string"
        },
        "baseWidget": {
            "description": "The base type for a widget",
            "type": "object",
            "required": [
                "title",
                "version",
                "colors"
            ],
            "properties": {
                "title": {
                    "type": "string",
                    "maximum": 100,
                    "minimum": 1,
                    "pattern": "^[a-zA-Z]+((_[a-zA-Z]+)*|([a-zA-Z]+_)*|_)"
                },
                "flanged": {
                    "type": "boolean"
                },
                "version": {
                    "type": "string",
                    "maximum": 64,
                    "minimum": 1
                },
                "colors": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/color"
                    }
                }
            }
        }
    },

    "anyOf": [
        { "$ref": "#/definitions/baseWidget" },
        { "$ref": "#/definitions/bentWidget" },
        { "$ref": "#/definitions/highPowerWidget" }
    ]
}

and I want to test it, so I write this out to a file:

{
    "type": "highPowerWidget",
    "title": "foobar",
    "version": "foo"
}

and then I run ajv on it from a shell

$ ajv -s widgetSchema.json -d widget-highPower.json
widget-highPower.json valid

And it tells me that it is valid, which is incorrect, a highPowerWidget must have a power property, and the "inherited" version and colors property.

I was able to test my individual schemas by removing the anyOf section and putting in something like this:

"properties": {
    "testObject": {
        "type": "object",
        "oneOf": [
            { "$ref": "#/definitions/baseWidget" },
            { "$ref": "#/definitions/bentWidget" },
            { "$ref": "#/definitions/highPowerWidget" }
        ]
    }
},
"required": [ "testObject" ]

and validating this JSON:

{
   "testObject": {
        "type" : "highPowerWidget",
        "title" : "title",
        "version" : "baz",
        "colors" : [ "red", "green", "blue"],
        "flanged" : true
   }

}

But this seems wrong for two reasons.

I shouldn't have to have a "testObject" property

The oneOf only worked when I listed a single line, using multiple lines validate anything.

I think I have a basic misunderstanding of how I can write, or at least test, my schemas. My goal is to have an array of objects that all validate, and a set of files which all fail. This way I can unit test my schema.

Body:
Your schema is valid.  As written this would be a valid highPowerWidget:

{
    "power": 150,
     "baseWidget":{
        "title": "SuperHighPower",
        "flanged":true,
        "version": "version 1",
        "colors":["blue"]
     }
}

I think the misunderstanding is that JSONSchema doesn't support OO style inheritance.

Instead this schema is essentially asking for a "baseWidget" property on either the highPowerWidget or bentWidget.  Here's a sandbox plnkr for AJV you can test it with.

EDIT: Just thought about it and you could accomplish this removing the baseWidget property from bentWidget and highPowerWidget and instead add "allOf":[{"$ref":"#/definitions/baseWidget"}] to each of the subwidgets.  That would require them to pass baseWidget's schema.  So your schema would be:

{
  "id": "http://schema.acme.com/widgets",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "definitions": {
    "bentWidget": {
      "type": "object",
      "required": ["angle"],
      "properties": {
        "angle": {
          "type": "number",
          "minimum": 0,
          "maximum": 90
        }
      },
      allOf: [{
        "$ref": "#/definitions/baseWidget"
      }]
    },
    "highPowerWidget": {
      "type": "object",
      "required": ["power"],
      "properties": {
        "power": {
          "type": "number",
          "minimum": 101,
          "maximum": 200
        }
      },
      allOf: [{
        "$ref": "#/definitions/baseWidget"
      }]
    },
    "color": {
      "description": "the color of a widget",
      "type": "string"
    },
    "baseWidget": {
      "description": "The base type for a widget",
      "type": "object",
      "required": [
        "title",
        "version",
        "colors"
      ],
      "properties": {
        "title": {
          "type": "string",
          "maximum": 100,
          "minimum": 1,
          "pattern": "^[a-zA-Z]+((_[a-zA-Z]+)*|([a-zA-Z]+_)*|_)"
        },
        "flanged": {
          "type": "boolean"
        },
        "version": {
          "type": "string",
          "maximum": 64,
          "minimum": 1
        },
        "colors": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/color"
          }
        }
      }
    }
  },

  "anyOf": [{
    "$ref": "#/definitions/baseWidget"
  }, {
    "$ref": "#/definitions/bentWidget"
  }, {
    "$ref": "#/definitions/highPowerWidget"
  }]
}


问:
ValueError: arrays must all be same length in Pandas
I was following Sentdex's second tutorial on pandas basics, and ran into this problem. Here's my code up to this point:

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

web_stats = {'Day' : [1,2,3,4,5,6],
             'Visitors' : [43,53,34,45,64,34],
             'Bounce_Rate' : [65,72,62,64,66]}

df = pd.DataFrame(web_stats)

print(df)
</code>```

I was really confused when this error message popped up. Please note that I'm on a mac.

```<code>Traceback (most recent call last):
  File "/Users/Terry/Documents/df.py", line 10, in <module>
    df = pd.DataFrame(web_stats)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 275, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 411, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 5496, in _arrays_to_mgr
    index = extract_index(arrays)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 5544, in extract_index
    raise ValueError('arrays must all be same length')
ValueError: arrays must all be same length
>>>
</code>```

Any help would be much appreciated.

答:
Bounce_Rate has less values than the amount of days / visitors. Check your web_stats dictionary

I.e. adding an item (an int i.e. a number) to that list would fix it. But make sure, you notice in the below example I change the list values to [65, 72, 62, 64, 54, 66] according to comments. You will probably want to check which values should go there.

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

web_stats = {'Day' : [1,2,3,4,5,6],
             'Visitors' : [43,53,34,45,64,34],
             'Bounce_Rate' : [65, 72, 62, 64, 54, 66]}  # Copied values from tutorial according to comments.

df = pd.DataFrame(web_stats)

print(df)
</code>```

Body:
I was following Sentdex's second tutorial on pandas basics, and ran into this problem. Here's my code up to this point:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

web_stats = {'Day' : [1,2,3,4,5,6],
             'Visitors' : [43,53,34,45,64,34],
             'Bounce_Rate' : [65,72,62,64,66]}

df = pd.DataFrame(web_stats)

print(df)

I was really confused when this error message popped up. Please note that I'm on a mac.

Traceback (most recent call last):
  File "/Users/Terry/Documents/df.py", line 10, in <module>
    df = pd.DataFrame(web_stats)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 275, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 411, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 5496, in _arrays_to_mgr
    index = extract_index(arrays)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 5544, in extract_index
    raise ValueError('arrays must all be same length')
ValueError: arrays must all be same length
>>>

Any help would be much appreciated.

Body:
Bounce_Rate has less values than the amount of days / visitors. Check your web_stats dictionary

I.e. adding an item (an int i.e. a number) to that list would fix it. But make sure, you notice in the below example I change the list values to [65, 72, 62, 64, 54, 66] according to comments. You will probably want to check which values should go there.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

web_stats = {'Day' : [1,2,3,4,5,6],
             'Visitors' : [43,53,34,45,64,34],
             'Bounce_Rate' : [65, 72, 62, 64, 54, 66]}  # Copied values from tutorial according to comments.

df = pd.DataFrame(web_stats)

print(df)


问:
grep: finding a string that starts and ends with a specific letter in directory
I am teaching myself commands and different ways to use grep. I know how to search for a string in a directory and its sub directories, but I am confused when it comes to searching for a split in the string.

for example: how could I search for all words (string size varies) that starts with a and ends with e. so that I could find ape or apple in text files?

EDIT UPDATE:
I am not sure of the grep version I am using, but I tried using:

" grep -nr "a[A-Za-z]*e" "

this produces the answer by including outputs like ape and apple but it also includes apes which is NOT wanted.

答:
I suppose you could use:

```<code>find . -type f -name '*.txt' -exec cat {} \; | grep 'a[A-Za-z]\+e'
</code>```

That should cat any .txt files in the current directory, recursively, and grep for "a... any characters... e"

The [A-Za-z] searches for a character of either case, the \+ says "any number of them".

I think that's what you're after?

Edit:

Word boundaries:

```<code>find . -type f -name '*.txt' -exec cat {} \+ | grep '\ba[A-Za-z]\+e\b'
</code>```

Body:
I suppose you could use:

find . -type f -name '*.txt' -exec cat {} \; | grep 'a[A-Za-z]\+e'

That should cat any .txt files in the current directory, recursively, and grep for "a... any characters... e"

The [A-Za-z] searches for a character of either case, the \+ says "any number of them".

I think that's what you're after?

Edit:

Word boundaries:

find . -type f -name '*.txt' -exec cat {} \+ | grep '\ba[A-Za-z]\+e\b'


问:
calculate an unique id from an array/class
I use a data class to feed templates my data, I want to calculate a unique id from the data in the data class so I can check if the template with that data is already in cache and then serve that version.

so a function to get an unique id from an array of a class would help me out.

something like this works but is rather costly md5(serialize($classdata))

I'm hoping there is some function to get the unique id without serializing all data, or at least not to have to in php.

edit:

I celebrated too soon, the unique id is only the same in the current instance
a restart of the same script makes another id, which then of course is not in cache.

testscript used:

```<code><?php
class foo {}
$f = new foo;
print spl_object_hash($f);
</code>```

I'll explain in some more depth

```<code>class template_data implements IteratorAggregate, ArrayAccess, Countable {

    private $_data;

    //some methods for the overloaded classes
    //

    //the getId function
    public function getId() {
        return hash('md5',serialize($this->_data));
    }

}

$t = new template('file');
$d = new template_data('some data');
$t->addData($d);
$t->display();
</code>```

Now if the data given to the template engine is in cache it uses that version
preventing to having to re-parse the template for the dataset.

This is a simplistic view of the template_data, it is actually lazy loading and uses memcached dataid's so the data isn't actually fetched till it is used in the template.

答:
You could try spl_object_hash()

From the docs

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects or for identifying an object.

Body:
I use a data class to feed templates my data, I want to calculate a unique id from the data in the data class so I can check if the template with that data is already in cache and then serve that version.

so a function to get an unique id from an array of a class would help me out.

something like this works but is rather costly md5(serialize($classdata))

I'm hoping there is some function to get the unique id without serializing all data, or at least not to have to in php.

edit:

I celebrated too soon, the unique id is only the same in the current instance
a restart of the same script makes another id, which then of course is not in cache.

testscript used:

<?php
class foo {}
$f = new foo;
print spl_object_hash($f);

I'll explain in some more depth

class template_data implements IteratorAggregate, ArrayAccess, Countable {

    private $_data;

    //some methods for the overloaded classes
    //

    //the getId function
    public function getId() {
        return hash('md5',serialize($this->_data));
    }

}

$t = new template('file');
$d = new template_data('some data');
$t->addData($d);
$t->display();

Now if the data given to the template engine is in cache it uses that version
preventing to having to re-parse the template for the dataset.

This is a simplistic view of the template_data, it is actually lazy loading and uses memcached dataid's so the data isn't actually fetched till it is used in the template.


问:
Unable to locate element when element is still present

Driver is unable to find element on the page even when its present
  . Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code  :

```<code>System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        //driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.get("https://www.sportskeeda.com/wwe");
        //WebElement popup=driver.findElement(By.className("bullbg"));
        WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));

        if (popup.isDisplayed())
        {

            System.out.println("True");
        }
        else
        {

            System.out.println("False");
        }
</code>```

ERROR

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to locate element: //div[contains(text(),'Close')]

Please click here to check there is a popup which gets display

答:
Try scrolling to the element first, something might be in the way</p>

```<code>WebElement element = driver.findElement(By.id("id"));

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
</code>```

Body:
Driver is unable to find element on the page even when its present
  . Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code  :

System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        //driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.get("https://www.sportskeeda.com/wwe");
        //WebElement popup=driver.findElement(By.className("bullbg"));
        WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));

        if (popup.isDisplayed())
        {

            System.out.println("True");
        }
        else
        {

            System.out.println("False");
        }

ERROR

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to locate element: //div[contains(text(),'Close')]

Please click here to check there is a popup which gets display

Body:
Try scrolling to the element first, something might be in the way

WebElement element = driver.findElement(By.id("id"));

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);


问:
c++ conversion string- unsigned char
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

```<code>std::vector<unsigned char>vect;
</code>```

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

答:
give type to vector.
std::vector vec;

to

std::vector< string> vec or whatever you need. and vector push_back signature is  void push_back(const T&). It does not take two arguments.

Title: c++ conversion string- unsigned char

Body:
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

std::vector<unsigned char>vect;

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.


问:
How to convert csv file to text file using python?
I want to convert a couple of .csv files to .txt files using python. In my .csv files, I have hundreds of lines of data like the bellow:
image of the csv file

```<code>Value   Date    Time
919     4/15/2016   19:41:02
551     4/15/2016   19:46:51
717     4/15/2016   19:49:48
2679    4/15/2016   19:52:49
2890    4/15/2016   19:55:43
2897    4/15/2016   19:58:38
1790    4/15/2016   21:39:14
2953    4/15/2016   21:42:10
2516    4/15/2016   21:45:04
2530    4/15/2016   21:47:58
2951    4/15/2016   21:51:02
2954    4/15/2016   21:53:56
2537    4/15/2016   21:56:52
2523    4/15/2016   21:59:45
2536    4/15/2016   22:02:49
2727    4/15/2016   22:05:43
</code>```

I use the bellow code for this purpose.

```<code>csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

text_list = []

with open(csv_file, "r") as my_input_file:
    for line in my_input_file:
        line = line.split(",", 2)
        text_list.append(" ".join(line))

with open(txt_file, "w") as my_output_file:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')
</code>```

My first problem is that when the name of the input file is (for example) "DFW002_0330PM_Thursday_November_16_2017", I get the bellow error:

```<code>Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 1, in <module>
    csv_file = input('Enter the name of your input file: ')
  File "<string>", line 1, in <module>
NameError: name 'DFW000_0330PM_Thursday_November_16_2017' is not defined
</code>```

But, when I change the name of the code to (for example) "11", the code defines the file and goes to the next steps, but again it returns the bellow error:

```<code>Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 6, in <module>
    with open(csv_file, "r") as my_input_file:
TypeError: coercing to Unicode: need string or buffer, int found
</code>```

Would you please help me handle these problems?

答:
Using csv it's very easy to iterate over the csv lines:

```<code>import csv
csv_file = raw_input('Enter the name of your input file: ')
txt_file = raw_input('Enter the name of your output file: ')
with open(txt_file, "w") as my_output_file:
    with open(csv_file, "r") as my_input_file:
        [ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
    my_output_file.close()
</code>```

Body:
I want to convert a couple of .csv files to .txt files using python. In my .csv files, I have hundreds of lines of data like the bellow:
image of the csv file

Value   Date    Time
919     4/15/2016   19:41:02
551     4/15/2016   19:46:51
717     4/15/2016   19:49:48
2679    4/15/2016   19:52:49
2890    4/15/2016   19:55:43
2897    4/15/2016   19:58:38
1790    4/15/2016   21:39:14
2953    4/15/2016   21:42:10
2516    4/15/2016   21:45:04
2530    4/15/2016   21:47:58
2951    4/15/2016   21:51:02
2954    4/15/2016   21:53:56
2537    4/15/2016   21:56:52
2523    4/15/2016   21:59:45
2536    4/15/2016   22:02:49
2727    4/15/2016   22:05:43

I use the bellow code for this purpose.

csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

text_list = []

with open(csv_file, "r") as my_input_file:
    for line in my_input_file:
        line = line.split(",", 2)
        text_list.append(" ".join(line))

with open(txt_file, "w") as my_output_file:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')

My first problem is that when the name of the input file is (for example) "DFW002_0330PM_Thursday_November_16_2017", I get the bellow error:

Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 1, in <module>
    csv_file = input('Enter the name of your input file: ')
  File "<string>", line 1, in <module>
NameError: name 'DFW000_0330PM_Thursday_November_16_2017' is not defined

But, when I change the name of the code to (for example) "11", the code defines the file and goes to the next steps, but again it returns the bellow error:

Traceback (most recent call last):
  File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 6, in <module>
    with open(csv_file, "r") as my_input_file:
TypeError: coercing to Unicode: need string or buffer, int found

Would you please help me handle these problems?

Body:
Using csv it's very easy to iterate over the csv lines:

import csv
csv_file = raw_input('Enter the name of your input file: ')
txt_file = raw_input('Enter the name of your output file: ')
with open(txt_file, "w") as my_output_file:
    with open(csv_file, "r") as my_input_file:
        [ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
    my_output_file.close()


问:
ReadProcessMemory to find Strings
I have a program designed to scan strings from a process. It is designed to output all of the readable strings within the process, at least 4 bytes long. (I am actually scanning Minecraft's java process). For some reason, the default game will SOMETIMES complete its scan, once I let it sit a while. Once you add even the smallest mod, the scan will hang. Is there any way I can fix this?

Here are the methods I am using for the scan.

```<code>    Private Function FindStrings(input() As Byte, minLength As Integer) As List(Of String)

            Dim arr() As String = System.Text.Encoding.Default.GetString(input).Split({Chr(0) & Chr(0) & Chr(0)}, StringSplitOptions.RemoveEmptyEntries)
                Dim output As New List(Of String)
                Dim tmp As String = ""
                Dim tmp1 As String = ""

            For Each item As String In arr
                    tmp = item.Replace(Chr(0), "")

                    For Each c As Char In tmp.ToCharArray

                        If isReadable(Asc(c)) = True Then
                            tmp1 &= c
                        Else
                            If tmp1.Length >= minLength Then output.Add(tmp1)
                            tmp1 = ""
                        End If

                    Next

                    If tmp1.Length >= minLength Then output.Add(tmp1)
                    tmp1 = ""

                Next

                Return output
        End Function

    Private Function isReadable(input As Integer) As Boolean
            Dim whitelist() As String = {"196,214,220,223,228,246,252"}

            If Array.IndexOf(whitelist, input) > -1 Then Return True

            If input < 32 Then Return False
            If input > 126 Then Return False

            Return True
        End Function

Private Sub BGW_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGW.DoWork

        Dim hProcess As IntPtr
        Dim lpMem As UInt32, ret As UInt32, lLenMBI As UInt32
        Dim si As SYSTEM_INFO
        Dim mbi As MEMORY_BASIC_INFORMATION
        Dim Prozess As Process = Process.GetProcessById(D.ID)

        'Open process with required access
        hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, Prozess.Id)

        If hProcess = 0 Then
            MsgBox("Can't open process!")
            Exit Sub
        End If

        'Determine applications memory addresses range
        'Call GetNativeSystemInfo(si)
        Call GetSystemInfo(si)
        lpMem = 0 'si.lpMinimumApplicationAddress
        lLenMBI = Marshal.SizeOf(mbi)

        'Try
        'Scan memory
        Do While lpMem < si.lpMaximumApplicationAddress

            BGW.ReportProgress(1)
            If BGW.CancellationPending = True Then Exit Sub

            ret = VirtualQueryEx(hProcess, lpMem, mbi, lLenMBI)

            If ret = lLenMBI Then

                If mbi.lType = &H20000 AndAlso mbi.State = &H1000 AndAlso mbi.RegionSize > 0 Then

                    Dim sBuffer As Byte() = New Byte(mbi.RegionSize - 1) {}
                    ReadProcessMemory(hProcess, mbi.BaseAddress, sBuffer, mbi.RegionSize, 0)

                    strings.AddRange(FindStrings(sBuffer, 4))
                End If

            Else
                Exit Do
            End If

            'Increase base address for next searching cicle. Last address may overhead max Long value (Windows use 2GB memory, which is near max long value), so add Error checking
            lpMem = mbi.BaseAddress + mbi.RegionSize

        Loop

        'Catch ex As Exception
        'System.Console.WriteLine("ERROR: " + ex.Message)
        'End Try

        CloseHandle(hProcess)

        BGW.ReportProgress(2, strings)

        '7ffe1000
    End Sub

    Private Sub BGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGW.RunWorkerCompleted

        lblStatus.Text = "Complete"
        Progress.Value = D.Pages
        System.Threading.Thread.Sleep(150)
        Dim thread As New Thread(
  Sub()
      strings = strings.Distinct.ToList
      lblStatus.Text = "Collecting Results..."

      For Each item As String In strings
          System.Console.WriteLine(item)
          Exit For
      Next

      System.Console.WriteLine("DONE")
      strings = Nothing

      System.GC.Collect()
      System.GC.WaitForPendingFinalizers()

      Application.Exit()
  End Sub)
        thread.Start()

    End Sub

    Public Sub EnumeratePages()
        Dim hProcess As IntPtr
        Dim lpMem As UInt32, ret As UInt32, lLenMBI As UInt32
        Dim si As SYSTEM_INFO
        Dim mbi As MEMORY_BASIC_INFORMATION
        Dim MBIitems() As String

        Dim Prozess As Process = Process.GetProcessById(D.ID)
        LV.Items.Clear()
        LV.BeginUpdate()
        'Open process with required access
        hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, Prozess.Id)

        If hProcess = 0 Then
            MsgBox("Can't open process!")
            Exit Sub
        End If

        'Determine applications memory addresses range
        'Call GetNativeSystemInfo(si)
        Call GetSystemInfo(si)
        lpMem = 0 'si.lpMinimumApplicationAddress
        lLenMBI = Marshal.SizeOf(mbi)

        'Label1.Text = "MinimumApplicationAddress: " & MakeNiceSize(si.lpMinimumApplicationAddress) & vbNewLine & _
        '                        "MaximumApplicationAddress: " & MakeNiceSize(si.lpMaximumApplicationAddress) & " / " & MakeNiceSize(UInteger.MaxValue)

        Try

            'Scan memory
            Do While lpMem < si.lpMaximumApplicationAddress

                ret = VirtualQueryEx(hProcess, lpMem, mbi, lLenMBI)

                If ret = lLenMBI Then

                    With mbi
                        MBIitems = New String() { .AllocationBase.ToString("X").ToLower, Protection2String(.AllocationProtect), MakeNiceSize(.RegionSize), State2String(.State), Protection2String(.Protect), Type2String(.lType)}
                        LV.Items.Add(.BaseAddress.ToString("X").ToLower).SubItems.AddRange(MBIitems)
                    End With

                Else
                    Exit Do
                End If

                'Increase base address for next searching cicle. Last address may overhead max Long value (Windows use 2GB memory, which is near max long value), so add Error checking
                lpMem = mbi.BaseAddress + mbi.RegionSize

            Loop

        Catch ex As Exception
            System.Console.WriteLine(ex.Message)

        End Try
        CloseHandle(hProcess)

        LV.EndUpdate()

        D.Pages = LV.Items.Count - 1
        Progress.Value = 0
        Progress.Maximum = D.Pages

        BGW.RunWorkerAsync()
        System.Console.WriteLine("Done enumerating!")
        Me.Text = D.Name & ".exe - " & D.ID
        '7ffe1000
    End Sub
</code>```

答: Solved! I have discovered the issue was caused by my compiler being set to x86 when it needed to be set to x64. No longer hangs!</p>

Title: ReadProcessMemory to find Strings

Body:
I have a program designed to scan strings from a process. It is designed to output all of the readable strings within the process, at least 4 bytes long. (I am actually scanning Minecraft's java process). For some reason, the default game will SOMETIMES complete its scan, once I let it sit a while. Once you add even the smallest mod, the scan will hang. Is there any way I can fix this?

Here are the methods I am using for the scan.

    Private Function FindStrings(input() As Byte, minLength As Integer) As List(Of String)

            Dim arr() As String = System.Text.Encoding.Default.GetString(input).Split({Chr(0) & Chr(0) & Chr(0)}, StringSplitOptions.RemoveEmptyEntries)
                Dim output As New List(Of String)
                Dim tmp As String = ""
                Dim tmp1 As String = ""

            For Each item As String In arr
                    tmp = item.Replace(Chr(0), "")

                    For Each c As Char In tmp.ToCharArray

                        If isReadable(Asc(c)) = True Then
                            tmp1 &= c
                        Else
                            If tmp1.Length >= minLength Then output.Add(tmp1)
                            tmp1 = ""
                        End If

                    Next

                    If tmp1.Length >= minLength Then output.Add(tmp1)
                    tmp1 = ""

                Next

                Return output
        End Function

    Private Function isReadable(input As Integer) As Boolean
            Dim whitelist() As String = {"196,214,220,223,228,246,252"}

            If Array.IndexOf(whitelist, input) > -1 Then Return True

            If input < 32 Then Return False
            If input > 126 Then Return False

            Return True
        End Function

Private Sub BGW_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGW.DoWork

        Dim hProcess As IntPtr
        Dim lpMem As UInt32, ret As UInt32, lLenMBI As UInt32
        Dim si As SYSTEM_INFO
        Dim mbi As MEMORY_BASIC_INFORMATION
        Dim Prozess As Process = Process.GetProcessById(D.ID)

        'Open process with required access
        hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, Prozess.Id)

        If hProcess = 0 Then
            MsgBox("Can't open process!")
            Exit Sub
        End If

        'Determine applications memory addresses range
        'Call GetNativeSystemInfo(si)
        Call GetSystemInfo(si)
        lpMem = 0 'si.lpMinimumApplicationAddress
        lLenMBI = Marshal.SizeOf(mbi)

        'Try
        'Scan memory
        Do While lpMem < si.lpMaximumApplicationAddress

            BGW.ReportProgress(1)
            If BGW.CancellationPending = True Then Exit Sub

            ret = VirtualQueryEx(hProcess, lpMem, mbi, lLenMBI)

            If ret = lLenMBI Then

                If mbi.lType = &H20000 AndAlso mbi.State = &H1000 AndAlso mbi.RegionSize > 0 Then

                    Dim sBuffer As Byte() = New Byte(mbi.RegionSize - 1) {}
                    ReadProcessMemory(hProcess, mbi.BaseAddress, sBuffer, mbi.RegionSize, 0)

                    strings.AddRange(FindStrings(sBuffer, 4))
                End If

            Else
                Exit Do
            End If

            'Increase base address for next searching cicle. Last address may overhead max Long value (Windows use 2GB memory, which is near max long value), so add Error checking
            lpMem = mbi.BaseAddress + mbi.RegionSize

        Loop

        'Catch ex As Exception
        'System.Console.WriteLine("ERROR: " + ex.Message)
        'End Try

        CloseHandle(hProcess)

        BGW.ReportProgress(2, strings)

        '7ffe1000
    End Sub

    Private Sub BGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGW.RunWorkerCompleted

        lblStatus.Text = "Complete"
        Progress.Value = D.Pages
        System.Threading.Thread.Sleep(150)
        Dim thread As New Thread(
  Sub()
      strings = strings.Distinct.ToList
      lblStatus.Text = "Collecting Results..."

      For Each item As String In strings
          System.Console.WriteLine(item)
          Exit For
      Next

      System.Console.WriteLine("DONE")
      strings = Nothing

      System.GC.Collect()
      System.GC.WaitForPendingFinalizers()

      Application.Exit()
  End Sub)
        thread.Start()

    End Sub

    Public Sub EnumeratePages()
        Dim hProcess As IntPtr
        Dim lpMem As UInt32, ret As UInt32, lLenMBI As UInt32
        Dim si As SYSTEM_INFO
        Dim mbi As MEMORY_BASIC_INFORMATION
        Dim MBIitems() As String

        Dim Prozess As Process = Process.GetProcessById(D.ID)
        LV.Items.Clear()
        LV.BeginUpdate()
        'Open process with required access
        hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, Prozess.Id)

        If hProcess = 0 Then
            MsgBox("Can't open process!")
            Exit Sub
        End If

        'Determine applications memory addresses range
        'Call GetNativeSystemInfo(si)
        Call GetSystemInfo(si)
        lpMem = 0 'si.lpMinimumApplicationAddress
        lLenMBI = Marshal.SizeOf(mbi)

        'Label1.Text = "MinimumApplicationAddress: " & MakeNiceSize(si.lpMinimumApplicationAddress) & vbNewLine & _
        '                        "MaximumApplicationAddress: " & MakeNiceSize(si.lpMaximumApplicationAddress) & " / " & MakeNiceSize(UInteger.MaxValue)

        Try

            'Scan memory
            Do While lpMem < si.lpMaximumApplicationAddress

                ret = VirtualQueryEx(hProcess, lpMem, mbi, lLenMBI)

                If ret = lLenMBI Then

                    With mbi
                        MBIitems = New String() { .AllocationBase.ToString("X").ToLower, Protection2String(.AllocationProtect), MakeNiceSize(.RegionSize), State2String(.State), Protection2String(.Protect), Type2String(.lType)}
                        LV.Items.Add(.BaseAddress.ToString("X").ToLower).SubItems.AddRange(MBIitems)
                    End With

                Else
                    Exit Do
                End If

                'Increase base address for next searching cicle. Last address may overhead max Long value (Windows use 2GB memory, which is near max long value), so add Error checking
                lpMem = mbi.BaseAddress + mbi.RegionSize

            Loop

        Catch ex As Exception
            System.Console.WriteLine(ex.Message)

        End Try
        CloseHandle(hProcess)

        LV.EndUpdate()

        D.Pages = LV.Items.Count - 1
        Progress.Value = 0
        Progress.Maximum = D.Pages

        BGW.RunWorkerAsync()
        System.Console.WriteLine("Done enumerating!")
        Me.Text = D.Name & ".exe - " & D.ID
        '7ffe1000
    End Sub


问:
Non-negative integers
Say i have a function prototype as follows:

```<code>func :: [Int] -> [Int]
</code>```

How is it possible to enforce only a non-negative list of integers as input arguments? I would have to change the param type from [Int] to what.. ? At this fair moment it works with func [-1,-2], i only want it to work with [1,2] i.e. with the interpreter spewing the error message.

答:
In the base package with version >= 4.8.0.0, which is included in GHC 7.10.1 and above, there is now a type Natural which does what you want - you can just change your code to:

```<code>import Numeric.Natural (Natural)

func :: [Natural] -> [Int]
</code>```

It is, however, closer to Integer than to Int, because like Integer and unlike Int, it has no maximum value.

Because Natural, like Integer, is an instance of Num and Integral, all the same arithmetic operations and conversion functions are available as you get with Integer. Attempts to calculate a negative Natural will throw an Underflow at runtime, which is an ArithException. Also, conveniently, you can create a Natural using just an integer literal, without a conversion:

```<code>GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m +Numeric.Natural
Prelude Numeric.Natural> 2 :: Natural
2
</code>```

However, if you would prefer to stay in the domain of fixed-size integers, there is a solution for that, too - and it has been around for far longer - Word from the module Data.Word (which also contains e.g. Word8 for 8-bit non-negative integers). You would use Word in the same way as Natural. However, be warned - the Word types will silently underflow, without throwing an exception:

```<code>GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m +Data.Word
Prelude Data.Word> 2 :: Word
2
Prelude Data.Word> it - 4
18446744073709551614
</code>```

Title: Non-negative integers

Body:
Say i have a function prototype as follows:

func :: [Int] -> [Int]

How is it possible to enforce only a non-negative list of integers as input arguments? I would have to change the param type from [Int] to what.. ? At this fair moment it works with func [-1,-2], i only want it to work with [1,2] i.e. with the interpreter spewing the error message.

Body:
In the base package with version >= 4.8.0.0, which is included in GHC 7.10.1 and above, there is now a type Natural which does what you want - you can just change your code to:

import Numeric.Natural (Natural)

func :: [Natural] -> [Int]

It is, however, closer to Integer than to Int, because like Integer and unlike Int, it has no maximum value.

Because Natural, like Integer, is an instance of Num and Integral, all the same arithmetic operations and conversion functions are available as you get with Integer. Attempts to calculate a negative Natural will throw an Underflow at runtime, which is an ArithException. Also, conveniently, you can create a Natural using just an integer literal, without a conversion:

GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m +Numeric.Natural
Prelude Numeric.Natural> 2 :: Natural
2

However, if you would prefer to stay in the domain of fixed-size integers, there is a solution for that, too - and it has been around for far longer - Word from the module Data.Word (which also contains e.g. Word8 for 8-bit non-negative integers). You would use Word in the same way as Natural. However, be warned - the Word types will silently underflow, without throwing an exception:

GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m +Data.Word
Prelude Data.Word> 2 :: Word
2
Prelude Data.Word> it - 4
18446744073709551614