问:
itunes connect replace binary when status is "waiting for review"
We found bug after we submit the binary for approval in itunes connect and we upload a new build but we can not figure out how to replace the new build in itunes connect. the status of the build active.

Any of you knows how can replace the binary is for a approval with the new version of the binary?

I found this : How to replace app in itunes connect, while waiting in review?

But it seems to make reference to the old version of itunes connect.

答:
You can't remove and replace the build anymore until you remove the app from review.

You go to your app detail page, under App Store, in app store connect, then at the top of the page there's a blue notification that indicates and confirms that in order to submit a new-build you must remove the version from review and gives you a link to click to do that.

Once you do, you can scroll down to builds and click the minus button on your build to remove it and then add a new one.


来源: stackexchange

问:
Laravel Relationship between two tables error after submitting the first post
Post Model:

```<code>class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class, 'id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class, 'id');
    }

    public function size()
    {
        return $this->hasOne(Size::class, 'id');
    }
}
</code>```

index.blade.php:

```<code>@foreach ($posts as $post)
    <td><img src="{{ url('storage/'. $post->image) }}" width="100" height="50"></td>
    <td>{{ $post->name }}</td>
    <td>{{ $post->size->name }}</td>
    <td>{{ $post->category->name }}</td>
    <td>{{ $post->gender->name }}</td>
    <td>{{ $post->price }} $</td>
    <td></td>
    </tbody>
@endforeach
</code>```

Posts table:

```<code>public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('genders_id');
        $table->string('sizes_id');
        $table->string('categories_id');
        $table->integer('price');
        $table->string('image');
        $table->timestamps();
    });
}
</code>```

PostsController:

```<code>public function store(PostValidation $request)
{
    $image = $request->file('image')->store('image');

    Post::create([
        'name' => $request->name,
        'image' => $image,
        'genders_id' => $request->gender,
        'categories_id' => $request->categories,
        'sizes_id' => $request->size,
        'price' => $request->price
    ]);

    return redirect(route('post.index'));
}
</code>```

The issue is {{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }} works after my first post, whenever I add a second post it gives me the following error:

Trying to get property 'name' of non-object (View:
  C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php)
  {{ $post->size->name }}

答:
Run php artisan tinker find your Post via $post = Post::find({{id}}) and then try and access its size property via $size = $post->size.

You should receive null, i.e. your Post/Size models relationship was never made.

Once that is confirmed, run $post->size_id to check whether this was even set in the request, if not you are not passing the size property in your request properly.

Otherwise, I would suggest you check the foreign keys in your relationships match your table names (especially in size), you may have overwritten the table name in the Model using the $table property in the Size class.

ContentLicense: CC BY-SA 4.0

Body:
Post Model:

class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class, 'id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class, 'id');
    }

    public function size()
    {
        return $this->hasOne(Size::class, 'id');
    }
}

index.blade.php:

@foreach ($posts as $post)
    image) }}" width="100" height="50">
    {{ $post->name }}
    {{ $post->size->name }}
    {{ $post->category->name }}
    {{ $post->gender->name }}
    {{ $post->price }} $

@endforeach

Posts table:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('genders_id');
        $table->string('sizes_id');
        $table->string('categories_id');
        $table->integer('price');
        $table->string('image');
        $table->timestamps();
    });
}

PostsController:

public function store(PostValidation $request)
{
    $image = $request->file('image')->store('image');

    Post::create([
        'name' => $request->name,
        'image' => $image,
        'genders_id' => $request->gender,
        'categories_id' => $request->categories,
        'sizes_id' => $request->size,
        'price' => $request->price
    ]);

    return redirect(route('post.index'));
}

The issue is {{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }} works after my first post, whenever I add a second post it gives me the following error:

Trying to get property 'name' of non-object (View:
  C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php)
  {{ $post->size->name }}


问:
log rotation for nginx on windows
I've found plenty of references on the web for rotating the nginx logs under linux.. just send the USR1 signal to the process.  But... unix like signals don't exist on windows and I haven't been able to find any information on this.  How can I accomplish the same thing with nginx on windows??</p>

答:
```<code>@echo off
SET DATE_FRM=%date%

REM set path of Nginx root folder.
SET NGINX_PATH="E:\nginx-1.14.2"

REM create old_logs folder if not exists , we will move old logs in this folder.
if not exist "%NGINX_PATH%\old_logs\NUL" mkdir "%NGINX_PATH%\old_logs"

REM move error.log in old_logs from logs folder and rename it
move %NGINX_PATH%\logs\access.log %NGINX_PATH%\old_logs\access_%DATE_FRM%.log
move %NGINX_PATH%\logs\error.log %NGINX_PATH%\old_logs\error_%DATE_FRM%.log

REM reopn nginx logs, this will create new error.log for nginx.
call %NGINX_PATH%\nginx -p %NGINX_PATH% -s reopen

REM compress error%DATE_FRM%.log, this will create error_%DATE_FRM%.log.zip file.
powershell Compress-Archive -Path %NGINX_PATH%\old_logs\access_%DATE_FRM%.log -DestinationPath %NGINX_PATH%\old_logs\access_%DATE_FRM%.log.zip -force
powershell Compress-Archive -Path %NGINX_PATH%\old_logs\error_%DATE_FRM%.log -DestinationPath %NGINX_PATH%\old_logs\error_%DATE_FRM%.log.zip -force

REM delete error%DATE_FRM%.log from old_logs.
del %NGINX_PATH%\old_logs\access_%DATE_FRM%.log
del %NGINX_PATH%\old_logs\error_%DATE_FRM%.log
</code>```

ContentLicense: CC BY-SA 2.5

Title: log rotation for nginx on windows


问:
How to drop multiple columns (using column names) from a dataframe using pandas?
I have a data frame df with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.

I cannot use:

```<code>df.drop('column name', axis=1)
</code>```

directly because there are so many columns to drop and I cannot really type each of its column names as in the above cases.

I am interested in knowing how to select the columns from particular column name column50 to another column name column90 and column120 to column170 rather than with the int

答:
You can create a list of columns like this:</p>

```<code>idx = list(range(50,90)) + list(range(120,170))

df = df.drop(df.columns[idx], axis=1)
</code>```

Body:
I have a data frame df with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.

I cannot use:

df.drop('column name', axis=1)

directly because there are so many columns to drop and I cannot really type each of its column names as in the above cases.

I am interested in knowing how to select the columns from particular column name column50 to another column name column90 and column120 to column170 rather than with the int

Body:
You can create a list of columns like this:

idx = list(range(50,90)) + list(range(120,170))

df = df.drop(df.columns[idx], axis=1)


问:
Filter out FASTA files by specified sequence length in bash
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG
</code>```

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
</code>```

答:
Could you please try following, tested and written with shown samples.

```<code>awk '
/^>/{
  if(sign_val && strLen>=30){
    print sign_val ORS line
  }
  strLen=line=""
  sign_val=$0
  next
}
{
  strLen+=length($0)
  line=(line?line ORS:"")$0
}
END{
  if(sign_val && strLen>=30){
    print sign_val ORS line
  }
}
'  Input_file
</code>```

Explanation: Adding detailed explanation for above.

```<code>awk '                                ##Starting awk program from here.
/^>/{                                ##Checking condition if line starts from > then do following.
  if(sign_val && strLen>=30){        ##Checking if sign_val is SET and steLen is SET then do following.
    print sign_val ORS line          ##Printing sign_val ORS and line here.
  }
  strLen=line=""                     ##Nullify variables steLen and line here.
  sign_val=$0                        ##Setting sign_val to current line here.
  next                               ##next will skip all further statements from here.
}
{
  strLen+=length($0)                 ##Checking length of line and keep adding it here.
  line=(line?line ORS:"")$0          ##Creating line variable and keep appending it to it with new line.
}
END{                                 ##Starting END block of this program from here.
  if(sign_val && strLen>=30){        ##Checking if sign_val is SET and steLen is SET then do following.
    print sign_val ORS line          ##Printing sign_val ORS and line here.
  }
}
' Input_file                         ##mentioning Input_file name here.
</code>```

Body:
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA

Body:
Could you please try following, tested and written with shown samples.

awk '
/^>/{
  if(sign_val && strLen>=30){
    print sign_val ORS line
  }
  strLen=line=""
  sign_val=$0
  next
}
{
  strLen+=length($0)
  line=(line?line ORS:"")$0
}
END{
  if(sign_val && strLen>=30){
    print sign_val ORS line
  }
}
'  Input_file

Explanation: Adding detailed explanation for above.

awk '                                ##Starting awk program from here.
/^>/{                                ##Checking condition if line starts from > then do following.
  if(sign_val && strLen>=30){        ##Checking if sign_val is SET and steLen is SET then do following.
    print sign_val ORS line          ##Printing sign_val ORS and line here.
  }
  strLen=line=""                     ##Nullify variables steLen and line here.
  sign_val=$0                        ##Setting sign_val to current line here.
  next                               ##next will skip all further statements from here.
}
{
  strLen+=length($0)                 ##Checking length of line and keep adding it here.
  line=(line?line ORS:"")$0          ##Creating line variable and keep appending it to it with new line.
}
END{                                 ##Starting END block of this program from here.
  if(sign_val && strLen>=30){        ##Checking if sign_val is SET and steLen is SET then do following.
    print sign_val ORS line          ##Printing sign_val ORS and line here.
  }
}
' Input_file                         ##mentioning Input_file name here.


问:
Roam array of arrays by position in Python
I have this array of arrays:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

```<code>AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
</code>```

I've tried with

```<code>for i in A:
   for j in i:
      #code
</code>```

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

