Algorithms – Heuristic function for evaluating the Nim state for Negamax / Minimax

I am trying to implement the Nim game using the Negamax algorithm.
Rules of the game: There are three piles filled with coins. The player who gets the last coin loses.

I am looking for a heuristic function to evaluate each state.

So far I've done the following:

int Nim::eval(int player)
    {
        if(ended()){
            return -Inf;
        }

        int notFavorable = 0;

        for(int i = 0; i < HEAPS_NUMBER; i++){
            if(2 <= heaps(i) && heaps(i) <= 4){
                continue;
            } else if(heaps(i) == 1){
                notFavorable++;
            } else if (not((heaps(i) - 3) % 2 == 0 || (heaps(i) - 3) % 4 == 0 || (heaps(i) - 3) % 3 == 0)){
                notFavorable++;
            }
        }

        return notFavorable % 2 == 0 ? Inf : -Inf;
    }

Any suggestions?

django – Pass the input value to the function in view.py

** **.

Objective:

** Pass input value itemnumbervalue to Item number() in views.py

> Error occurred:

The item.views.itemnumer view did not return an HTTP return
Answer. Instead, none is returned

views.py:

import from .forms InputForm

def home_view(request):
    context1 ={}
    context1('form') = InputForm(request.POST)
    return render(request, "input.html", context1)

def itemnumber(request):
    *if (request.GET.get('submitted')):
        c = request.get('ENTER_ITEM_NUMBER')
        print("input valuegiven by user",c)*
        cursor = connection.cursor()
        try:
            itemnumbervalue =  c
            C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'")
            result_set = cursor.fetchall()
            result_set1= (' {} '.format(x) for x in result_set)
            context = {"row": result_set1}
            return render(request, "home.html", context)
        finally:
            cursor.close()

forms.py

class InputForm(forms.Form):
    regex = re.compile('^((1-9){8})$', re.UNICODE)
    ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}."))

home.html

 
    
    {% for row in row %}
{% endfor %}
(column 1,column 2)
{{ row }}

input.html

    
{% csrf_token %} {{form}}

Problem details:

To receive input from the user and to provide this input itemnumbervalue in itemnumber () in view.py. I have already set itemnumbervalue = & # 39; 12345678 & # 39; checked (without user input value) works perfectly and receives the resulting table.

How to reproduce the JacobianMatrix function

I want to use that JacobianMatrix Function in the package VectorAnalysis, but I get the following warning after running the code below.