答:
You should to use the zip function in the following way:</p>

```<code>AUX = [list(x) for x in zip(*A)]
</code>```

Body:
I have this array of arrays:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I've tried with

for i in A:
   for j in i:
      #code

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

Body:
You should to use the zip function in the following way:

AUX = [list(x) for x in zip(*A)]


问:
How do I make my A star search algorithm more efficient?
I have a grid in matplotlib (20*20 or 40*40 based on user's choice) that contains data divided based on LatLong location. Each cell in that grid represents a 0.002 or 0.001 area (ex: [-70.55, 43.242] to [-70.548, 43.244]). The grid is coloured basesd on threshold value, say anything above 30 is green and anything below is red.

I implemented the A start algorithm to go from one location (cell) to another on that graph while avoiding all green cells. The cost of traveling on a border of a green and red cell is 1.3 while the diagonal cost is 1.5, and traveling between two red cells is 1.

I'm using the diagonal distance heuristic, and for each cell I'm getting all possible neighbours and setting their G value based on the threshold.

Now I'm able to get a correct path most of the time, and for cells that are nearby, it runs at sub 1 sec. but when I go further it takes 14-18 seconds.

I don't understand what wrong I'm doing here? I've been trying to figure out a way to improve it but failed.

Here's a fragment of the algorithm. I would like to note that determining the accessible neighbours and setting the G value might not be issue here because each function call runs at around 0.02 - 0.03 seconds.

Any advice is appreciated! Thanks

```<code>def a_star(self, start, end):
    startNode = Node(None, start)
    endNode = Node(None, end)
    openList = []
    closedList = []
    openList.append(startNode)

    while len(openList) > 0:

        current = openList[0]
        if current.location == endNode.location:
            path = []
            node = current
            while node is not None:
                path.append(node)
                node = node.parent
            return path[::-1]

        openList.pop(0)
        closedList.append(current)

       # This takes around 0.02 0.03 seconds
        neighbours = self.get_neighbors(current)

        for neighbour in neighbours:
            append = True
            for node in closedList:
                if neighbour.location == node.location:
                    append = False
                    break
            for openNode in openList:
                if neighbour.location == openNode.location:
                    if neighbour.g < openNode.g:
                        append = False
                        openNode.g = neighbour.g
                        break
            if append:

                neighbour.h = round(self.heuristic(neighbour.location, endNode.location), 3)
                neighbour.f = round(neighbour.g + neighbour.h, 3)

                bisect.insort_left(openList, neighbour)
    return False
</code>```

Edit: Add Node fragment

```<code> class Node:
    def __init__(self, parent, location):
        self.parent = parent
        self.location = location
        self.g = 0
        self.h = 0
        self.f = 0
</code>```

Edit 2: Add Image

Circle is start location, star is destination. Yellow cells are not accessible, so no diagonal path on yellow cells, and cannot travel between two yellow cells.

答:
This part is very inefficient. For every neighbour you walk over two relatively large lists, this brings the overall complexity high very fast once the lists start to grow:

```<code>for node in closedList:
    if neighbour.location == node.location:
        append = False
        break
for openNode in openList:
    if neighbour.location == openNode.location:
</code>```

Basically, your algorithm should not be dependent on any lists. You have your cells, you pop one from the list, you get 8 neighbours, you process them by comparing to the cells you have, then some of those are appended to the list. No need to loop over any lists.

Body:
I have a grid in matplotlib (20*20 or 40*40 based on user's choice) that contains data divided based on LatLong location. Each cell in that grid represents a 0.002 or 0.001 area (ex: [-70.55, 43.242] to [-70.548, 43.244]). The grid is coloured basesd on threshold value, say anything above 30 is green and anything below is red.

I implemented the A start algorithm to go from one location (cell) to another on that graph while avoiding all green cells. The cost of traveling on a border of a green and red cell is 1.3 while the diagonal cost is 1.5, and traveling between two red cells is 1.

I'm using the diagonal distance heuristic, and for each cell I'm getting all possible neighbours and setting their G value based on the threshold.

Now I'm able to get a correct path most of the time, and for cells that are nearby, it runs at sub 1 sec. but when I go further it takes 14-18 seconds.

I don't understand what wrong I'm doing here? I've been trying to figure out a way to improve it but failed.

Here's a fragment of the algorithm. I would like to note that determining the accessible neighbours and setting the G value might not be issue here because each function call runs at around 0.02 - 0.03 seconds.

Any advice is appreciated! Thanks

def a_star(self, start, end):
    startNode = Node(None, start)
    endNode = Node(None, end)
    openList = []
    closedList = []
    openList.append(startNode)

    while len(openList) > 0:

        current = openList[0]
        if current.location == endNode.location:
            path = []
            node = current
            while node is not None:
                path.append(node)
                node = node.parent
            return path[::-1]

        openList.pop(0)
        closedList.append(current)

       # This takes around 0.02 0.03 seconds
        neighbours = self.get_neighbors(current)

        for neighbour in neighbours:
            append = True
            for node in closedList:
                if neighbour.location == node.location:
                    append = False
                    break
            for openNode in openList:
                if neighbour.location == openNode.location:
                    if neighbour.g < openNode.g:
                        append = False
                        openNode.g = neighbour.g
                        break
            if append:

                neighbour.h = round(self.heuristic(neighbour.location, endNode.location), 3)
                neighbour.f = round(neighbour.g + neighbour.h, 3)

                bisect.insort_left(openList, neighbour)
    return False

Edit: Add Node fragment

 class Node:
    def __init__(self, parent, location):
        self.parent = parent
        self.location = location
        self.g = 0
        self.h = 0
        self.f = 0

Edit 2: Add Image

Circle is start location, star is destination. Yellow cells are not accessible, so no diagonal path on yellow cells, and cannot travel between two yellow cells.

Body:
This part is very inefficient. For every neighbour you walk over two relatively large lists, this brings the overall complexity high very fast once the lists start to grow:

for node in closedList:
    if neighbour.location == node.location:
        append = False
        break
for openNode in openList:
    if neighbour.location == openNode.location:

Basically, your algorithm should not be dependent on any lists. You have your cells, you pop one from the list, you get 8 neighbours, you process them by comparing to the cells you have, then some of those are appended to the list. No need to loop over any lists.


问:
How to uninstall mongodb from Windows
I saw a tutorial that said to run this:

```<code>C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.conf --remove
</code>```

but that command does not work since there is no mongod.conf file in the mongodb folder in my Windows. Besides, I don't want to only stop the service, but to remove everythin, including files, services, etc. Is that possible?

I am using Windows 8.1.

答:
Run the mongo-db installation file that ends with .msi.

You'll see the remove option there, click on it.

Then you could delete the mongo-db files that are in your computer.

Title: How to uninstall mongodb from Windows

Body:
I saw a tutorial that said to run this:

C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.conf --remove

but that command does not work since there is no mongod.conf file in the mongodb folder in my Windows. Besides, I don't want to only stop the service, but to remove everythin, including files, services, etc. Is that possible?

I am using Windows 8.1.


问:
python binary tree recursion
```<code>class Node:
    def __init__(self,value):
        self.value = value
        self.right = None
        self.left = None

class Tree:
    def __init__(self,root):
        self.root = Node(root)

    def print_tree(self):
        return self.preorder_print(self.root,"")

    def preorder_print(self,start,traversal):
        if start:
            print('step 1')
            traversal = self.preorder_print(start.left, traversal)
            print('step 2')
            traversal +=(str(start.value)+"-")
            print('step 3')
            traversal = self.preorder_print(start.right, traversal)
        return traversal

"""
             F
        B         G
    A      D        I
        C    E   H

In- order print: A->B->C->D->E->F->G->H->I
"""

tree = Tree("F")
tree.root.left = Node("B")
tree.root.right = Node("G")
tree.root.right.right = Node("I")
tree.root.right.right.left = Node("H")

tree.root.left.left = Node("A")
tree.root.left.right = Node("D")
tree.root.left.right.left = Node("C")
tree.root.left.right.right = Node("E")
print(tree.print_tree())
</code>```

I understand the 'step 1' recursion goes to the deep left, Node("A"), but when after reaching A,

how does the func break out of that recursion? Does it move on to the next line, "step 2"?

what's the return value of that traversal in 'step 1'?

答:
Yes, there are lots of programmers who have trouble visualising recursion.

Yes, when the recursion reaches Node A the recursion does help.

The function breaks out of the recursion (the base case) at the if start: statement.

by the way, your code, as posted, outputs this: A-B-C-D-E-F-G-H-I-

An example of the base case for your data is this: When the code enters preorder_print() with start referring to Node("A"), then if start: passes and the next statement is traversal = self.preorder_print(start.left, traversal) which passes start.left to the next level down.

Now because Node("A") has both left and right set to the default None, the above call is a nop and just returns traversal, so the next statement is the traversal += str(start.value) + "-" where start.value is "A".

Again the next statement traversal = self.preorder_print(start.right, traversal) is a nop and then return traversal exits this level and goes up one level.

Now we find ourselves back in self.preorder_print() having just executed traversal = self.preorder_print(start.left, traversal) where start refers to Node("B") and start.left refers to Node("A").

Title: python binary tree recursion

Body:
class Node:
    def __init__(self,value):
        self.value = value
        self.right = None
        self.left = None

class Tree:
    def __init__(self,root):
        self.root = Node(root)

    def print_tree(self):
        return self.preorder_print(self.root,"")

    def preorder_print(self,start,traversal):
        if start:
            print('step 1')
            traversal = self.preorder_print(start.left, traversal)
            print('step 2')
            traversal +=(str(start.value)+"-")
            print('step 3')
            traversal = self.preorder_print(start.right, traversal)
        return traversal

"""
             F
        B         G
    A      D        I
        C    E   H

In- order print: A->B->C->D->E->F->G->H->I
"""

tree = Tree("F")
tree.root.left = Node("B")
tree.root.right = Node("G")
tree.root.right.right = Node("I")
tree.root.right.right.left = Node("H")

tree.root.left.left = Node("A")
tree.root.left.right = Node("D")
tree.root.left.right.left = Node("C")
tree.root.left.right.right = Node("E")
print(tree.print_tree())

I understand the 'step 1' recursion goes to the deep left, Node("A"), but when after reaching A,

how does the func break out of that recursion? Does it move on to the next line, "step 2"?

what's the return value of that traversal in 'step 1'?


答:
You can use np.r_ to do this:

```<code>import numpy
idx = np.r_[50:90, 120:170]

df.drop(df.columns[idx], axis=1, inplace=True)
</code>```

From the np.r_ docs:

Translates slice objects to concatenation along the first axis.

In your case, it concatenates non-contiguous slices of arrays which you can use in df.drop command.

Title: How to drop multiple columns (using column names) from a dataframe using pandas?

Body:
You can use np.r_ to do this:

import numpy
idx = np.r_[50:90, 120:170]

df.drop(df.columns[idx], axis=1, inplace=True)

From the np.r_ docs:

Translates slice objects to concatenation along the first axis.

In your case, it concatenates non-contiguous slices of arrays which you can use in df.drop command.


问:
C++ - How to use a stream to parse a file?
I have a file and I need to loop through it assigning an int foo, string type, 64/128 bit long. How would I use a stream to parse these lines into the following variables - I want to stick with the stream syntax ( ifs >> foo >> type ) but in this case type would end up being the rest of the line after the 0/52 ... and at that point I'd just get a char* and use strtoull and such so why use the stream in the first place... I'm hoping for readable code without horrid performance over char strings / strtok / strtoull </p>

```<code>//input file:
0ULL'04001C0180000000000000000EE317BC'
52L'04001C0180000000'
//ouput:
//0 ULL 0x04001C0180000000 0x000000000EE317BC
//52 L 0x04001C0180000000

  ifstream ifs("input.data");
  int foo;
  string type;
  unsigned long long ull[2];
</code>```

答:
This is a rather trivial task for a more sophisticated parser such as boost.spirit.

To solve this using just the standard C++ streams you would need to

a) treat ' as whitespace and

b) take an extra pass over the string "04001C0180000000000000000EE317BC" which has no separators between the values.

Borrowing Jerry Coffin's sample facet code,

```<code>#include <iostream>
#include <fstream>
#include <locale>
#include <vector>
#include <sstream>
#include <iomanip>
struct tick_is_space : std::ctype<char> {
    tick_is_space() : std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask>
               rc(table_size, std::ctype_base::mask());
        rc['\n'] = std::ctype_base::space;
        rc['\''] = std::ctype_base::space;
        return &rc[0];
    }
};

int main()
{
    std::ifstream ifs("input.data");
    ifs.imbue(std::locale(std::locale(), new tick_is_space()));
    int foo;
    std::string type, ullstr;
    while( ifs >> foo >> type >> ullstr)
    {
        std::vector<unsigned long long> ull;
        while(ullstr.size() >= 16) // sizeof(unsigned long long)*2
        {
            std::istringstream is(ullstr.substr(0, 16));
            unsigned long long tmp;
            is >> std::hex >> tmp;
            ull.push_back(tmp);
            ullstr.erase(0, 16);
        }
        std::cout << std::dec << foo << " " << type << " "
                  << std::hex << std::showbase;
        for(size_t p=0; p<ull.size(); ++p)
            std::cout << std::setw(16) << std::setfill('0') << ull[p] << ' ';
        std::cout << '\n';
    }
}
</code>```

test: https://ideone.com/lRBTq

ContentLicense: CC BY-SA 3.0

Body:
I have a file and I need to loop through it assigning an int foo, string type, 64/128 bit long. How would I use a stream to parse these lines into the following variables - I want to stick with the stream syntax ( ifs >> foo >> type ) but in this case type would end up being the rest of the line after the 0/52 ... and at that point I'd just get a char* and use strtoull and such so why use the stream in the first place... I'm hoping for readable code without horrid performance over char strings / strtok / strtoull

//input file:
0ULL'04001C0180000000000000000EE317BC'
52L'04001C0180000000'
//ouput:
//0 ULL 0x04001C0180000000 0x000000000EE317BC
//52 L 0x04001C0180000000

  ifstream ifs("input.data");
  int foo;
  string type;
  unsigned long long ull[2];

Body:
This is a rather trivial task for a more sophisticated parser such as boost.spirit.

To solve this using just the standard C++ streams you would need to

a) treat ' as whitespace and

b) take an extra pass over the string "04001C0180000000000000000EE317BC" which has no separators between the values.

Borrowing Jerry Coffin's sample facet code,

#include <iostream>
#include <fstream>
#include <locale>
#include <vector>
#include <sstream>
#include <iomanip>
struct tick_is_space : std::ctype<char> {
    tick_is_space() : std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask>
               rc(table_size, std::ctype_base::mask());
        rc['\n'] = std::ctype_base::space;
        rc['\''] = std::ctype_base::space;
        return &rc[0];
    }
};

int main()
{
    std::ifstream ifs("input.data");
    ifs.imbue(std::locale(std::locale(), new tick_is_space()));
    int foo;
    std::string type, ullstr;
    while( ifs >> foo >> type >> ullstr)
    {
        std::vector<unsigned long long> ull;
        while(ullstr.size() >= 16) // sizeof(unsigned long long)*2
        {
            std::istringstream is(ullstr.substr(0, 16));
            unsigned long long tmp;
            is >> std::hex >> tmp;
            ull.push_back(tmp);
            ullstr.erase(0, 16);
        }
        std::cout << std::dec << foo << " " << type << " "
                  << std::hex << std::showbase;
        for(size_t p=0; p<ull.size(); ++p)
            std::cout << std::setw(16) << std::setfill('0') << ull[p] << ' ';
        std::cout << '\n';
    }
}

test: https://ideone.com/lRBTq


问:
PayPal PayFlow Pro Auth Failure
I've setup a test account for PayPal Payflow Pro, but I'm having authentication issues.  Unless i'm using cURL, the api returns "User authentication failed".  I am sure I'm passing the same information as I've copied and pasted from the working cURL to PostMan and .net.  Am trying to replicate an example API call from:
https://developer.paypal.com/docs/payflow/gs-ppa-hosted-pages/#make-your-first-call

I'd appreciatie any help with this.

Postman failure:

.Net failure:

答:
In case anyone wants to see exactly how I changed Postman and .net to work.  Thanks again to Preston PHX!

Text Body:
PARTNER=PayPal&VENDOR=&USER=&PWD=&TRXTYPE=S&AMT=40&CREATESECURETOKEN=Y&SECURETOKENID=

.Net Code:

```<code>private string GetSecureToken(string amount, string trxtype)
{
var secure = new SecureTokenRequest(true)
{
    PARTNER = PartnerId,
    VENDOR = VendorId,
    USER = User,
    PWD = Password,
    AMT = amount,
    TRXTYPE = trxtype
    //CREATESECURETOKEN is set by boolean in SecureTokenRequest constructor
    //SECURETOKENID is set in SecureTokenRequest constructor using new Guid to string
};

var client = new RestClient(Uri);

var request = new RestRequest(Method.POST);

var parameterDict = new Dictionary<string,string>()
{
    {nameof(secure.PARTNER), secure.PARTNER},
    {nameof(secure.VENDOR), secure.VENDOR},
    {nameof(secure.USER), secure.USER},
    {nameof(secure.PWD), secure.PWD},
    {nameof(secure.TRXTYPE), secure.TRXTYPE},
    {nameof(secure.AMT), secure.AMT},
    {nameof(secure.CREATESECURETOKEN), secure.CREATESECURETOKEN},
    {nameof(secure.SECURETOKENID), secure.SECURETOKENID},
};

var parameterList = parameterDict.Select(kvp
    => $"{kvp.Key}={kvp.Value}").ToList();

var postBody = string.Join("&", parameterList);

request.AddParameter("text", postBody, ParameterType.RequestBody);

var response = client.Execute(request);

var responseContent = response.IsSuccessful
    ? response.Content
    : $"{response.StatusCode} : {response.ErrorMessage}";

return responseContent;
}
</code>```

Title: PayPal PayFlow Pro Auth Failure

Body:
In case anyone wants to see exactly how I changed Postman and .net to work.  Thanks again to Preston PHX!

Text Body:
PARTNER=PayPal&VENDOR=&USER=&PWD=&TRXTYPE=S&AMT=40&CREATESECURETOKEN=Y&SECURETOKENID=

.Net Code:

private string GetSecureToken(string amount, string trxtype)
{
var secure = new SecureTokenRequest(true)
{
    PARTNER = PartnerId,
    VENDOR = VendorId,
    USER = User,
    PWD = Password,
    AMT = amount,
    TRXTYPE = trxtype
    //CREATESECURETOKEN is set by boolean in SecureTokenRequest constructor
    //SECURETOKENID is set in SecureTokenRequest constructor using new Guid to string
};

var client = new RestClient(Uri);

var request = new RestRequest(Method.POST);

var parameterDict = new Dictionary<string,string>()
{
    {nameof(secure.PARTNER), secure.PARTNER},
    {nameof(secure.VENDOR), secure.VENDOR},
    {nameof(secure.USER), secure.USER},
    {nameof(secure.PWD), secure.PWD},
    {nameof(secure.TRXTYPE), secure.TRXTYPE},
    {nameof(secure.AMT), secure.AMT},
    {nameof(secure.CREATESECURETOKEN), secure.CREATESECURETOKEN},
    {nameof(secure.SECURETOKENID), secure.SECURETOKENID},
};

var parameterList = parameterDict.Select(kvp
    => $"{kvp.Key}={kvp.Value}").ToList();

var postBody = string.Join("&", parameterList);

request.AddParameter("text", postBody, ParameterType.RequestBody);

var response = client.Execute(request);

var responseContent = response.IsSuccessful
    ? response.Content
    : $"{response.StatusCode} : {response.ErrorMessage}";

return responseContent;
}


问:
Set Recat LInk to Button when button click call the function & after Navigite to Another Component
I need to set Link to navigate another component & also I want to call function when same button clicked.

```<code>addValue(evt)
    {
      evt.preventDefault();
      if(this.state.value !=undefined)
      {
        alert('Your input value is: ' + this.state.value)
        localStorage.setItem('reg_no',this.state.value);
        alert(localStorage.getItem('reg_no'));

      }

    }

    render() {
        return (
            <form onSubmit={this.addValue}>
            <input type="text" onChange={this.updateInput} placeholder="Enter Hospital Registration Number"/><br/><br/>
            <Button type="submit" value="Enter" onClick={()=>this.addValue}> Enter</Button>

            </form>
          );
    }
</code>```