Needs["VectorAnalysis`"]
JacobianMatrix[{Rr, Ttheta, Zz}, Cylindrical]
General::obspkg: VectorAnalysis` is now obsolete. The legacy version being loaded may conflict with current functionality. See the Compatibility Guide for updating information.

But I haven't found the same function in the built-in functions. What should I do to reproduce this function?

I would like to reproduce the function in various common coordinate systems.

"Skip ports on success" function

Does this only work in conjunction with the port scanner when the loop is activated?
If you scan more than one IP, does the "skip ports on success" check NOT attempt to scan a specific port across the IP range? Such as For example, if I scan 0.0.0.0 and port 21 is a proxy, will the port scanner skip port 21 if port 0.0.0.1 is reached? Or only when looping and on the same IP? Thank you so much!

Equation solution – Vectorized RootFind for interpolated function

I have been trying to vectorize my code for the past few days to speed up root finding in a grid. Sorry in advance if my code is badly formatted. I have quite a bit of setup for the problem. It really starts here where I solve a large system of equations and find an interpolated function trcfnint:

ff = NDSolveValue({q'(t) == A(t).q(t), q(0) == initialc}, {q}, {t, 0, 
     3 period}); // AbsoluteTiming
ggg = Flatten(Through(ff(period)));
trc = ggg((1 ;; -1 ;; 4)) + ggg((4 ;; -1 ;; 4));
listint = ArrayReshape(trc, Dimensions(grid));
trcfnint = ListInterpolation(listint, {{-1, 1}, {-1, 1}})
evs1(a_?VectorQ, b_?VectorQ, d_?VectorQ) := 
  trcfnint(a, b) - 2 Cos(c period (a + I b)/(c^2 - 1) + d);
evs2(a_, b_, d_) := 
  trcfnint(a, b) - 2 Cos(c period (a + I b)/(c^2 - 1) + d);

My goal is to find (a, b, d) in the interpolated range so that evs2 is 0 (evs1 is only the vectorized version). This is very quick and easy, though b = 0::

imAxis1 = {}; Do(
 plot1 = Plot(
   trcfnint(a, 0) - 2 Cos(c period a/(c^2 - 1) + (Theta)), {a, 0, 1},
    Mesh -> {{0}}, MeshFunctions -> {#2 &}, 
   MeshStyle -> PointSize(Medium), PlotRange -> {{0, 1}, {0, 0}}, 
   PlotPoints -> 100); 
 AppendTo(imAxis1, 
  Sort@Cases(Normal@plot1, Point({x_, y_}) -> x, 
    Infinity)), {(Theta), 0, 2 Pi + 0.1, 0.01});
imAxis1 = Flatten(imAxis1); imAxis1 = 
 Transpose({ConstantArray(0, Length(imAxis1)), imAxis1});
ListPlot(imAxis1, PlotStyle -> Directive(Red, PointSize(0.005)), 
 PlotRange -> {{-1, 1}, {-1, 1}}, 
 FrameLabel -> {Style("Re((Lambda))", FontSize -> 20), 
   Style("Im((Lambda))", FontSize -> 20)}, 
 LabelStyle -> Directive(Black), ImageSize -> Large, AspectRatio -> 1,
  Frame -> True, Axes -> False)

When b != 0The most reliable results I have are using the non-vectorized function evs2 in the following code:

total = {};
Table(Do(
    root1 = 
     FindRoot({Re(evs2(aa, b, dd)) == 0, 
       Im(evs2(aa, b, dd)) == 0}, {{aa, a}, {dd, theta}}, 
      MaxIterations -> 20, AccuracyGoal -> 6);
     test = Abs(evs2(aa, b, dd)) /. root1;
    If(Abs(test) < 10^(-5), AppendTo(total, {b, root1((1))((2))}));
    Break, {theta, 0, 2 Pi, 2}), {a, {0.5, 0.6}}, {b, 0, 0.18, 
    0.001}); // AbsoluteTiming
ListPlot(total, PlotStyle -> Directive(Red, PointSize(0.005)), 
 PlotRange -> {{-1, 1}, {-1, 1}}, 
 FrameLabel -> {Style("Re((Lambda))", FontSize -> 20), 
   Style("Im((Lambda))", FontSize -> 20)}, 
 LabelStyle -> Directive(Black), ImageSize -> Large, AspectRatio -> 1,
  Frame -> True, Axes -> False)

When I do that, I only take the upper half bladder. The initial values ​​for a are chosen because they are in a spectral gap on the a axis, and this saves a lot of time in the calculations. Generally I want the ability to quickly solve for many values ​​of a. I investigated various questions about this vectorization: Findroot with a precompiled function with parameters, Jacobian for parallelized FindRoot with multiple variables, FindRoot with vector functions were the most useful. I can publish my successful vectorizations, but they suffer from being slower than the undisclosed implementation. If anyone has any advice, it would be greatly appreciated.

Powershell workflow guide for each -parallel () {} function

I just discovered powershell workflows and am experimenting, but I have some difficulties. I don't know if workflows have any of the following functions at all, but if so, I would appreciate instructions for the following functions to work.

In short, my role workflow ProcessFrame is (hopefully) designed to accept an array of arrays, look at two fields in the second dimension of the array, and return certain values ​​from other arrays of the second dimension to a if the paired values ​​in one of the arrays of the second dimension match the conditional parameters match new array that returns the function. Okay, I understand that this description may have given you a headache. So let me create an example using the script.

By the way, I know how to do that with a traditional one foreach Loop, but if possible I want to use that foreach -parallel Powershell workflow features to learn a new skill.

When I refer to the "second" or "third" field of an array, I start from zero. The field on the far left would be called "zero". An array of (1,2,3) would be called fields zero, one and two. I just want to avoid confusion.

Suppose the array or arrays are filled as follows (as a variable $ inputArray):

$inputArray(0):(1,1,FRAME,BEGIN,1)
$inputArray(1):(1,2,media_type,video,2)
$inputArray(2):(1,2,pkt_pts,1234,3)
$inputArray(3):(1,2,pict_type,P,4)
$inputArray(4):(1,1,key_frame,0,5)

The following script is intended to process all arrays of the second dimension in $ inputArray and return key data if the conditions are met. In particular, it should first be determined whether the matching pair of exists media_type,video in the fields $inputArray()(2),$inputArray()(3) in a single array with a second dimension (in this example $inputArray(1)(2),$inputArray(1)(3)). If not, return a one-dimensional array with three solid fields $returnArray=@(0,0,0). If the matching pair exists – as in this example in $inputArray(1)(2),$inputArray(1)(3) – Then a one-dimensional array with data from other arrays should be returned.

In particular, it should find the second dimension arrays that contain pict_type and key_frame in the field of the second dimension $inputArray()(2). Then the matching values ​​of the same array of the second dimension should be extracted in the field $inputArray()(3). It should then fill the $ returnArray with the corresponding values ​​of $returnArray=@($inputArray(0)(0),$inputArray(3)(3),$inputArray(4)(3)). Please do not worry about the first return field from $inputArray(0)(0) as a value in the first field of arrays of the second dimension – $inputArray()(0) will all be the same; it is simply passed on to them $returnArray.

Provided that this is possible with workflow and foreach -parallelI am unable to figure out how to tell the function if any of the second dimension arrays match media_type,video in their second and third fields they meet if-then Condition. Once I figure out how to do it in you foreach -parallel Loop, I will continue on how to respond to this information. Especially if they don't meet them if-then Condition, return a (0,0,0) Array; Otherwise, continue processing the second dimension arrays and look for keywords in the second field. If found, return the value of the third field within the specified array of the second dimension.

So here is the skeletal structure that I have. I've tried a lot of things, but I'm not getting anywhere near the results I want. Thanks for your help.

workflow ProcessFrame
{
    (CmdletBinding())
    param (
        # The input will be an array of arrays where the first dimension is of variable length (20-45) and the second dimension each have 5 fields.
        # Example (with only two first dimensions - that is, 2 arrays of arrays):
        # $frameArray(0):@(int32,int32,string,string,int32)
        # $frameArray(1):@(int32,int32,string,string,int32)
        $inputArray
    )

    foreach -parallel ($i in $inputArray)
    { 
        # Determine if any single second dimension array $inputArray()(2),$inputArray()(3) matches "media_type,video".
        # If not exit function with return array of (0,0,0)
        if ($i(2) -eq "media_type" -and $i(3) -ne "video")
        {
            # the following may now work; it is a placeholder until I know the correct commands.
            Write-Output @(0,0,0)
        }
        # Determine if any single second dimension array $inputArray()(2),$inputArray()(3) matches "media_type,video".
        # If yes, extract key data from specific second dimension arrays and return values
        else
        {
            if ($i(2) -eq "pict_type")
            {
                $pictType=$inputArray()(3)
            }
            if ($i(2) -eq "key_frame")
            {
                $keyFrame=$inputArray()(3)
            }

            # the following may now work; it is a placeholder until I know the correct commands.
            Write-Output "$($inputArray(0)(0)),$pictType,$keyFrame)"          
        }
    }
}

Possible security problem with the custom taxonomy search function

I would like to add some features to a client WordPress site that allow you to include taxonomy terms from custom post types in WordPress search, and encounter the following answer:

Include a custom taxonomy term in the search

This solution works, but in the comments, one user mentioned that "it is probably not a good idea to insert the raw publicly available search string directly into an SQL query". and added a link for further reading. I can't see anything in this link that relates to the details of the answer.

For quick reference, the code for the answer is below. Would this code be a security risk? If so, what would the solution look like so that you still have the functionality to be able to include taxonomy terms in the WP search without any security risk?

Many thanks

// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23

function atom_search_where($where){
global $wpdb;
if (is_search())
    $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')";
return $where;
}

function atom_search_join($join){
global $wpdb;
if (is_search())
    $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";
return $join;
}

function atom_search_groupby($groupby){
global $wpdb;

// we need to group on post ID
$groupby_id = "{$wpdb->posts}.ID";
if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby;

// groupby was empty, use ours
if(!strlen(trim($groupby))) return $groupby_id;

// wasn't empty, append ours
return $groupby.", ".$groupby_id;
}

add_filter('posts_where','atom_search_where');
add_filter('posts_join', 'atom_search_join');
add_filter('posts_groupby', 'atom_search_groupby');

Continued fractions – How do you calculate this function?

Please, I want to calculate this function, which contains an infinite continuous fraction

f(y_)=1/(1 + ContinuedFractionK(-(((n + 1) (n + 3))/((2 n + 3) (2 n + 5))) y^2 A, 1, {n, 0, Infinity}))

But no results, Mathematica returns the same continued fraction.

function

Please, is there a way to construct this infinite fraction and evaluate f (y)?

Many thanks.

Variational Calculation – Find a distribution that minimizes a function of its moments

Imagine a probability density function $ f (x) $, defined as positive $ x $and let's write his down $ n $The non-centered moment $ x_ {n} $. The mean $ x_ {1} $ is firm (and positive).

How can i find $ f (x) $ that minimizes a certain function of his moments? In my case $ frac {x_ {3} + x_ {1} ^ {3} -2x_ {1} x_ {2}} {(x_ {2} -x_ {1} ^ {2}) ^ {2}} $.

I tried to take the pie derivative of this expression towards a test function $ h (x) $and zeroing the result for each $ h (x) $. In the end, I find a relationship that includes some moments from $ f (x) $ and the variable $ x $, which makes no sense. Do you have an idea of ​​the correct course of action here?

Many thanks!

php – global variable is not passed to another function

I am new to PHP. I have this code and want to pass a global variable called $ sum that is defined in the function post_order Function update_custom_meta. Still no luck. What am I doing wrong?
Thanks in advance!

function post_order() {
    $args = array(
        'type' => 'shop_order',
        'status' => 'processing',//zmienić//zmienić na completed
        'return' => 'ids',
        'date_created' => ( date("F j, Y", strtotime( '-2 days' ) ) ),
    );

    $orders_ids = wc_get_orders( $args );

    foreach ($orders_ids as $order_id) {
        $order = new WC_Order( $order_id );
        $items = $order->get_items();
        global $sum;
        foreach ( $items as $item ) {
            $product_id = $item->get_product_id();
            if($product_id == $_GET('post')) {
                $product_qty = $item->get_quantity();
                $sum += $product_qty;
            }
        }
    }
}    

add_action('init', 'post_order'); 

function update_custom_meta() {
    global $post_id;
    echo $sum;
    $custom_value = $_POST('auto_restock_value') - $sum;
    update_post_meta($post_id, 'auto_restock_value', $custom_value);
    //get_post_meta($post -> ID, 'daily_restock_amount', true);
    update_post_meta($post_id, '_stock', $custom_value);
}

function update_cart_stock() {
    global $post_id;
    //echo get_post_meta($post_id, 'total_sales', true);
    update_post_meta($post_id, '_stock', $custom_value);
}

add_action( 'save_post', 'update_custom_meta' , 10, 2 );