This is my react code. I want to set Link to Enter button. How I do it?
(suppose i want to load 'Home' component by url '/homeurl'

答:
try to use React-router redirect method

```<code>import { Redirect } from "react-router-dom";
</code>```

then use a state prop to identify that you click operation has been finished like this

```<code>state = {
    open:false;
    }
addValue(evt)
{
  evt.preventDefault();
  if(this.state.value !=undefined)
  {
    alert('Your input value is: ' + this.state.value)
    localStorage.setItem('reg_no',this.state.value);
    alert(localStorage.getItem('reg_no'));
this.setState({open:true});
  }

}

render() {
    return (
        <form onSubmit={this.addValue}>
    {this.state.open? (
    <Redirect
          to={{
            pathname: "/home"
          }}
    ):null}
        <input type="text" onChange={this.updateInput} placeholder="Enter Hospital Registration Number"/><br/><br/>
        <Button type="submit" value="Enter" onClick={()=>this.addValue}> Enter</Button>

        </form>
      );
}
</code>```

Body:
I need to set Link to navigate another component & also I want to call function when same button clicked.

addValue(evt)
    {
      evt.preventDefault();
      if(this.state.value !=undefined)
      {
        alert('Your input value is: ' + this.state.value)
        localStorage.setItem('reg_no',this.state.value);
        alert(localStorage.getItem('reg_no'));

      }

    }

    render() {
        return (
            <form onSubmit={this.addValue}>
            <input type="text" onChange={this.updateInput} placeholder="Enter Hospital Registration Number"/>

            <Button type="submit" value="Enter" onClick={()=>this.addValue}> Enter</Button>

            </form>
          );
    }

This is my react code. I want to set Link to Enter button. How I do it?
(suppose i want to load 'Home' component by url '/homeurl'

Body:
try to use React-router redirect method

import { Redirect } from "react-router-dom";

then use a state prop to identify that you click operation has been finished like this

state = {
    open:false;
    }
addValue(evt)
{
  evt.preventDefault();
  if(this.state.value !=undefined)
  {
    alert('Your input value is: ' + this.state.value)
    localStorage.setItem('reg_no',this.state.value);
    alert(localStorage.getItem('reg_no'));
this.setState({open:true});
  }

}

render() {
    return (
        <form onSubmit={this.addValue}>
    {this.state.open? (
    <Redirect
          to={{
            pathname: "/home"
          }}
    ):null}
        <input type="text" onChange={this.updateInput} placeholder="Enter Hospital Registration Number"/><br/><br/>
        <Button type="submit" value="Enter" onClick={()=>this.addValue}> Enter</Button>

        </form>
      );
}


问:
Filtering calculated values with pandas in python
I am trying to filter the values of 'BMI', such that I'm left with all values less than 35. However, when executing this (see code) I end up with a 248x19 (i.e. the imported file) matrix with some (for me unexplainable) NaN values inside of it, instead of getting a single column of filtered 'BMI'-values, which I ultimately want.

Code in pycharm:

```<code>df = pd.read_csv('BodyFat.csv', sep=';',decimal=',')
df['BMI'] = 703*df.WEIGHT/(df.HEIGHT**2)

df_filter = df[df['BMI'] < 35]

print(df_filter)
</code>```

Code

Edit* Output

How can I solve this?

答:
I am guessing this might be due to NaN values : </p>

```<code>new_data = df[(df[''BMI'] < 35) & (df['BMI'].notnull())]

len(df)
len(new_data)

</code>```

Body:
I am trying to filter the values of 'BMI', such that I'm left with all values less than 35. However, when executing this (see code) I end up with a 248x19 (i.e. the imported file) matrix with some (for me unexplainable) NaN values inside of it, instead of getting a single column of filtered 'BMI'-values, which I ultimately want.

Code in pycharm:

df = pd.read_csv('BodyFat.csv', sep=';',decimal=',')
df['BMI'] = 703*df.WEIGHT/(df.HEIGHT**2)

df_filter = df[df['BMI'] < 35]

print(df_filter)

Code

Edit* Output

How can I solve this?

Body:
I am guessing this might be due to NaN values :

new_data = df[(df[''BMI'] < 35) & (df['BMI'].notnull())]

len(df)
len(new_data)


问:
Basic Integer Enum
I created a very basic enum

```<code>public enum StatusCode {

OK(0, "Everything ran correctly"),
ERROR(4, "Fatal Error");

private final int value;
private final String description;

StatusCode(final int value, final String description) {
    this.value = value;
    this.description = description;
}

public int getValue() { return value; }

public String getDescription() { return description; }
}
</code>```

In my method I'm trying to return a integer

```<code>public Integer func() {
   return StatusCode.OK; // Inside method
 }
</code>```

ERROR:

Type mismatch: cannot convert from StatusCode to Integer

I know I can do StatusCode.OK.getValue() but it looks weird. How can StatusCode.OK be an integer by default?

答:
How can StatusCode.OK be an integer by default?

It can't be. It's not an Integer, it's a StatusCode.

And that's better. Anybody can create an Integer, with any value in the range. But you can't create a new StatusCode, so you know that the thing you get is definitely one of [this small number of values].

Title: Basic Integer Enum

Body:
I created a very basic enum

public enum StatusCode {

OK(0, "Everything ran correctly"),
ERROR(4, "Fatal Error");

private final int value;
private final String description;

StatusCode(final int value, final String description) {
    this.value = value;
    this.description = description;
}

public int getValue() { return value; }

public String getDescription() { return description; }
}

In my method I'm trying to return a integer

public Integer func() {
   return StatusCode.OK; // Inside method
 }

ERROR:

Type mismatch: cannot convert from StatusCode to Integer

I know I can do StatusCode.OK.getValue() but it looks weird. How can StatusCode.OK be an integer by default?


问:
Find record length independent of EOL characters
I am using awk to find the length of record .

```<code>awk '{print  length($0),$0}'
</code>```

It works for Unix line endings <LF> but considers DOS line endings <CR><LF> as a character

Is there a way over this.

答:
Just use the Record Separator in awk to DOS line endings (\r\n), so that they are not treated as part of line. In Unix world, the usual endings in just \n which happens to be the default RS value.

```<code>awk -v RS="\r\n" '{ print  length($0), $0 }'
</code>```

You could also sub()/gsub() functions to substitute those characters at the each line and apply your actions.

To handle both Unix/DOS style endings, make the RS definition a regex to occur zero or more occurrence of \r

```<code>awk -v RS="[\r]*\n" '{ print  length($0), $0 }'
</code>```

Both the variants are supported in GNU awk only as POSIX version does not "accept" a multi-character record separator.

Body:
I am using awk to find the length of record .

awk '{print  length($0),$0}'

It works for Unix line endings <LF> but considers DOS line endings <CR><LF> as a character

Is there a way over this.

Body:
Just use the Record Separator in awk to DOS line endings (\r\n), so that they are not treated as part of line. In Unix world, the usual endings in just \n which happens to be the default RS value.

awk -v RS="\r\n" '{ print  length($0), $0 }'

You could also sub()/gsub() functions to substitute those characters at the each line and apply your actions.

To handle both Unix/DOS style endings, make the RS definition a regex to occur zero or more occurrence of \r

awk -v RS="[\r]*\n" '{ print  length($0), $0 }'

Both the variants are supported in GNU awk only as POSIX version does not "accept" a multi-character record separator.


答:
Java enums are not C/C++/C# enums. They aren't integers in disguise, they are more like classes in disguise.

(In fact they -are- classes in disguise -- https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html)

Whereas in C# enum { Foo, Bar } would have implicit values Foo = 0 and Bar = 1, this is not true in Java.

Your line StatusCode.OK.getValue() is the right thing to do in Java.

Title: Basic Integer Enum


问:
Loop through a list and get each value in the list
I have a folder in ADLS that has few files. For the purpose of understanding, I will keep it simple. I have the following three files. When I loop through this folder, I want to get the "file name" and "source" as separate parameters so that I can pass it subsequent activities/pipelines.

employee_crm.txt

contractor_ps.txt

manager_director_sap.txt

I want to put this in an array so that it can be passed accordingly to the subsequent activities.

(employee, contractor, manager_director)

(crm, ps, sap)

I want to pass two parameters to my subsequent activity (may be a stored procedure) as usp_foo (employee, crm) and it will execute the process based on the parameters. Similary, usp_foo (contractor, ps) and usp_foo (manager_director, sap).

How do I get the child items as two separate parameters so that it can be passed to SP?

答:
To rephrase the question, you would like to 1) get a list of blob names and 2) parse those names into 2 variables. This pattern occurs frequently, so the following steps will guide you through how to accomplish these tasks.

Define an ADLS DataSet that specifies the folder. You do not need a schema, and you can optionally parameterize the FileSystem and Directory names:

To get a list of the objects within, use the GetMetadata activity. Expand the "Field list" section and select "Child Items" in the drop down:

Add a Filter activity to make sure you are only dealing with .txt files. Note it targets the "childItems" property:

You may obviously alter these expressions to meet the specific needs of your project.

Use ForEach activity to loop through each element in the Filter sequentially:

Inside the ForEach, add activities to parse the filename. To access the fileName, use "item().name":

In my example, I am storing these values as pipeline variables, which are global [hence the need to perform this operation sequentially]. Storing them in an Array for further use gets complicated and tricky in a hurry because of the limited Array and Object support in the Pipeline Expression Language. The inability to have nested foreach activities may also be a factor.

To overcome these, at this point I would pass these values to another pipeline directly inside the ForEach loop.

This pattern has the added benefit of allowing individual file execution apart from the folder processing.


问:
or [self dealloc] work?
I make a object that use the camera to decode a bar code. If it was successful it send a delegate message to next action, if not, it only go out, and next screen start to work.

If am I in the last command of the object, can I send [self release] to free the memory? But, the problem is: the retainCount can be more than on one?

Like

```<code>  ObjectToDealloc *test = [[ObjectToDealloc alloc] init];
  [test doYourJob];
  //can't release here, it broke my program
</code>```

in the last thing that this object do, it run:

```<code>  -(void)destroyYourself {
     [self release];
     [self dealloc];
  }
</code>```

This will work? I will release the memory? Or I have to make "test" in global visibility (not only function visibility) and do a:

```<code>   [test release];
</code>```

答:
This is not correct memory management. There are a small number of cases when [self release] is correct. There are no cases where [self dealloc] is correct (you should never call anyone's dealloc except your superclass's in your own dealloc).

When you say "it broke my program" above, what do you mean? Does ObjectToDealloc perform background processing of some sort? If it does not, then you should always be able to release it at the point you indicate. If it does do background processing, then you need something to retain the object until it is done, and then release it. Every so often, the best approach is to retain and release self, but usually you have some other thing do it like an NSOperationQueue or the like.

The more likely issue here is that you are handling memory management incorrectly in ObjectToDealloc and that when it deallocates it crashes. What is the crash?

The key thing to remember is that you never say "destroy this object right now" in ObjC. You say "I'm done with this object." When everyone is done with the object, then it is destroyed by the runtime.

Title: or [self dealloc] work?

Body:
I make a object that use the camera to decode a bar code. If it was successful it send a delegate message to next action, if not, it only go out, and next screen start to work.

If am I in the last command of the object, can I send [self release] to free the memory? But, the problem is: the retainCount can be more than on one?

Like

  ObjectToDealloc *test = [[ObjectToDealloc alloc] init];
  [test doYourJob];
  //can't release here, it broke my program

in the last thing that this object do, it run:

  -(void)destroyYourself {
     [self release];
     [self dealloc];
  }

This will work? I will release the memory? Or I have to make "test" in global visibility (not only function visibility) and do a:

   [test release];


答:
For non-contiguous slice objectss, always prefer to use np.r_.

The main goal for np.r_ is:

Translates slice objects to concatenation along the first axis.

Given that you have now concatenated, non-contiguous slice blocks, it gets easy to perform operations. You can use drop, loc, iloc or whatever logic you want (not much gain here beyond readability).

For example,

```<code>df = df.iloc[:, np.r_[50:90, 120:170]]
</code>```

or, as suggested by @anky

```<code>df[df.columns ^ df.columns[np.r_[50:90,120:170]]]
</code>```

Body:
I have a data frame df with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.

I cannot use:

df.drop('column name', axis=1)

directly because there are so many columns to drop and I cannot really type each of its column names as in the above cases.

I am interested in knowing how to select the columns from particular column name column50 to another column name column90 and column120 to column170 rather than with the int

Body:
For non-contiguous slice objectss, always prefer to use np.r_.

The main goal for np.r_ is:

Translates slice objects to concatenation along the first axis.

Given that you have now concatenated, non-contiguous slice blocks, it gets easy to perform operations. You can use drop, loc, iloc or whatever logic you want (not much gain here beyond readability).

For example,

df = df.iloc[:, np.r_[50:90, 120:170]]

or, as suggested by @anky

df[df.columns ^ df.columns[np.r_[50:90,120:170]]]


问:
Why couldn't I cache a variable in MULE4?
Im trying to cache a varibale in mule4. My simple test caching  flow is this;

```<code><ee:object-store-caching-strategy name="Caching_Strategy" doc:name="Caching Strategy" doc:id="9c17681c-81c3-4344-bd4f-7fda1e36a440">
        <os:private-object-store alias="token" persistent="false" entryTtl="100" expirationInterval="5" />
    </ee:object-store-caching-strategy>
<ee:cache doc:name="Cache" doc:id="b413ab46-e3e1-4eb0-ac40-0e5884e1438f" cachingStrategy-ref="Caching_Strategy">

            <set-variable value="500" doc:name="Set Variable" doc:id="97f4436c-98d3-4993-a4bc-b191282b8f16" variableName="cachevariable"/>
            <logger level="INFO" doc:name="Logger" doc:id="0a88f98d-ace9-4326-8d84-31fb7030b75a" message="inside cache"/>

        </ee:cache>
<logger level="INFO" doc:name="Logger" doc:id="d92550c2-041f-42ae-b3b5-62ea906ccbb0" message="#[vars.'cachevariable']"/>
</code>```

In the above scenario i try to cache a variable named cachevariable
In first invocation. my cache flow get hits and the log outside cache scope prints 500.
In the second invocation within a minute, i get Null for cachevariable.

Why is that?

I use anypointstudio 7.5.1 with runtime 4.1.3

答:
I have used the caching strategy with a reference to an object store instead of using a private one:

```<code><os:object-store name="customObjectStore" persistent="false" entryTtl="15" expirationInterval="15" expirationIntervalUnit="SECONDS" maxEntries="100"/>
<ee:object-store-caching-strategy  name="Caching_Strategy" doc:name="Caching Strategy" objectStore="customObjectStore" keyGenerationExpression="#[vars.id]" />
</code>```

Also I recommend to always set the maxEntries.

My example is on my blog: https://medium.com/@adobni/configuring-an-object-store-in-mule-4-5da609e3456a

Body:
Im trying to cache a varibale in mule4. My simple test caching  flow is this;

<ee:object-store-caching-strategy name="Caching_Strategy" doc:name="Caching Strategy" doc:id="9c17681c-81c3-4344-bd4f-7fda1e36a440">
        <os:private-object-store alias="token" persistent="false" entryTtl="100" expirationInterval="5" />
    </ee:object-store-caching-strategy>
<ee:cache doc:name="Cache" doc:id="b413ab46-e3e1-4eb0-ac40-0e5884e1438f" cachingStrategy-ref="Caching_Strategy">

            <set-variable value="500" doc:name="Set Variable" doc:id="97f4436c-98d3-4993-a4bc-b191282b8f16" variableName="cachevariable"/>
            <logger level="INFO" doc:name="Logger" doc:id="0a88f98d-ace9-4326-8d84-31fb7030b75a" message="inside cache"/>

        </ee:cache>
<logger level="INFO" doc:name="Logger" doc:id="d92550c2-041f-42ae-b3b5-62ea906ccbb0" message="#[vars.'cachevariable']"/>

In the above scenario i try to cache a variable named cachevariable
In first invocation. my cache flow get hits and the log outside cache scope prints 500.
In the second invocation within a minute, i get Null for cachevariable.

Why is that?

I use anypointstudio 7.5.1 with runtime 4.1.3

Body:
I have used the caching strategy with a reference to an object store instead of using a private one:

<os:object-store name="customObjectStore" persistent="false" entryTtl="15" expirationInterval="15" expirationIntervalUnit="SECONDS" maxEntries="100"/>
<ee:object-store-caching-strategy  name="Caching_Strategy" doc:name="Caching Strategy" objectStore="customObjectStore" keyGenerationExpression="#[vars.id]" />

Also I recommend to always set the maxEntries.

My example is on my blog: https://medium.com/@adobni/configuring-an-object-store-in-mule-4-5da609e3456a


问:
Javascript Sockets (failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET)
I am trying to create a simple program to send a message to a socket in plain text.  The sender is a webpage in javascript using websocket and the server is a C program.  I don't have any control over the C code but I have been assured by the codes owners that I can use simple javascript to send the message. My code is as follows:

```<code><!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            //initialize the websocket ws
            var ws;
            //Open the socket connection
            function openSock() {
                //test for Websocket compatibility in the browser
                if ("WebSocket" in window) {
                    // log socket attempt
                    console.log("Attempting to open socket!");
                    //open web socket ws
                    ws = new WebSocket("ws://192.168.6.222:11000/echo");
                } else { // else the browser doesn't support WebSocket
                    //Websocket is not supported
                    alert("APS NOT supported by your Browser!");
                }
            }
            //send the command to socket ws
            function sendCommand() {
                console.log("Attempting to Send Message");
                ws.send("your message here");
            }
            //close the socket ws
            function closeSock() {
                console.log("Closing Socket");
                // close socket ws
                ws.close();
            }

        </script>
    </head>
    <body>
        <div id="sse">
            <a href="javascript:openSock()"><input type=submit value="open"></a>
            <a href="javascript:sendCommand()"><input type=submit value="send"></a>
            <a href="javascript:closeSock()"><input type=submit value="close"></a>
        </div>
    </body>
</html>
</code>```

When I click the connect button I get this error:

WebSocket connection to 'ws://192.168.6.222:11000/echo' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

I have checked the firewall and the port seems to be open.  After spending a fair amount of time troubleshooting the server (making sure it is running and on the network, etc.) I am wondering if I did something wrong with this client side code.

From my limited knowledge and the reading I have done this looks correct but any help is welcome.

答:
This is probably super late but I just ran into a similar problem while using Django channels. I fixed it by adding a slash (/) at the end of the URL.

```<code>ws = new WebSocket("ws://192.168.6.222:11000/echo/");
</code>```

Body:
I am trying to create a simple program to send a message to a socket in plain text.  The sender is a webpage in javascript using websocket and the server is a C program.  I don't have any control over the C code but I have been assured by the codes owners that I can use simple javascript to send the message. My code is as follows:

<!DOCTYPE HTML>

            <input type=submit value="open">
            <input type=submit value="send">
            <input type=submit value="close">

When I click the connect button I get this error:

WebSocket connection to 'ws://192.168.6.222:11000/echo' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

I have checked the firewall and the port seems to be open.  After spending a fair amount of time troubleshooting the server (making sure it is running and on the network, etc.) I am wondering if I did something wrong with this client side code.

From my limited knowledge and the reading I have done this looks correct but any help is welcome.

Body:
This is probably super late but I just ran into a similar problem while using Django channels. I fixed it by adding a slash (/) at the end of the URL.

ws = new WebSocket("ws://192.168.6.222:11000/echo/");


问:
Tinymce images auto-wrapped in
 tag. CSS ways around or text editor hacks
Hiya,

I have run into this problem many times now using drupal or wordpress where my tinymce config files are a bit too cleverly abstracted.

The problem is that tinymce auto-wraps my  tags in
 tags.  If there is a way around this in either Wordpress or Drupal, that would be awesome.

My problem exists when I want to do something like this

```<code><style>
    img {
        float: left;
    }
    p {
        float: right;
        margin-right: 20px;
        width: 400px;
    }
 </style>
</code>```

and I want my code to look like this

```<code><img src="some_png.png" />
<p> Imagine a lot of lipsum text.</p>
</code>```

but tinymce does this

```<code><p><img src="crap_im_wrapped_in_a_paragraph.png" /></p>
<p> Imagine a lot of lipsum text.</p>
</code>```

I'm trying to float an image to the left of a paragraph with a set width, without having width restraints on the image itself.

in this case the image's parent then gets a width and a float right.  That is not what I want.

It is very possible that there is an easy clever fix for this but I still have not found one. I would prefer not hacking my config files if I don't have to.

1 caveat...

The only reason this problem exists is because I want clients to be able to easily do their own editing so I won't just have them wrap the image in a
 instead of a
.  That seems to me unintuitive for my clients who are the actual users of the wysiwyg

Previous Solution

I have been using a regex to remove the paragraph tags but it is always somehow problematic.  I end up adding more images somewhere else then i have to keep tuning my regex to ignore them.  502 errors abound!

my question(s) is(are)

What can I to in my CSS to make the image wrapped in the paragraph do what I want it to do?

and if i can't

What drupal or wordpress specific can I do to make that paragraph disappear?

-- Edit --
the solution needs to be compatible with IE7+ and modern browsers. :P

Thanks!

aaron

答:
If you don't want it to wrap image tags, look in the Tinymce source for a function called "isBlock". There is a regular expression white list test that determines whether or not an element is a block element. If you need image tags to be treated as block elements then add "IMG" to the list of node names it looks for. I just had to do this myself, am still looking for negative side effects right now but it does solve the immediate problem at hand.

EDIT:
That was more or less a temporary solution, if you just need to stop the root level block wrapping of image tags, there's a function called "forceRoots" where you'll actually want to perform your image tag check. I did it by modifying this line of code:

```<code>if (nx.nodeType == 3 || (!t.dom.isBlock(nx) && nx.nodeType != 8)) {
</code>```

to look like this:

```<code>if (nx.nodeType == 3 || (!t.dom.isBlock(nx) && nx.nodeType != 8) && nx.nodeName.toLowerCase() != "img") {
</code>```

This solves the problem quite well for me.

Title: Tinymce images auto-wrapped in <p> tag. CSS ways around or text editor hacks

Body:
Hiya,

I have run into this problem many times now using drupal or wordpress where my tinymce config files are a bit too cleverly abstracted.

The problem is that tinymce auto-wraps my  tags in
 tags.  If there is a way around this in either Wordpress or Drupal, that would be awesome.

My problem exists when I want to do something like this

and I want my code to look like this

 Imagine a lot of lipsum text.

but tinymce does this

 Imagine a lot of lipsum text.

I'm trying to float an image to the left of a paragraph with a set width, without having width restraints on the image itself.

in this case the image's parent then gets a width and a float right.  That is not what I want.

It is very possible that there is an easy clever fix for this but I still have not found one. I would prefer not hacking my config files if I don't have to.

1 caveat...

The only reason this problem exists is because I want clients to be able to easily do their own editing so I won't just have them wrap the image in a
 instead of a
.  That seems to me unintuitive for my clients who are the actual users of the wysiwyg

Previous Solution

I have been using a regex to remove the paragraph tags but it is always somehow problematic.  I end up adding more images somewhere else then i have to keep tuning my regex to ignore them.  502 errors abound!

my question(s) is(are)

What can I to in my CSS to make the image wrapped in the paragraph do what I want it to do?

and if i can't

What drupal or wordpress specific can I do to make that paragraph disappear?

-- Edit --
the solution needs to be compatible with IE7+ and modern browsers. :P

Thanks!

aaron

Body:
If you don't want it to wrap image tags, look in the Tinymce source for a function called "isBlock". There is a regular expression white list test that determines whether or not an element is a block element. If you need image tags to be treated as block elements then add "IMG" to the list of node names it looks for. I just had to do this myself, am still looking for negative side effects right now but it does solve the immediate problem at hand.

EDIT:
That was more or less a temporary solution, if you just need to stop the root level block wrapping of image tags, there's a function called "forceRoots" where you'll actually want to perform your image tag check. I did it by modifying this line of code:

if (nx.nodeType == 3 || (!t.dom.isBlock(nx) && nx.nodeType != 8)) {

to look like this:

if (nx.nodeType == 3 || (!t.dom.isBlock(nx) && nx.nodeType != 8) && nx.nodeName.toLowerCase() != "img") {

This solves the problem quite well for me.


问:
Python function returns generator instead of list
I wanted to play around with primes in Python and therefore use a function to create a Sieve of Eratosthenes:

```<code>def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for (i, isprime) in enumerate(a):
        if isprime:
            yield i
            for n in range(i*i, limit, i):
                a[n] = False
    return list(a)
</code>```

In my opinion this function should definitely return a list but when I do print(primes(1000)) I only get <generator object primes at 0x0000000002C5C558> as the output. When using print(list(primes(1000))) everything works as expected (the list of primes is printed).

What am I missing?

Why does the function return a generator instead of a list?

答:
I just had a similar issue and wanted to update you all. If the function yields at some point it returns a generator even if you expect a list. So you need to get rid of yields.

```<code>def get_list_or_generator(return_list=True):
    items = [1, 2, 3, 4]
    if return_list:
        return items  # returns generator
    else:
        for item in items:
            yield item  # returns generator
</code>```

And it works with list(get_list_or_generator()) as a list because casting to list iterates through the generator

Body:
I wanted to play around with primes in Python and therefore use a function to create a Sieve of Eratosthenes:

def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for (i, isprime) in enumerate(a):
        if isprime:
            yield i
            for n in range(i*i, limit, i):
                a[n] = False
    return list(a)

In my opinion this function should definitely return a list but when I do print(primes(1000)) I only get <generator object primes at 0x0000000002C5C558> as the output. When using print(list(primes(1000))) everything works as expected (the list of primes is printed).

What am I missing?

Why does the function return a generator instead of a list?

Body:
I just had a similar issue and wanted to update you all. If the function yields at some point it returns a generator even if you expect a list. So you need to get rid of yields.

def get_list_or_generator(return_list=True):
    items = [1, 2, 3, 4]
    if return_list:
        return items  # returns generator
    else:
        for item in items:
            yield item  # returns generator

And it works with list(get_list_or_generator()) as a list because casting to list iterates through the generator


问:
How to drop multiple columns (using column names) from a dataframe using pandas?
I have a data frame df with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.

I cannot use:

```<code>df.drop('column name', axis=1)
</code>```

directly because there are so many columns to drop and I cannot really type each of its column names as in the above cases.

I am interested in knowing how to select the columns from particular column name column50 to another column name column90 and column120 to column170 rather than with the int

答:
```<code>df.drop(df.columns.to_series()["column_name_1":"column_name_2"], axis=1)
</code>```

By converting to a series you can actually use a range to drop. You'd just need to know the column names.

Body:
df.drop(df.columns.to_series()["column_name_1":"column_name_2"], axis=1)

By converting to a series you can actually use a range to drop. You'd just need to know the column names.


问:
Trouble with nested ifelse statement in R
I'm trying to run a nested ifelse statement in R.  Here's a look at the structure of my data using the glimpse() function from the tidyverse:

```<code>Rows: 22,104
Columns: 9
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
</code>```

I'm trying to get R to look at the Age column and if the value is within a certain range, for it to put the geological age name into a new column called AgeName.  If the value is not within the range, I want it to move on to the next age range and so on and so forth.  Here's my code so far:

```<code>pbdb_tidyish$AgeName <- ifelse(56>=pbdb_tidyish$Age&&47.8<pbdb_tidyish$Age,
                               "Ypresian",
                               ifelse(47.8>=pbdb_tidyish$Age&&41.2<pbdb_tidyish$Age,
                                      "Lutetian",
                                      ifelse(41.2>=pbdb_tidyish$Age&&37.8<pbdb_tidyish$Age,
                                             "Bartonian",
                                             ifelse(37.8>=pbdb_tidyish$Age&&33.9<=pbdb_tidyish$Age,
                                                    "Priabonian",NA))))
</code>```

When I run this code, it creates the new column but fills the whole column with "Priabonian" so the dataset now looks like this:

```<code>Rows: 22,104
Columns: 10
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
$ AgeName                 <chr> "Priabonian", "Priabonian", "Priabonian", "Priabonia...
</code>```

Does anyone have any idea where I'm going wrong? I think it's just looking at the first Age value, running the ifelse statement then filling the whole column with the result of that as opposed to moving on to the next row.

Thanks,

Carolina

答:
Without data it is unclear whether this is the only error but you should not use && here since it is not vectorized. That means, it only checks the value in the first row, returns either TRUE or FALSE, based on this single observation only, and recycles this value.

Use & instead.

For a comparison see this answer

Body:
I'm trying to run a nested ifelse statement in R.  Here's a look at the structure of my data using the glimpse() function from the tidyverse:

Rows: 22,104
Columns: 9
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...

I'm trying to get R to look at the Age column and if the value is within a certain range, for it to put the geological age name into a new column called AgeName.  If the value is not within the range, I want it to move on to the next age range and so on and so forth.  Here's my code so far:

pbdb_tidyish$AgeName <- ifelse(56>=pbdb_tidyish$Age&&47.8<pbdb_tidyish$Age,
                               "Ypresian",
                               ifelse(47.8>=pbdb_tidyish$Age&&41.2<pbdb_tidyish$Age,
                                      "Lutetian",
                                      ifelse(41.2>=pbdb_tidyish$Age&&37.8<pbdb_tidyish$Age,
                                             "Bartonian",
                                             ifelse(37.8>=pbdb_tidyish$Age&&33.9<=pbdb_tidyish$Age,
                                                    "Priabonian",NA))))

When I run this code, it creates the new column but fills the whole column with "Priabonian" so the dataset now looks like this:

Rows: 22,104
Columns: 10
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
$ AgeName                 <chr> "Priabonian", "Priabonian", "Priabonian", "Priabonia...

Does anyone have any idea where I'm going wrong? I think it's just looking at the first Age value, running the ifelse statement then filling the whole column with the result of that as opposed to moving on to the next row.

Thanks,

Carolina


问:
Is there a way to define the fraction of each label I want in sci-kit learn cross validation?
I've written a simple Python script that uses sklearn.neural_network.MLPClassifier and sklearn.model_selection.GridSearchCV to make predictions about binary classification data, each point being labelled either 0 or 1. In the training data, roughly 90% have the label 1 and 10% have the label 0. In the test data, roughly 35% have the label 1 and 65% have the label 0. This proportion is known, although the labels aren't known.

My model is currently over-fitting. My cross-validation score for the training data is 85-90%, but the score when I run the code on the test set is below 40%.

One workaround I've thought of is that I could try setting GridSearchCV to split the data so that each training/validation set has approximately the same proportion of labels as the test data. This doesn't seem to be an option with this library however, and my google-fu hasn't returned any results in terms of other sci-kit learn programmes.

Are there any other libraries I could use, or a parameter I could input that I haven't managed to find? Thank you.

答: I would suggest the imblearn library, as it offers a great variety of methods for re-sampling. I do not know the size or other specifics of your data set, but in general, I would argue that oversampling strategies should be favored over undersampling ones. You could for example use SMOTE to oversample your 0 labels in the training set.  The sampling_strategy  parameter also allows you to specify your desired ratio beforehand.


问:
printing array not working
hello everyone i am printing array from the database in the following format

```<code>Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )
</code>```

It is the result of

```<code>$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;
</code>```

problem is how can i pick the single record from it like this

```<code>echo $row[$task_id]; // not working
</code>```

Thanks

答:
You need quotes around the key for this to work:

```<code> echo $row['task_id'];
</code>```

Good-luck!

Title: printing array not working

Body:
hello everyone i am printing array from the database in the following format

Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )

It is the result of

$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;

problem is how can i pick the single record from it like this

echo $row[$task_id]; // not working

Thanks

Body:
You need quotes around the key for this to work:

 echo $row['task_id'];

Good-luck!


问:
left indent in children div
how do I remove the indent in 1 px left of the blue div? I tried to reset border, no effect

body
{margin: 0; padding: 0; width: 100%; height: 100%; background: #222222;}

.container
{background: red; width: 1600px; height: 100px; margin: 0 auto;}

.header
{background: blue; width: 100%; height: 64px; box-sizing: border-box;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>

<div class="container">
<div class="header"></div>
</div>

</body>
</html></code>```

答:
Judging your example, there seems to be some margin on the body element. You can remove it like this:

.container {
  background: red;
  width: 1600px;
  height: 100px;
  margin: 0 auto;
}

.header {
  background: blue;
  width: 100%;
  height: 64px;
  box-sizing: border-box;
}

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="header"></div>
</div></code>```

Title: left indent in children div

Body:
how do I remove the indent in 1 px left of the blue div? I tried to reset border, no effect

body
{margin: 0; padding: 0; width: 100%; height: 100%; background: #222222;}

.container
{background: red; width: 1600px; height: 100px; margin: 0 auto;}

.header
{background: blue; width: 100%; height: 64px; box-sizing: border-box;}

<!DOCTYPE html>

<title>Test</title>

Body:
Judging your example, there seems to be some margin on the body element. You can remove it like this:

.container {
  background: red;
  width: 1600px;
  height: 100px;
  margin: 0 auto;
}

.header {
  background: blue;
  width: 100%;
  height: 64px;
  box-sizing: border-box;
}

body {
  margin: 0;
}

<div class="container">
  <div class="header"></div>
</div>


问:
MySql Workbench installer requires Visual C++ 2015 Redistributable Package to be installed, but it already is installed
I've looked everywhere online, but it doesn't look like anyone has been able to resolve this issue.

When I download and try to install MySql Workbench, I get prompted to install Visual C++ Redistributable package (2015) to be installed. The wizard then takes me directly to this website in order to install it.

However, whenever I try to install either, it just tells me they're already installed.

After googling this for about an hour, I found some other people had this problem which apparently was resolved by following the instructions from this website. I downloaded instaedit and followed the instructions, but I continue to get the same error.

I've been at this for two days now and am going to go crazy. If someone can help me with this I'd be very grateful. I'm using Windows 10,

答:
The issue here is permissions.  When running the MSI, AND if your local policy is set to  (prompt for everything), you will encounter this issue because the MSI isn't prompting for credentials to browse the registry to look and see if c++ redistributable is installed.

Solution.

Run the msi as an admin.

how i did that:

download and open the workbench msi in a msi editor, like InstEd. from within InstEd, run the package as an admin.


问:
Editing Date Time Member Variables with a DropDownListFor doesn't save
So, I am trying to create a DropDownList that will edit the various member variables the DateTime class has (which I have an instance of in my model), such as Day, Month, and Year. However, when an item is selected in the DropDownList and the Save input button is clicked, the data does not save. All other edited pieces of data will be changed and saved, but the DateTime field will just not update. I'd rather not make a new model just for my Dates, but it can be done. I can create the SelectList, I do so in an HTML Helper, shown below:

```<code>namespace ErrorReport.Helpers
{
public class DateList
{
    public static IEnumerable<SelectListItem> DayList
    {
        get
        {
            var days = new List<SelectListItem>();
            for (int i = 1; i < 32; i++)
            {
                days.Add(new SelectListItem
                {
                    Value = i.ToString(),
                    Text = i.ToString()
                });
            }
            return days;
        }
    }
</code>```

There's obviously two more Lists that get made, one for Year and one for Month (I'm not bothering with hours, minutes, or seconds), didn't show them since the code is identical. In my View, my editor code looks like the below, and the variable I want to change is CmpD (of DateTime class):

```<code><script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
        type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
        type="text/javascript"></script>

@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
    <legend>Edit Report: "@Model.Title"</legend>

    @Html.HiddenFor(model => model.ReportId)
    @Html.HiddenFor(model => model.SbmD)
    @Html.HiddenFor(model => model.UserName)
    @Html.HiddenFor(model => model.CmpD)

    ...irrelevant editor code...

    <div class="editor-label">
        @Html.LabelFor(model => model.CmpD, "Estimated Completion Date:")
    </div>

    <div class="editor-field">

        @Html.DropDownListFor(model => model.CmpD.Month, DateList.MonthList)
        @Html.DropDownListFor(model => model.CmpD.Day, DateList.DayList)
        @Html.DropDownListFor(model => model.CmpD.Year, DateList.YearList)

        //@Html.ValidationMessageFor(model => model.CmpD.Month)
        //Above line was commented out
    </div>
    <p>
        <input type="submit" value="Save"/>
    </p>
</fieldset>
}
</code>```

I did have validation in place for CmpD's member variables earlier (only the ones I wanted to change), commented them out because they kept throwing validation errors for every possible SelectList choice (marked in above code). I didn't put arguments in the BeginForm function because they caused save problems with saving the other data. I also added the HiddenFor field for CmpD (which is my DateTime) to get everything to save properly, since without that line of code the return controller did not recognize the Model as valid and didn't save it. I tried adding a HiddenFor field for every member variable in the DateTime class I am not using, and I still get Validation errors if I remove the HiddenFor(model => model.CmpD), even with other Hidden Fields present. I have also tried to make a list this way:

```<code>    public static IEnumerable<int> YearList
    {
        get
        {
            var years = new List<int>();
            for (int i = 0; i < 4; i++)
            {
                years.Add(i);
            }
            return years.AsEnumerable();
        }
    }
</code>```

However, this prevents the Html.DropDownListFor function from working at all, it apparently has to use SelectList items. I have noticed that only strings can be SelectList items, and that the DateTime member variables are ints. Is that causing the problem? Because I don't see where they are recasted to ints and cannot figure out how I would do that. Basically, how do I edit DateTime member variables in a DropDownList?

Also: Is this too much inline code? Thanks in advance!

答:
The DateTime properties (Day, Month, etc.) are all read-only. Hence, it is not possible to set them on a DateTime instance.
You would need settable int properties in your model to be able to update the values from the drop-downs. Then you can construct a DateTime from those values later. I would probably create a separate model class just for this purpose and implement the date editor as separate editor template or partial view that handles all the details (to keep your code clean).</p>

Body:
So, I am trying to create a DropDownList that will edit the various member variables the DateTime class has (which I have an instance of in my model), such as Day, Month, and Year. However, when an item is selected in the DropDownList and the Save input button is clicked, the data does not save. All other edited pieces of data will be changed and saved, but the DateTime field will just not update. I'd rather not make a new model just for my Dates, but it can be done. I can create the SelectList, I do so in an HTML Helper, shown below:

namespace ErrorReport.Helpers
{
public class DateList
{
    public static IEnumerable<SelectListItem> DayList
    {
        get
        {
            var days = new List<SelectListItem>();
            for (int i = 1; i < 32; i++)
            {
                days.Add(new SelectListItem
                {
                    Value = i.ToString(),
                    Text = i.ToString()
                });
            }
            return days;
        }
    }

There's obviously two more Lists that get made, one for Year and one for Month (I'm not bothering with hours, minutes, or seconds), didn't show them since the code is identical. In my View, my editor code looks like the below, and the variable I want to change is CmpD (of DateTime class):

@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
    <legend>Edit Report: "@Model.Title"</legend>

    @Html.HiddenFor(model => model.ReportId)
    @Html.HiddenFor(model => model.SbmD)
    @Html.HiddenFor(model => model.UserName)
    @Html.HiddenFor(model => model.CmpD)

    ...irrelevant editor code...

        @Html.LabelFor(model => model.CmpD, "Estimated Completion Date:")

        @Html.DropDownListFor(model => model.CmpD.Month, DateList.MonthList)
        @Html.DropDownListFor(model => model.CmpD.Day, DateList.DayList)
        @Html.DropDownListFor(model => model.CmpD.Year, DateList.YearList)

        //@Html.ValidationMessageFor(model => model.CmpD.Month)
        //Above line was commented out

        <input type="submit" value="Save"/>

</fieldset>
}

I did have validation in place for CmpD's member variables earlier (only the ones I wanted to change), commented them out because they kept throwing validation errors for every possible SelectList choice (marked in above code). I didn't put arguments in the BeginForm function because they caused save problems with saving the other data. I also added the HiddenFor field for CmpD (which is my DateTime) to get everything to save properly, since without that line of code the return controller did not recognize the Model as valid and didn't save it. I tried adding a HiddenFor field for every member variable in the DateTime class I am not using, and I still get Validation errors if I remove the HiddenFor(model => model.CmpD), even with other Hidden Fields present. I have also tried to make a list this way:

    public static IEnumerable<int> YearList
    {
        get
        {
            var years = new List<int>();
            for (int i = 0; i < 4; i++)
            {
                years.Add(i);
            }
            return years.AsEnumerable();
        }
    }

However, this prevents the Html.DropDownListFor function from working at all, it apparently has to use SelectList items. I have noticed that only strings can be SelectList items, and that the DateTime member variables are ints. Is that causing the problem? Because I don't see where they are recasted to ints and cannot figure out how I would do that. Basically, how do I edit DateTime member variables in a DropDownList?

Also: Is this too much inline code? Thanks in advance!


问:
How can I pivot a table and get the percentage of each row in Python?
I have a dataframe with a few rows, being each one a different subgroup from a major group, just like this:

```<code>group    subgroup    count
A        aaa         10
A        bbb         20
A        ccc         30
B        aaa         10
B        bbb         20
</code>```

How can I pivot this table and get the percentage of each subgroup?
Basically, I want to get this:

```<code>group    subgroup_aaa    subgroup_bbb    subgroup_ccc
A        0.1666          0.33333         0.5
B        0.3333          0.5             0
</code>```

答:
We can try crosstab with normalize

```<code>s=pd.crosstab(index=df.group,columns=df.subgroup,values=df['count'],
              normalize='index',aggfunc='sum').\
              add_prefix('subgroup_').reset_index()
Out[476]:
subgroup group  subgroup_aaa  subgroup_bbb  subgroup_ccc
0            A      0.166667      0.333333           0.5
1            B      0.333333      0.666667           0.0
</code>```

Body:
I have a dataframe with a few rows, being each one a different subgroup from a major group, just like this:

group    subgroup    count
A        aaa         10
A        bbb         20
A        ccc         30
B        aaa         10
B        bbb         20

How can I pivot this table and get the percentage of each subgroup?
Basically, I want to get this:

group    subgroup_aaa    subgroup_bbb    subgroup_ccc
A        0.1666          0.33333         0.5
B        0.3333          0.5             0

Body:
We can try crosstab with normalize

s=pd.crosstab(index=df.group,columns=df.subgroup,values=df['count'],
              normalize='index',aggfunc='sum').\
              add_prefix('subgroup_').reset_index()
Out[476]:
subgroup group  subgroup_aaa  subgroup_bbb  subgroup_ccc
0            A      0.166667      0.333333           0.5
1            B      0.333333      0.666667           0.0


问:
Python - Skip over key if it doesn't exist in json array
I have big json array that lists out certain key value pairs. Each element in the array should look like this:

```<code>{
   "id" : "tmp3269879718695646867",
   "owner" : "johndoe",
   "x11-display" : ":7",
   "x11-authority" : "/run/user/1676/dcv/tmp3269879718695646867.xauth",
   "num-of-connections" : 0,
   "creation-time" : "2019-05-15T20:05:46.170274Z",
   "last-disconnection-time" : "2019-07-19T15:14:37.349168Z"
 },
</code>```

I then attach a beginning square braket and an end square bracket at the end to make it valid JSON. Sometimes, there are around 100 elements in the array. Due to an software upgrade, if the user has not disconnected then the last-disconnection-time key does not appear on this output. What I want to do is loop over each element in the array, but skip the entire element if the last-disconnection-time key does not exist. This is what I have so far in the loop:

```<code>for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        session_details['last-disconnection-time'] = item['last-disconnection-time']
        # Format date
        ...
</code>```

What I would like to do is check for the item each time it loops. Something like this:

```<code>for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        if "last-disconnection-time" in json_array:
                session_details['last-disconnection-time'] = item['last-disconnection-time']
        else:
                print("last-disconnection-time does not exist in this array item")
        # Format date
        ...
</code>```

However I still get the KeyError when running the script.

答:
You need to check if "last-disconnection-time" is in item. json_array is your entire list. item is a dictionary where you want to find out if the key exists.</p>

```<code>if "last-disconnection-time" in item:
</code>```

Body:
I have big json array that lists out certain key value pairs. Each element in the array should look like this:

{
   "id" : "tmp3269879718695646867",
   "owner" : "johndoe",
   "x11-display" : ":7",
   "x11-authority" : "/run/user/1676/dcv/tmp3269879718695646867.xauth",
   "num-of-connections" : 0,
   "creation-time" : "2019-05-15T20:05:46.170274Z",
   "last-disconnection-time" : "2019-07-19T15:14:37.349168Z"
 },

I then attach a beginning square braket and an end square bracket at the end to make it valid JSON. Sometimes, there are around 100 elements in the array. Due to an software upgrade, if the user has not disconnected then the last-disconnection-time key does not appear on this output. What I want to do is loop over each element in the array, but skip the entire element if the last-disconnection-time key does not exist. This is what I have so far in the loop:

for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        session_details['last-disconnection-time'] = item['last-disconnection-time']
        # Format date
        ...

What I would like to do is check for the item each time it loops. Something like this:

for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        if "last-disconnection-time" in json_array:
                session_details['last-disconnection-time'] = item['last-disconnection-time']
        else:
                print("last-disconnection-time does not exist in this array item")
        # Format date
        ...

However I still get the KeyError when running the script.

Body:
You need to check if "last-disconnection-time" is in item. json_array is your entire list. item is a dictionary where you want to find out if the key exists.

if "last-disconnection-time" in item: