text:
Q: Is it possible to use the subscription-key query string parameter with Azure API Management SOAP-passthrough? We use API Management to expose several API's. One of the API's we expose is configured as a SOAP-passthrough API but we are facing some issues with it regarding authentication of APIM.
When we use the Ocp-Apim-Subscription-Key header for passing the query string it all works correct and the API is returning it's content correct.
When we use the subscription-key query string parameter the API is returning a 401 Unauthorized. I tested this behavior in Postman and changing the way of sending the subscription key is resulting in this behavior.
An implementation detail of this API is that it exposes an existing WSDL and routes this SOAPAction to an Azure Function via the policy. In the Application Insights of the function I can verify that the function is never invoked when I get a 401 but it is invoked when I get a successful call (using the header).
Is this normal behavior? Am I doing things wrong? Or is it a bug in APIM?

A: This might be an issue with the way we do routing for SOAP Passthrough. You will notice in the API setup that we add on a query parameter to identify the SoapAction that an operation will be matched to. It may be that your the api key query parameter is getting overwritten when adding the SoapAction parameter to the inbound request. I will investigate and let your know.

A: We currently use a workaround around this problem with the following policy. Instead of changing the backend-server url in the policy we send a request and set the response of that request as a response for this api. Below you can find our policy which is working with the subscription-key in the query string.
<policies>
    <inbound>
        <base />
        <send-request mode="copy" response-variable-name="response" timeout="20" ignore-error="false">
            <set-url>{{BackendServer_URL}}</set-url>
        </send-request>
        <!--return-response response-variable-name="reponse" /-->
        <choose>
            <!-- If StatusCode is not OK, return Unauthorized with the reason. -->
            <when condition="@(((IResponse)context.Variables["response"]).StatusCode != 200)">
                <return-response response-variable-name="reponse">
                    <set-status code="401" reason="Unauthorized" />
                    <set-body>@(((IResponse)context.Variables["response"]).Body.As<string>())</set-body>
                </return-response>
            </when>
            <otherwise>
                <return-response response-variable-name="reponse">
                    <set-status code="200" />
                    <set-header name="Content-Type" exists-action="override">
                        <value>text/xml; charset=utf-8</value>
                    </set-header>
                    <set-body>@(((IResponse)context.Variables["response"]).Body.As<string>())</set-body>
                </return-response>
            </otherwise>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>


text:
Q: how can i break my do while with nested if/else if? this is the code that i have but i have to admit i have become a bit code blind and cant seem to see the problem eventhough i feel it is an easy one. Any help would be much appreciated. Thank you in advance.
   do{
        System.out.println("Command:");
        scan = new Scanner (System.in);

        String line;

        line = scan.nextLine();

        String[]SplitUpText;

        SplitUpText=line.split(" ");

        Command = SplitUpText[0];

        int param1=-1, param2=-1;

        if (Command.compareTo("move")==0)
        {
            if (SplitUpText.length>1)
            {
                param1=Integer.parseInt(SplitUpText[1]);
                if(SplitUpText.length>2)
                {
                    param2=Integer.parseInt(SplitUpText[2]);
                }
            }g.moveTo (param1, param2);

        }else if(Command.compareTo("circle")==0){

            if (SplitUpText.length>1)
            {
                param1=Integer.parseInt(SplitUpText[1]);
            }g.circle (param1);
        }else if(Command.compareTo("line")==0){
            if (SplitUpText.length>1)
            {
                param1=Integer.parseInt(SplitUpText[1]);
                if(SplitUpText.length>2)
                {
                    param2=Integer.parseInt(SplitUpText[2]);
                }
            }g.lineTo (param1, param2);
        } else {
            System.out.println("Invalid Command");
        }

    } while (Command.compareTo ("end")!=0);

A: It's generally best practice to avoid it (by adding a condition to the while expression instead), but if you want to end the loop prematurely, you can use break;
Here's a simpler example:
int i;

i = 0;
do {
    ++i;
    System.out.println("Before: " + i);
    if (someSpecialCondition) {
        break;
    }
    System.out.println("After: " + i);
}
while (i < 5);

Let's suppose the special condition occurs when i has just become 3, the output would be:
Before: 1
After: 1
Before: 2
After: 2
Before: 3
Note how the break terminated the loop. It can be used with all kinds of loops (do..while, while, and both kinds of for).
If you have nested loops and need to break the outer one from within the inner one, you should probably refactor that code into sub-methods. BUT, if you don't want to refactor, you can use a directed break:
int i, j;

outerLoop: for (i = 0; i < 5; ++i) {
    for (j = 0; j < 5; ++j) {
        if (i == 2 && j == 2) {
            break outerLoop;
        }
    }
}

There, outerLoop labels the outer loop, and break outerLoop causes both the inner loop and the outer loop to terminate. Again, though, if you get into doing this, it's probably time to refactor.
More from the JLS: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.15

A: Consider using break statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating global js variable within function and sending updated to HTML document I am having a really hard time updating a global variable and sending the updated to HTML.
I have the following in HTML:
We found <script type="text/javascript">
var $mainCount;
document.write($mainCount); </script> places for you!

In Javascript:
   var $mainCount = 3; //Global variable

   if (1 = 1) {
   test();
   }

   function test() {
   $mainCount;

   for (var p = 0; p < 10; p++){

   $mainCount = p;
}
}

However, the HTML page does not update the number to 9, and still writes 3 as the global variable was declared as first

A: There is no way to bind HTML to a JavaScript variable.
If you want to update the HTML, then you need to use DOM manipulation to do it.

A: So as we stated in comments you will have to use javascript for it.
var $globalVariable = 3;

(function() {
  console.log('asa');
  $globalVariable = 9;
  document.getElementById("field").innerHTML = $globalVariable;
})();

Take a look at this jsfiddle code.


text:
Q: Installing Thrift on CentOS: can't find Boost 1.40 or higher I can't shake this error when trying to install Thrift:
    ./configure
    ...
    checking for boostlib >= 1.40.0... configure: WARNING: We could not detect the boost libraries (version 1.40 or higher). If you have a staged boost library (still not installed) please specify $BOOST_ROOT in your environment and do not give a PATH to --with-boost option.  If you are sure you have boost installed, then check your version number looking in <boost/version.hpp>. See http://randspringer.de/boost for more documentation.

I'm using CentOS. As per the Thrift docs on CentOS, I've done
sudo yum install automake libtool flex bison pkgconfig gcc-c++ boost-devel libevent-devel zlib-devel python-devel ruby-devel

I've tried using --with-boost to no avail.
I've also done:
[]# yum install boost141
Setting up Install Process
Package boost141-1.41.0-2.el5.x86_64 already installed and latest version
Nothing to do
[]# yum install boost141-devel
Setting up Install Process
Package boost141-devel-1.41.0-2.el5.x86_64 already installed and latest version
Package boost141-devel-1.41.0-2.el5.i386 already installed and latest version
Nothing to do

So now I have:
[root@domU-12-31-39-18-3D-20 include]# find / -name boost
/usr/local/bin/boost
/usr/include/boost141/boost
/usr/include/boost

Through various googling, I've found people with this error who say, 'Oh it was gcc-c++, I didn't have that installed,' but as far as I can tell, I have gcc-c++ installed:
[root@domU-12-31-39-18-3D-20 boost]# yum install gcc-c++
rightscale-epel                                                                                |  951 B     00:00
Setting up Install Process
Package gcc-c++-4.1.2-46.el5_4.2.x86_64 already installed and latest version
Nothing to do

Any advice? Thanks in advance.

A: This is an old question, but I recently hit the same thing working with a Cent 5.10 machine and building Thrift
Fixup the include files for boost141 and the build will work.
ln -s /usr/include/boost141/boost /usr/include/boost


text:
Q: How much pure math should a physics/microelectronics person know I do condensed matter physics modeling in my phd and I was struck up learning quite an amount of physics. But while having done lot of physics courses, I see that if I learn pure math I would understand lot of things better and also probably my modeling skills also might get better. A math prof asked me to do all courses from basic analysis to differential geometry. But that would take time as I see I am taking time studying Walter Rudin's Principles of mathematical analysis. So I am little confused whether am going the right way. Any suggestions?

A: Without knowing more about your research interests it is difficult to offer an informed opinion. That said, here is my take on your question:
Before I did my Ph.D. work (in condensed matter physics) one of my undergraduate majors was pure mathematics. I took a year of analysis and in particular studied some of the same texts you are. I don't regret this. It was worthwhile.
That said, I suspect studying e.g. analysis will offer you little insight into your work in physics. It is certainly not something a condensed matter physicist is expected to know. It also seems unlikely to improve your "modeling skills", although it's not entirely clear what you mean by that.
Doing all the courses from "basic analysis to differential geometry" is a huge undertaking. In my experience, studying outside your field is valuable because drawing from a different set of influences (as compared to your peers) tends to foster original work. But that was not your stated motivation, and if it is, there is no reason to limit yourself to mathematics.

A: I totally agree with previous comments . But if the new study makes your research more improved you should learn it and understand it completely. The book you are telling will take at-least two month in my opinion to go through and understand its concept completely because i took 3-4 month to go through it.


text:
Q: MySQL Subqueries issue To make this example simple, lets pretend my table has the following attributes.
Table
ID: Int
Amount: Int
nameId: Int

Records Ex
ID: 1
Amount: 2
nameId: 3

ID: 2
Amount: 2
nameId: 3

ID: 3
Amount: 1
nameId: 3

Currently I have the following query.
SELECT DISTINCT(amount) FROM server.`inventory` where nameid = 558

It gives me
Amount 1
Amount 2

Straight forward, it selects a unique records base on amount. However, how can I also include in my query so that it counts how many id's are using that amount with nameid 558
So the output should be
Amount 1, Used 1
Amount 2, Used 2

A: This is an aggregation query.  You want group by and count():
SELECT amount, COUNT(*)
FROM server.inventory
WHERE nameid = 558
GROUP BY amount;


text:
Q: Adding other currency format to AngularJS How to add other currency formats like euro to currency filter in AngularJS ?

        Enter Cost
        <input type="text" ng-model="cost" />

 {{ cost | currency }}

A: You could choose to create a custom filter for your currency of choice. However according to Angulars Documentation on the Currency Filter that you can simply provide the symbol, currency abbreviation, and decimal place formatters for your currency .
In HTML Template Binding :
{{ currency_expression | currency : symbol : fractionSize}}

In JavaScript :
$filter('currency')(amount, symbol, fractionSize)

A: You can pass in html entities after currency:. Here are a couple examples.
Item Price{{price | currency:"€"}}
Item Price{{price | currency:"¥"}}

From the documentation, the format for this filter is

{{ currency_expression | currency : symbol : fractionSize}}

A:

        Enter Cost
        <input type="text" ng-model="cost" />

 {{cost| currency:"USD$"}}

A: As described in the documentation, simply add the currency symbol you want after the filter.

 {{ cost | currency : '€' }}

A: // Setup the filter
app.filter('customCurrency', function() {

  // Create the return function and set the required parameter name to **input**
  // setup optional parameters for the currency symbol and location (left or right of the amount)
  return function(input, symbol, place) {

    // Ensure that we are working with a number
    if(isNaN(input)) {
      return input;
    } else {

      // Check if optional parameters are passed, if not, use the defaults
      var symbol = symbol || '$';
      var place = place === undefined ? true : place;

      // Perform the operation to set the symbol in the right location
      if( place === true) {
        return symbol + input;
      } else {
        return input + symbol;
      }

    }
  }

Then pass whatever currency you need.

{{example1 | customCurrency}} - Default

{{example1 | customCurrency:'€'}} - Custom Symbol

{{example1 | customCurrency:'€':false}} - Custom Symbol and Custom Location


text:
Q: Contours -- OpenCV error : Same output for different features like Hull, Rectangle Image used --

My code:
# multiple programs

import cv2
import numpy as np

img = cv2.imread('Dodo.jpg', 0)
ret, thresh = cv2.threshold(img, 127, 255, 0)
img2, contours, hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print(M)

cx = int(M['m10']/ M['m00'])
cy = int(M['m01']/ M['m00'])
print("Cx:", cx, "Cy:", cy)

area = cv2.contourArea(cnt)
print("Area:", area)
perimeter = cv2.arcLength(cnt, True)
print("Perimeter:", perimeter)

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
imgapprox = cv2.drawContours(img,[approx],0,(0,0,255),2)

hull = cv2.convexHull(cnt)
imghull =cv2.drawContours(img,[hull],0,(0,0,255),2)

k = cv2.isContourConvex(cnt)
print(k)

x,y,w,h = cv2.boundingRect(cnt)
rectst = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
rectrt =cv2.drawContours(img,[box],0,(0,0,255),2)

cv2.imshow('StraightRect', rectst)
cv2.imshow('RotatedRect', rectrt)
cv2.imshow('Approx', imgapprox)
cv2.imshow('hull', imghull)

cv2.waitKey()
cv2.destroyAllWindows()

OpenCV-Python version 3.4.1
So I am trying to learn the contour section in OpenCV (Link below)
Link : https://docs.opencv.org/3.4.1/dd/d49/tutorial_py_contour_features.html
Now the output is the same for all the features. i.e. same output for every cv2.imshow here.
Why? What is the error?
If it is overwriting the previous feature, then how do I display every feature?
Please help. Thanks :)

A: You are making the change in the same image each time.
Use image.copy() in cv2.drawContours(img.copy ,.......) , cv2.rectangle(img.copy(),.....)
.Because of that it seems they are showing the same features but it isn't .
Also since the background is black you are not able to see the rectangles and contour properly
Try this:
import cv2
import numpy as np

img = cv2.imread('Dodo.jpg')

f1 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
f1 = cv2.threshold(f1, 120,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

img2, contours, hierarchy = cv2.findContours(f1, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

#ret, thresh = cv2.threshold(img, 127, 255, 0)
#img2, contours, hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print(M)

cx = int(M['m10']/ M['m00'])
cy = int(M['m01']/ M['m00'])
print("Cx:", cx, "Cy:", cy)

area = cv2.contourArea(cnt)
print("Area:", area)
perimeter = cv2.arcLength(cnt, True)
print("Perimeter:", perimeter)

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
imgapprox = cv2.drawContours(img.copy(),[approx],0,(0,0,255),2)

hull = cv2.convexHull(cnt)
imghull =cv2.drawContours(img.copy(),[hull],0,(0,0,255),2)

k = cv2.isContourConvex(cnt)
print(k)

x,y,w,h = cv2.boundingRect(cnt)
rectst = cv2.rectangle(img.copy(),(x,y),(x+w,y+h),(0,255,0),2)

rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
rectrt =cv2.drawContours(img.copy(),[box],0,(0,0,255),2)

cv2.imshow('StraightRect', rectst)
cv2.imshow('RotatedRect', rectrt)
cv2.imshow('Approx', imgapprox)
cv2.imshow('hull', imghull)

cv2.waitKey()
cv2.destroyAllWindows()

This is the result i get after executing the above code.


text:
Q: My text loses its 'bold' when I change its font-size property I have some text on my website that I would like to make 'bold', and its font-size to be 'x-small'. But whenever I apply the font-size, the text loses its bold. When I remove the font-size, and the text goes back to default, it's bold again. What's going on here?
<span style="font-size:x-small; font-weight:bold;">TESTING</span

A: Have you tried other font families? If I remember correctly, Arial in small sizes looks the same in bold and normal weights. Give Verdana a shot.

A: the thing is that true type fonts DO render differently on various sizes.
If you have bitmap fonts, its just resampled to whatever size necessary.
TTF are based on vector graphics and can be scaled to any size needed.
However there are, depending on the font family, differences in how the font is rendered in different sizes.
Theese changes are intentionally and coded by in by the designer of the font.
Usually lines get thinner the smaller the font is rendered, this could cause the effect you are experiencing. You can try different fonts, but rest assuered that, unless you use certified standardized fonts, there is no guarantee of how they will be rendered.

A: Some font families will appear as normal when you shrink them.
Try using Type Tester to see exactly how your fonts look. It will use the web safe ones as well as what's on your machine if your using @font-face.
http://www.typetester.org/


text:
Q: error in only production server in flask app I am using the flask app for backend development. but when I run it on the production server, I have an error in the import bs4 library in the file.
I checked of bs4 version on both servers, versions are the same on both servers.
when I add import bs4 in the file code at the time file automatically terminates without giving any kind of error statement.
try:
    from bs4 import BeautifulSoup
except os.error:
    print("error :- "+ os.error)

I import bs4 this way for getting an error statement.

it does not give any error statement.
so, how can find the error and how can I solve it?


text:
Q: Hide a category/posts from the homepage in wp I tried it all and since i am not so good in this coding,
I want to hide a category and his posts from the homepage
I tried all plugins especially wp hide post but it needs pro version and seems Support is not answering on my emails so i rather do not buy that
 i tried the code that i found everywhere see below,
however my theme has his own categories for products (taxonomy=download_category&post_type=download)
the code i found and tried in many ways to change
function exclude_category($query) {
    if ( $query->is_home() ) {
        $query->set( 'cat', '-156, -58,-154,-155' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_category' );

so 1 of the things i tried was

function exclude_category_download($query) {
if ( $query->is_home() ) {
$query->set('cat', '-156, -58,-154,-155');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category_download');

I am completely lost could really use some help

A: Have you tried Ultimate Category Excluder plugin? You can use it to exclude categories very easily. You just need to select the categories that you want to remove. It can be very useful, as you are not comfortable with coding.
Also, you can try using the following codes:
function exclude_category_home( $query ) {if ( $query->is_home ) {$query->set( 'cat', '-156, -58,-154,-155' );}return $query;}add_filter( 'pre_get_posts', 'exclude_category_home' );

You can find more information about the method of hiding category here.

A: @PratikPatel oh my god why i did not think of that, most easy ever thank you so much...
regarding ultimate category excluder i tried them all, not made for that, well only wp hide post showed he could see that other kind of categories, but they not answer
for some one maybe works SIMPLY EXCLUDE, i just found it and it did show up in the special pages that others do not show, however it did not work anymore at least not for me https://wordpress.org/plugins/simply-exclude
Thank you so much all, saved me some grey hair here! however
i have another website theme etc. from wpjobster, seems i am not able to do that trick... there are some adult categories i would like to exclude


text:
Q: How to dynamically inspect a format string with named placeholders like "{foo} {bar} {baz}" Given a string that uses named placeholders for formatting, is it possible to inspect what the names are dynamically?
>>> var = '''{foo} {bar} {baz}'''
# How to do this?
>>> for k in var.inspect_named_placeholders():
>>>     print(k)
foo
bar
baz

A: Yes, you can use the built-in parser:
>>> var = '''{foo} {bar} {baz}'''
>>> import string
>>> formatter = string.Formatter()
>>> formatter.parse(var)
<formatteriterator object at 0x109174750>
>>> list(formatter.parse(var))
[('', 'foo', '', None), (' ', 'bar', '', None), (' ', 'baz', '', None)]


text:
Q: WPF MVVM: Find out on which header context menu has been clicked I am trying to use the MVVM pattern to write a WPF application. I am using WPF data grid (from the toolkit) which lacks the autofiltering feature. So I want to implement it. I've added a context menu to the column header template, it has MenuItem called "Filter" which should actually call the filtering method.
So I've set a MenuItem's command to be the appropriate DelegateCommand which goes to the ViewModel. The problem is that I need to pass the information about the actual column that has been right-clicked! If I wasn't using MVVM, I would implement an event handler which would receive a "sender" argument (the MenuItem), then I would find its parent (the ContextMenu), then its parent would give me the column. But how can I achieve the same thing here? How can I pass the sender to my command? Can this be done using ComandParameter?
I really don't want to use additional complicated patterns to achieve such a simple task. After all, MVVM should simplify the development and not vice versa...

A: Can you pass the Column header value as a Command Parameter and use that to get the Column details at the ViewModel?

A: You could try some relative source magic, but it might be easier on you if you can have a different ViewModel that you bind to for each header, like HeaderViewModelItem.  From there you'd just be firing a DelegateCommand in your HeaderViewModelItem, rather on your larger viewmodel.
I've used this model with pretty good success.  Gets around a little bit of databinding dance.

A: If you want to pass something into the command parameter it is important to note that a context menu is on its own visual tree. Luckily it still inherits the DataContext from its parent, so something like
<MenuItem CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=DataContext}" />

should get you the GridViewColumnHeader, or at least something in the visual tree of it.


text:
Q: Max amount of parallel value access When I limit the amount of threads for my parallel for to 6 or below, it works fine. Anything above 6, it says it can't read the object at the specified location. Is there was a certain amount of times you can initialize the same object at a time, or how can I fix the error it gives out? All the code works fine if the MaxDegreeOfParallelism is <=6
Parallel.For(4, erCnt/2 ,opt, a =>
{
    if (a % 2 == 0)
    {
        dynamic[] name = new dynamic[2], num = new dynamic[2], wage = new dynamic[2], dept = new dynamic[2];//, name1 = new dynamic[2], num1 = new dynamic[2], wage1 = new dynamic[2], dept1 = new dynamic[2];
        num[0] = (string)(empSheet.Cells[a, 1] as Excel.Range).Value2;
        name[0] = (string)(empSheet.Cells[a, 2] as Excel.Range).Value2 + "," + (string)(empSheet.Cells[a, 3] as Excel.Range).Value2;
        dept[0] = ((empSheet.Cells[a, 4] as Excel.Range).Value2);
        wage[0] = (empSheet.Cells[a, 5] as Excel.Range).Value2;
        num[1] = (string)(empSheet.Cells[a + 1, 1] as Excel.Range).Value2;
        name[1] = (string)(empSheet.Cells[a + 1, 2] as Excel.Range).Value2 + "," + (string)(empSheet.Cells[a + 1, 3] as Excel.Range).Value2;
        dept[1] = ((empSheet.Cells[a + 1, 4] as Excel.Range).Value2);
        wage[1] = (empSheet.Cells[a + 1, 5] as Excel.Range).Value2;
        employee.Add(name[0], dept[0]);
        employee.Add(name[0], wage[0]);
        employee.Add(name[0], num[0]);
        employee.Add(name[1], wage[1]);
        employee.Add(name[1], dept[1]);
        employee.Add(name[1], num[1]);
    }
});


text:
Q: On a claim of Deligne about representations of Weil-Deligne groups In Deligne's article 'Les constantes des equations fonctionelles des fonctions L' http://publications.ias.edu/sites/default/files/Number20.pdf, we find the following claim:
Proposition 8.9 (ibid.):  Suppose $(V,  \rho, N )$  and  $(V', \rho',  N')$  are two Frobenius semisimple,  $\ell$-adic and $\ell'$-adic representations of the Weil-Deligne group $' W_K $ of a (non-archimedean ) local field $ K$, respectively. Let $\mathbf{M}_{\bullet}$ and $\mathbf{M'}_{\bullet}$ be the (monodromy) filtrations induced by $N $ and $N'$ on $ V$ and $V'$, respectively. Then $(V, \rho, N )$ and $(V', \rho', N')$ are compatible (in the sense of ibid. 8.7) if and only if the characters, of the representations induced by $\rho$ and $\rho '$ on the graded parts of $\mathbf{M}_{\bullet}$  and $\mathbf{M'}_{\bullet}$ coincide and has values in $\mathbb{Q}$.
Deligne states this as an exercise. Does anyone know a rigorous proof  or any reference?
Of course it is clear that if the characters of the representations (as in the proposition) induced by $\rho $ and $ \rho'$ on the graded parts of  the filtrations $\mathbf{M}_{\bullet}$  and $\mathbf{M'}_{\bullet}$, coincide and has values in $\mathbb{Q}$, then the character of $\rho $ and $ \rho'$ are same and hence due to semi-simplicity, $\rho $ and $\rho'$ are isomorphic (after base extension to a common algebraic closure $\Omega \supset \mathbb{Q}_{\ell}, \mathbb{Q}_{\ell '} $) as representations of the Weil group $ W_K $. But what is not clear to me is how to find an  isomorphism   $ f $ between $ \rho$ and $ \rho' $ ( after base extension $\Omega $), such that
$$ f \circ N = N' \circ f \quad \text{(after base extension to $\Omega $) } \;? $$


text:
Q: VB.Net Is there away of reading and updating a picture's tags and comments? In File Explorer in Windows 10, going via a file's Properties | Details you can set Tags and Comments.
I want to use these fields for annotating photos and movies created by our wildlife camera, tagging files with "Fox", "Badger" etc. You can add the two fields as columns in File Explorer lists.
However it would be very tiresome updating the properties for all 2700 files we have so far, so I have written a program which makes the process much quicker, BUT at the moment the tags and comments for each file go into a text file, which is stored in the same folder as the media file and under a similar name.
Very nice, but it would be much better if the tags and comments could be stored in the media file - the only trouble being that a prolonged search of the web has revealed nothing, or rather a great deal of stuff which appears relevant, but isn't!
So please can someone help me?


text:
Q: What's the best way of implementing multiple activities? I have a few activities in my app, and I define them like this:

    <activity
            android:name=".DetailsActivity"
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"/>

    <activity
            android:name=".ZoomActivity"
            android:theme="@style/Theme.Something.FullScreen"
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"/>

    <activity
            android:name=".RadioActivity"
            android:label="@string/radio"
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"/>

    <activity
            android:name=".SettingsActivity"
            android:label="@string/settings"
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"/>

DetailsActivity and ZoomActivity are activities started after tapping on an item in RecyclerView, and they just show details of an item.
RadioActivity is an activity bound to service.
SettingsActivity is just an ordinary android preferences activity.
I am not really certain if that's the best way to define multiple activities (I mean launchMode, clearTaskOnLaunch and excludeFromRecents).
Should I leave it as is, or maybe change my approach?
Thanks in advance.

A: Your approach is fine.
If you're afraid of having to declare many activities, it's likely that you're unnecessarily creating new subclasses of activities you can reuse. Bear in mind that you can easily pass data into an activity through the Intent's Bundle.
It's difficult to say if the flags you're providing for each activity necessarily make sense, but if you want the application to close when the user backs out of one activity, and itself have no history in the back stack, then this is will accomplish that task.


text:
Q: Checking for a directory in results returned from attributesOfItemAtPath In the following code, I am scanning a directory for its contents and am attempting to ascertain whether a child is a directory or file:
NSString *child = [dir stringByAppendingPathComponent:candidate];
NSDictionary *candidate_attr = [self.manager attributesOfItemAtPath:child error:nil];
if(candidate_attr.fileType == NSFileTypeDirectory)
  [stack addObject:child];

Is it legitimate to use the pointer comparison above with NSFileTypeDirectory or should I be using the compare method?  I should point out that the above code appears to be working as I expect.

A: NSDictionary fileType is an NSString. Therefore it is an object type. Therefore you really need to use isEqual: (or isEqualToString:).
if ([candidate_attr.fileType isEqualToString:NSFileTypeDirectory]) {
    // it's a directory
}

BTW - if it appears to be working with == it is merely due to some possible optimization with the strings that can't be relied upon.
Another way to check if a file is a directory is to do this:
NSString *child = [dir stringByAppendingPathComponent:candidate];
BOOL isDir = NO;
if ([self.manager fileExistsAtPath:child isDirectory:&isDir]) {
    // child exists
    if (isDir) {
        // it's a directory
    } else {
        // it's not a directory
    }
} else {
    // child does't exist
}


text:
Q: How to store data in db in array form i want to store my PHP values in db(mysql) in the form of array...
for example
$a=array{10,20,30,40};

i want to store this variable $a in to db in the array form like how it's storing in array using index.
why i want to do this because in future i may have to perform update or delete operation on the array values..
i know that it's possible to do this thing... but i don't know how to implement this..
i searched about this topic but i didn't get proper answer....
Please suggest me how to do this things...

A: Why don't use json_encode in PHP and store it on your database. It's the best way.
The array will be converted to a string and will be stored.
Retrieve the data and make use of json_decode and then start working as per your needs.
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

OUTPUT: {"a":1,"b":2,"c":3,"d":4,"e":5}

A: You should create a distinct TABLE to store this kind of data.
Consists of 2 columns, corresponding record ID and the actual data.
So, your record will be looks like
rid value
1   10
1   20
1   30
1   40
2   10
2   40
...

this way you will be able to perform update or delete operation on the array values using conventional SQL routines, as well as selecting data based on the array values.
This is how the things done oin the real world, not in PHP sandbox.
All othe answers here are plainly wrong

A: You can always serialize your array then store the result in a VARCHAR or TEXT field and after fetching you can unserialize the field.

A: I would use serialize/unserialize for this. You can use it like this:
Send to MySQL
<?php
    $a = array{10,20,30,40};
    $a = serialize($a);
    // your code here to send it to the mysql
?>

Get from MySQL
<?php
    // your code here to collect it from mysql
    $a = unserialize($mysql->str);
?>

The field in the MySQL should be TEXT or VARCHAR.
Regards
BlackBonjour


text:
Q: Showing a curve must lie on a sphere.
Let $\mathbf{r}(t)$ be a parametrisation of a curve $\mathcal{C}$ in $\mathbb{R}^3$ such that $\mathbf{r}(0) = (R, −R, R)$, where $R \in \mathbb{R}$. Suppose $\mathbf{r}(t)\neq \mathbf{0}$ and $\mathbf{r}(t)\cdot\mathbf{r'}(t) = 0$ for all points of $\mathcal{C}$. Show that any such $\mathcal{C}$ must lie on the surface of a sphere. Find the position of the sphere's centre and determine its radius.

I've tried integrating giving,
$$
\int \mathbf{r}(t)\cdot\mathbf{r'}(t)\text{dt} = \frac{\mathbf{r}(t)^2}{2} \\
\implies t_0 = \frac{\mathbf{r}(t)^2}{2}
$$
where $t_0 \in \mathbb{R}$ but I don't see how this helps. Also differentiating $||\mathbf{r}(t)-s_0||^2$ where $s_0$ is the centre of our sphere $\mathcal{S}$ should equal zero as its a constant radius but I don't see how that helps.

A: It's pretty much what you said. Let $f(t) = \mathbf{r}(t)^2 \equiv \langle \mathbf{r}(t), \mathbf{r}(t)\rangle$. Then, differentiating the function $f$ yields:
\begin{align}
f'(t) &= \mathbf{r}(t) \cdot \mathbf{r}'(t) \\
&= 0 \tag{by hypothesis}
\end{align}
Since $f'$ is identically zero, it follows that $f$ is identically equal to a constant. In other words, for all $t \in \Bbb{R}$, we must have that
\begin{align}
f(t) &= f(0) \\
&= \mathbf{r}(0) \cdot \mathbf{r}(0) \\
&= (R,-R,R) \cdot (R,-R,R) \\
&= 3R^2
\end{align}
Now, recall that $f(t) = \mathbf{r}(t) \cdot \mathbf{r}(t) = x(t)^2 + y(t)^2 + z(t)^2$ is the squared length of the position vector $\mathbf{r}(t)$. This squared length being constant for all time $t$ means that the curve lies on some sphere. In particular, it lies on the sphere centered at the origin, having radius $\sqrt{3} |R|.$

What you did by integration is also equivalent to what I wrote. To figure out what the constant $t_0$ must be, note that if you evaluate both sides at $t=0$ then you find that $t_0 = \dfrac{3R^2}{2}$.


text:
Q: GroupedItemsPage: View jumps back to start when navigating back from detailpage I developed a quite popular news app for a newspaper. Unfortunately, my users reported the following problem that I can reproduce:
The App basically consists of a GroupedItemsPage and a ItemDetailPage (and several other pages, not important here). The GroupedItemsPage shows the news grouped by category. As the user scrolls to the right, he clicks on one of the items of interests, gets redirected to the ItemDetailPage and navigates back. Back on the GroupedItemsPage the view jumps back to the first group and does not stay at the last position (group) the user has been. The exact same behaviour can be found (in my environment) when I create a new Windows Store "Grid App".
Unfortunately, I was not able to resolve this problem on my own, nor have I found some useful comments in the web. I saw several other apps who could solve this issue and others didn't. Any comment would be very much appreciated. Thank you!

A: You need to implement this by your self. When navigating from GroupedItemsPage to ItemDetailPage you need to remember the click item. Then, when you navigate back to GroupedItemsPage you need to scroll to the remembered item. You can do it by using the ScrollIntoView method on your GridView.

A: I found another, easier solution. I'd like to share it:
In the GroupedItemsPage (XAML) i added:
<common:LayoutAwarePage
NavigationCacheMode="Enabled" ...


text:
Q: Add more than 256 ip adresses on the same network I'm trying to include more than 256 devices in one network, so I made some changes:

*

*Router 1:

This is the ISP provider Router
   LAN IP  : 190.168.1.1
   DHCP    : 190.168.1.10 - 190.168.1.250
   MASK    : 255.255.0.0
   Gateway : 190.168.1.1

*

*Router 2:

This is the router I want to use for my devices:
LAN IP  : 190.168.1.2
DHCP    : 190.168.2.10 - 190.168.2.250
MASK    : 255.255.0.0
Gateway : 190.168.1.1

*

*Router (3...10):

This is the router I want to use for my clients:
LAN IP : 190.168.1.(3...10)
DHCP   : 190.168.(3...10).10 - 190.168.(3...10).250
MASK   : 255.255.0.0
Gateway: 190.168.1.1

Why isn't this working as one ?

A: So, this sould work:

*

*Router 1:

ISP provider Router
   LAN IP  : 10.0.0.1
   DHCP    : 190.168.1.10 - 190.168.1.250
   MASK    : 255.0.0.0
   Gateway : 10.0.0.1

*

*Router 2:

Personal devices:
LAN IP  : 10.0.0.2
DHCP    : 10.0.1.10 - 10.0.1.250
MASK    : 255.0.0.0
Gateway : 10.0.0.1

*

*Router (3...10):

Clients devices
LAN IP : 10.0.0.(3...10)
DHCP   : 10.0.(3...10).10 - 10.0.(3...10).250
MASK   : 255.0.0.0
Gateway: 10.0.0.1

A: So, first of all: Classful networking is dead and has been for a rather long time. Just forget about it. Make sure you stick to private address ranges or you risk breakage when address conflicts arise. 190.168.x.x is not a private address range.
"One network" kind of implies that all devices are on the same broadcast domain. That means no additional routers. No isolation either. Is that really what you want? From your description this doesn't appear to be the case. Either way, just set an appropriate network mask (like /16) and DHCP range on the one router and you're done.
It appears you actually want separate networks that may or may not be able to communicate with each other. This is easily accomplished by using non-NAT routing and appropriate routes on all routers involved. Routers can also firewall traffic as required. The networks (as defined by the network address and network mask) must not overlap. The broadcast domains must be fully separated by routers, otherwise you'll get conflicts with multiple DHCP servers on one network.


text:
Q: Closure obtained from reflection cannot properly address input parameters A hardcore Swift question I guess. Given this trivial code:
struct Container {
    let closure: (Int) -> Void
}

let container = Container { param in
    print("\(param)")
}

One can assume calling container.closure(42) will print out 42, which is true.
However, if this same closure is retrieved from the container's Mirror:
let mirror = Mirror(reflecting: container)
let closure = mirror.children
    .first(where: { $0.label == "closure" })!
    .value as! ((Int) -> Void)

... then calling closure(42) distorts the parameter's value, and it prints out 6166589480.
The same thing happens if you use String instead of Int, and I assume with other types too. If I pass a reference to an object, expectedly that reference get messed up too and I get EXC_BAD_ACCESS when trying to access the object.
Is this a bug in Swift / Xcode 13.2 or am I missing something?


text:
Q: Is is possible to download software with IP packets sent from another computer? I was wondering if a computer was connected to the internet but needed an application downloaded, Instead of physically going to the computer and downloading the software, could another computer remotely send IP packets to send the software on to it?

A: This can be done on any OS by listening to sockets, where another computer would send the information about what software to download and upon receiving this information, the host would automatically download the software.
You can also consider Remote management software on Windows or SSH on Unix-based systems.
To send the software directly onto it can be done by combining sockets with FTP apps and such, however, it is not really efficient.


text:
Q: Why is Cookie available in Request immediately after setting using Response? In pageload, if you do Response.Cookies.Add(..., immediately in the next line, you can access that cookie via Request.Cookies(...
I know that under the covers, the cookie is added to Request.Cookies by .net, but the original request never had that cookie.
If what I'm saying is correct, why is it this way?  Shouldn't the cookie be available in the following request?  Shouldn't the immediate access to Request.Cookies(... be null?

A: You're right, ASP.NET does do that behind the scenes:

After you add a cookie by using the
  HttpResponse.Cookies collection, the
  cookie is immediately available in the
  HttpRequest.Cookies collection, even
  if the response has not been sent to
  the client.

-- HttpRequest.Cookies page on MSDN
Why is it like that?  At a guess, it's because that's how developers expect it to work.


text:
Q: Absolute zero and Heisenberg uncertainty principle I got to read Volume I of Feynmann's lectures. It said that at absolute zero, molecular motion doesn't cease at all, because if that happens, we will be able to make precise determination of position and momentum of the atom. We do know that Heisenberg uncertainty principle holds for microscopic particles in motion. But what then is wrong to consider that all molecular motion ceases at absolute zero? In other words, does the uncertainty principle not hold when there is no motion?
Need some help!

A: The uncertainty principle is a fundamental property of quantum systems, and is not a statement about observational success. No particle either free or in crystal can have zero momentum otherwise a nonsensical infinity is required for the standard deviation of position $\Delta x$, in the uncertainty principle $\Delta x \Delta p \geq \hbar / 2$.
$0 \cdot \infty$ is undefined, so breaks the principle if the product is interpreted as zero. More likely the product should be interpreted as also undefinable, in which case the principle itself becomes undefinable. So all particles must move at least to some extent at all times or the uncertainty principle itself breaks down.

A: Motion does not cease at absolute zero if the system you are looking at has a zero point energy.
In many systems, e.g. crystals, at low temperatures the atoms/molecules behave as harmonic oscillators, and the energy of a harmonic oscillator cannot be reduced to zero: there is always some minimum energy called the zero point energy. This means that at absolute zero the atoms in a crystal will not be stationary. There will be a small vibration corresponding to the zero point energy. This is most obvious for light atoms like Helium where the zero point energy is enough to keep the system liquid, so even at absolute zero Helium will not solidify unless it's put under pressure.
The situation is different for a free particle. In that case, at absolute zero the momentum is zero but then we have no knowledge about where the particle is (i.e. $\Delta x = \infty$). If we want to measure where the particle is we have to put some energy in, but then of course the system is no longer at absolute zero and the momentum is now non-zero.


text:
Q: Gesture triggers exception in subview of UIScrollView Novice iOS programmer here, so sorry if I'm missing something easy, but...
I have a UIViewController class called LVSTSPMasterViewController whose view was built in IB. The view contains a UIScrollView (added in IB) and that scroll view has a subview of type LVSTSPView. LVSTSPView has a controller of type LVSTSPViewController.
I want to respond to touches in the LVSTSPView, so I added gesture recognizers to LVSTSPViewController.m. When I execute the gesture (e.g., do a long press), the code crashes with message "EXC_BAD_ACCESS (code=1, address=...)" in main.m.
Relevant code:
In LVSAppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    // Get pointer to app bundle
    NSBundle *appBundle = [NSBundle mainBundle];

    // Get xib file
    LVSTSPMasterViewController *tspmvc = [[LVSTSPMasterViewController alloc] initWithNibName:@"LVSTSPMasterViewController" bundle:appBundle];

    self.window.rootViewController = tspmvc;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

In LVSMasterViewController.m:
@interface LVSTSPMasterViewController () <UIScrollViewDelegate>

// IBOutlet declarations

@property (nonatomic, weak) IBOutlet UIScrollView *TSPScrollView;

// Pointers for convenience

@property (strong, nonatomic) LVSTSPView *TSPView;

@end

@implementation LVSTSPMasterViewController
- (void)viewDidLoad
{
    // Create LVSTSPViewController
    LVSTSPViewController *tspvc = [[LVSTSPViewController alloc] init];

    // Set up pointer to LVSTSPView
    self.TSPView = (LVSTSPView *)tspvc.view;

    // Set frame of LVSTSPView
    self.TSPView.frame = self.TSPScrollView.bounds;

    // Set tspvc's view as subview of TSPScrollView
    [self.TSPScrollView addSubview:tspvc.view];

    // Set up scroll view
    self.TSPScrollView.pagingEnabled = NO;
    self.TSPScrollView.contentSize = self.TSPView.frame.size;
    self.TSPScrollView.minimumZoomScale = 1.0;
    self.TSPScrollView.maximumZoomScale = 3.0;

    // Set scroll view's delegate property
    self.TSPScrollView.delegate = self;
}

In LVSTSPViewController.m:
- (void)loadView
{
    // Create view
    LVSTSPView *view = [[LVSTSPView alloc] initWithFrame:CGRectZero];
    self.view = view;

    // Long-press recognizer
    UILongPressGestureRecognizer *pressRecognizer =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.view addGestureRecognizer:pressRecognizer];
}

- (void)longPress:(UIGestureRecognizer *)gr
{
    NSLog(@"longPress:");

}

One other note: If I set up the gesture recognizer in viewDidLoad: in LVSTSPMasterViewController.m, like so --
UILongPressGestureRecognizer *pressRecognizer =
    [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.TSPView addGestureRecognizer:pressRecognizer];

-- (and of course add longPress: to LVSTSPMasterViewController.m), then it works. But this doesn't seem like the right approach since the LVSTSPMasterViewController is not the view controller for LVSTSPView.
Any help will be appreciated!

A: Your view controller LVSTSPViewController is not retained anywhere or in other words your master view controller needs to retain it.
In LVSMasterViewController.m, change your code to
@implementation LVSTSPMasterViewController
{
   LVSTSPViewController *tspvc;//creates strong reference to self(LVSTSPMasterViewController)
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view from its nib.
  tspvc = [[LVSTSPViewController alloc] init];

  // Set up pointer to LVSTSPView
  self.TSPView = (LVSTSPView *)tspvc.view;

  // Set frame of LVSTSPView
  self.TSPView.frame = self.TSPScrollView.bounds;

  // Set tspvc's view as subview of TSPScrollView
  [self.TSPScrollView addSubview:tspvc.view];

  // Set up scroll view
  self.TSPScrollView.pagingEnabled = NO;
  self.TSPScrollView.contentSize = self.TSPView.frame.size;
  self.TSPScrollView.minimumZoomScale = 1.0;
  self.TSPScrollView.maximumZoomScale = 3.0;

  // Set scroll view's delegate property
  self.TSPScrollView.delegate = self;
}

Also always call [super viewDidLoad] first in your viewDidLoad method. I would suggest to read more about view and view controller in the apple documentation. You necessarily do not need a view controller with every view. It all depends on your specific case. One view controller can manage multiple views.


text:
Q: Работа с таймерами в приложении Xamarin.Forms В приложении Xamarin.Forms необходимо реализовать таймер, срабатывающий через заданный интервал времени. При срабатывании таймера должно появляться диалоговое окно-сообщение и срабатывать звуковой сигнал.
Попробовал сделать двумя способами:
1) Использовать метод Device.StartTimer(TimeSpan interval, Func callback);
2) Использовать симуляцию таймера с помощью временной задержки Task.Delay() в вызванном асинхронно методе.
Проблема заключается в том, что таймер существует только до того момента, пока пользователь не перейдет со страницы мобильного приложения, на котором вызывается таймер, на другую страницу. При переходе на другую страницу таймер уничтожается.
Прошу подсказать как сделать таймер, который будет работать при переходе на другую страницу приложения до полного закрытия приложения. Попробовал реализовать таймер внутри App.xaml.cs, но в таком случае не получается вызвать диалоговое окно с сообщением DisplayAlert()
Вот как сделано сейчас:
private async void AlarmTimer(string nameRecipe, string nameTimer, int interval)
{
    await Task.Delay(interval);
    DependencyService.Get<IAudio>().PlayAudioFile("alarm.mp3");
    await DisplayAlert("Таймер рецепта " + nameRecipe, "Cработал таймер " + nameTimer + " в " + DateTime.Now.ToString(), "Закрыть");
}

Установка таймера:
AlarmTimer(SelectedRecipe.Name, recipeTiming.Description, 5000);

Таймер работает если приложение находится на странице с таймером или странице, вызванной из неё. Но перестает работать при возврате на корневую страницу или предыдущую той, с которой идет вызов.
Думаю проблему бы решило размещение метода таймера на корневой странице и вызов его с вложенной страницы. Не могу только понять как в Xamarin.Forms правильно сделать такой вызов. Прошу подсказать

A: Пример решения через Device.StartTimer
Устройство вызывает Func callback каждые 5мс
    Device.StartTimer(TimeSpan.FromMilliseconds(5), OnTimerTick);

Реализация Func callback:
    private bool OnTimerTick()
    {
        bool alive = true;
        //Делаем что надо
        return alive;
    }

OnTimerTick - возвращает true - таймер продолжает работу, возвращает false - заканчивает работу.
Если ты вызываешь со страницы с таймером новую страницу, например:
    await Navigation.PushAsync(new SecondPage());

Таймер продолжает работу. Если нужно его отключать, делаешь это в OnAppearing и не забываешь запускать таймер при возврате на страницу в OnDisappearing().
При навигации, можно все таймеры оставить на корневой странице.
Малость о навигации https://metanit.com/sharp/xamarin/5.1.php
Вариант 2 - асинхронный метод While(timerEnable) и Task.Delay
async public void DrawTimer(int interval)
{

    if (await DisplayAlert("Подтвердите", "Запустить таймер?", "Да", "Нет"))
    {
        timerEnable = true;
        while (timerEnable)
        {
            DependencyService.Get<IAudio>().PlayAudioFile("alarm.mp3");
            await DisplayAlert("Таймер рецепта " + nameRecipe, "Cработал таймер " + nameTimer + " в " + DateTime.Now.ToString(), "Закрыть");
            //что-то делаем
            await Task.Delay(interval);
        }
    }
}


text:
Q: React Native highlight items and return indexes alert I have json and i render items with flatlist component. I have component "TouchableOpacity" and I need to highlight some items from flatlist. After highlighting I need display choosen items IDs to alert after I press button. Can someone help me with this issue?
 export default class Grid extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectId: [],
      countIds: 0,
    }
  }

  renderItem = ({item}) => {
    return(
        <View style={styles.container}>
          <TouchableOpacity onPress={() => this.highlightItem(item.id)} style={this.state.selectId === item.id ? styles.selected : null}>
            <View style={styles.viewContainer}>
              <Image source={{uri: item.imageUrl}} style={styles.imageContainer}/>
              <Text>{item.name}</Text>
            </View>
          </TouchableOpacity>
        </View>
    )
  }

  highlightItem = (id) => {
    console.log(id)
    this.setState({
      selectId: [...this.state.selectId, " " + id],
      countIds: this.state.selectId.length + 1
    })
  }

  selectedItems = () => {
    Alert.alert(
      'Data alert',
      `Count of items: ${this.state.countIds} \nIDs items selected: ${this.state.selectId}`,
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
        },
        {
          text: 'OK',
          onPress: () => console.log('OK Pressed')
        },
      ],
      {cancelable: false},
    )
  }

  render() {
    return(
      <View>
          <FlatList
            data={dataSource}
            extraData={this.state.selectId}
            renderItem={this.renderItem}
            keyExtractor={(item, index) => index.toString()}
            numColumns={columnNumber}
            ListFooterComponent={this.renderButton}
          />
      </View>
    )
  }
}


text:
Q: How to disable MyEclipse visual HTML designer My computer lags for several seconds when I open an HTML file in MyEclipse, or make a major change to a file that's already open.  I suspect that the WYSIWYG part of the visual HTML designer is responsible; is there a way to turn that off but retain the color-coded text editor/formatter?  I also don't care about the "preview" feature, if that makes a difference.

A: I have faced the same issue. Go to Window > Preferences > General > Editors > File Associations and pick the file extension for which you would like to disable/enable the designer. Hope that works for you.

A: Make Default MyEclipse Jsp Editor for opening jsp files without Visual Designer
Go to
WIndow > Prefs > General > Text Editors > File Associations
1-Click on File Associations  -
2-select file type for whom you want to change Editor-
3-Select Myeclipse Jsp Editor as default
Same way you can adjust any files types Editors
adjust the default editor for the file types like .jsp, .jspf, .jspx and so on to use the non-visual editor.


text:
Q: inserting node in yaml with ruamel I would like to have printed the following layout:

extra:
  identifiers:
      biotools:
          - http://bio.tools/abyss

I'm using this code to add nodes:

yaml_file_content['extra']['identifiers'] = {}
yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']

But, instead, I'm getting this output, that encapsulates the tool in []:

extra:
  identifiers:
     biotools: ['- http://bio.tools/abyss']

I have tried other combinations but didn't work?

A: Once you have loaded a YAML file it's no longer "yaml"; it's now a Python data structure, and the contents of the biotools key is a list:
>>> import ruamel.yaml as yaml
>>> data = yaml.load(open('data.yml'))
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss']

Like any other Python list, you can append to it:
>>> data['extra']['identifiers']['biotools'].append('http://bio.tools/anothertool')
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss', 'http://bio.tools/anothertool']

And if you print out the data structure you get valid YAML:
>>> print( yaml.dump(data))
extra:
  identifiers:
    biotools: [http://bio.tools/abyss, http://bio.tools/anothertool]

Of course, if for some reason you don't like that list representation you can also get the syntactically equivalent:
>>> print( yaml.dump(data, default_flow_style=False))
extra:
  identifiers:
    biotools:
    - http://bio.tools/abyss
    - http://bio.tools/anothertool

A: The dash in - http://bio.tools/abyss indicates a sequence element and is added on output if you dump a Python list in block style.
So instead of doing:
yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']

you should be doing:
yaml_file_content['extra']['identifiers']['biotools'] = ['http://bio.tools/abyss']

and then force the output of all composite elements in block style using:
yaml.default_flow_style = False

If you want finer grained control, create a ruamel.yaml.comments.CommentedSeq instance:
tmp = ruamel.yaml.comments.CommentedSeq(['http://bio.tools/abyss'])
tmp.fa.set_block_style()
yaml_file_content['extra']['identifiers']['biotools'] = tmp


text:
Q: Can use input only one time then it goes null I am doing practice of JavaScript and now having problem in printing. If i write "listaa" to input field and press Submit button, it lists few words. Then I write something else and try "listaa" again, it is not working. I tried to first make it blank with document.getElementById("listaus").innerHTML = "" but it's not working.
Consolelog says TypeError: document.getElementById(...) is null and tell me it is line 42, where is the first document.getElementById in case you write "listaa".
How can I solve this?
My HTML:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Laskin</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="/css/style.css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <audio id="myAudio">
  <source src="americano.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
  </audio>

Nimesi: <input type="text" id="kakki" name="kakki"/>

    <button onclick="takki()">Submit</button>

And JavaScript
document.getElementById("kakki").value
console.log(kakki.value)

var musiikki = document.getElementById("myAudio");

function takki(){
    let current ="kakki"

    var txt = ""
    let array = ['Google', 'joku', 'asdasd', 'asdasd']

    if (kakki.value == "moi"){
        document.getElementById("result1").innerHTML = kakki.value
        document.getElementById("result2").innerHTML = kakki.value
    }
    else if(kakki.value == "Pasi"){
        document.getElementById("result1").innerHTML = "En tunne Pasia, mutta Matin tunnen."
    }
    else if(kakki.value == "Matti"){
        console.log("Matti ei ole paikalla")
    }
    else if(kakki.value == "Reiska"){
        var i;
        for (i = 1; i < 101; i++)
        console.log("Reijo" + [i]);
    }
    else if(kakki.value == "aloitamusiikki"){
        musiikki.play();
    }
    else if(kakki.value == "lopetamusiikki"){
        musiikki.pause();
    }
    else if(kakki.value == "google"){
        document.getElementById("google").innerHTML = "Siirrytäänkö Googleen?"
        document.getElementById("google").href = "https://www.w3schools.com";
        document.getElementById("google").target = "_blank";
    }
    else if(kakki.value == "listaa"){
        array.forEach(myFunction);
        document.getElementById("listaus").innerHTML = ""
        document.getElementById("listaus").innerHTML = txt;

        function myFunction(value, index, array) {
        txt = txt + value + "
";
        }
    }

}

A: I would say this is the issue:

You are overriding #result1 before so #listaus does not exist afterwards.

A: You forgett an closing tag

Try with

A: It is not logical
 document.getElementById("kakki").value

out of the function takki() , So insert it into the function
and Check all ends of tags like :


text:
Q: Setting up an Access Point, Raspberry Pi, and Laptop to serve a website in a classroom. "The internet in a suitcase" Our trainers experience bad internet connections at some schools. I would like to provide them with a "mobile" (as in take it on the train) version of our platform running on a laptop, which the students can connect to directly via a private WiFi network. "The internet in a suitcase".
Equipment:

*

*Access Point
(https://store.ui.com/collections/unifi-network-wireless/products/unifi-ac-pro)

*Raspberry Pi 4

*Laptop running Ubuntu serving the website

Past Progress:
As a proof of concept, I was able to serve the platform on ubuntu with the wifi set to AP mode - this would not be sufficient in a real-world setting because of the range, and simultaneous connections limitations.
Help:
I am generally looking to be pointed in the right direction with some keywords I might be missing, or told "no, none of this will work" - the crux of it is:
What do I need to do with the Raspberry  Pi / Laptop / Access Point to allow users connected to the access point to access the website via their browser i.e type in portable.xyz.com in the address bar of their smartphone, get served a website running on the laptop?
My Guesstimate:

*

*On the Raspberry Pi

*

*set up a DHCP server because the AP doesn't have one.

*set up a DNS server so that portable.xyz.com would point somewhere.

*set up the controller software for the Access Point.

*On the laptop

*

*Set up the server and make sure it's serving on port:443/80 (there are other services on other ports so set them up too).

*? I am not sure how the Raspberry Pi knows that there is a server on the laptop.

*

*Is it the relationship between the DHCP IP address configuration and the laptop's IP address (which I would have to configure as fixed)? The DNS setting for portable.xyz.com would then have A records pointing to the laptop's fixed IP?

Other info:
We expect the typical load to be 15 - 100 simultaneous connections, on a range of hardware (tablets,  cellphones, laptops).
The platform is not incredibly data-intensive (mostly text and images), but there is a lot of traffic flying around i.e. collaborative text editors, notifications ...etc
Dismissing the "No internet connection available on this wireless network" notification on smartphones is not a problem.

A: That all sounds like a perfectly sensible solution to your problem, and you've more or less answered your own questions correctly already.
Specifically:

I am not sure how the Raspberry Pi knows that there is a server on the
laptop.

The raspberry pi doesn't need to "know" anything about the laptop. Clients accessing the website will do so in a browser, by putting in the hostname portable.xyz.com which you will resolve using the DNS server running on the pi in your solution to the IP address of the laptop, which will then serve the content based on its web server configuration. This leads to your next question:

Is it the relationship between the DHCP IP address configuration and
the laptop's IP address (which I would have to configure as fixed)?
The DNS setting for portable.xyz.com would then have A records
pointing to the laptop's fixed IP?

Yes, the easiest thing to do in this scenario would be to configure the laptop with a fixed IP (which you can do either via a DHCP reservation or by configuring a fixed IP manually on the laptop), and adding a DNS record on the pi for the laptop. One solution to this might be to just use the laptop's hostname to connect to the website, as some dhcp/dns servers will automatically register reserved hosts in DNS (e.g. dnsmasq)
As an aside, two points:

*

*What we've described above is basically a build-your-own-WiFi-router setup but using a separate access point and router (the router in this case is the raspberry pi). You might consider simplifying the setup to just purchasing an inexpensive WiFi-enabled router to handle all of the above instead.

*You may have a reason for using a separate laptop to host the web content, but an alternative would be to serve it also from the raspberry pi (if you do end up using one).


text:
Q: How can I create a secure application-database connection? Introduction :
I have a desktop application (.net framework 4.8.2 winform) and successfully connected to MSSQL. But I am afraid that the connection string in the application will be decompiled because it contains all the confidential information of the database. I will use the application I made for a private school project (for students), so I will distribute it.
What I want :
I want to extract data securely from my MSSQL database by connecting to the database via a desktop program.
What I have :
I have a website and hosting provider.
I've seen similar questions to my question on Stackoverflow, but unfortunately, the questions could not be answered.
In short, what should I do? I will continue my research according to the answer given because unfortunately, I am stuck... Thank you.


text:
Q: Can I run an instance of python with a script saved as a variable Can I run a separate instance of python that runs a script that is saved as a variable
main.py
script = "print('hello')"

What would I have to add to main.py to make it run another instance of python with it running the variable 'script'


text:
Q: How can I block certain urls from my website In my website, I load some files and for example one of them is index.js
If I type in google https://mywebsite.com/index.js and then it shows the code of that javascript file.
How can I block this kind of actions and for example show a 404 page?
Thanks


text:
Q: How to rsync changes and reload remote service but only type SSH password once I would like to sync local changes to a file to a remote server and then reload the service that uses that file. For example:
# Sync file to remote server
rsync -avzhe ssh --rsync-path "sudo rsync" \
    /etc/haproxy/haproxy.cfg vagrant@192.168.50.31:/etc/haproxy/

# Reload remote service
ssh vagrant@192.168.50.31 "sudo /etc/init.d/haproxy reload"

Doing it this way forces me to enter the SSH user's password twice. Is there any way to do this better, so that I may only have to enter the password once?

A: You can use ControlMaster, ControlPath and ControlPersist ssh options to make use of ssh connection sharing feature. Using these makes ssh keep the connection specified amount of seconds(or forever with 0) and any consequent ssh sessions will connect without requiring authentication because they will use the already established connection.
Example:
put this in .ssh/config
Host *
    ControlMaster auto
    ControlPath /tmp/ssh_shared_%h_%p_%r
    ControlPersist 60

this will keep the connection for 60 seconds. Durring this time you wil not be asked for password.

A: Run ssh-keygen:
ssh > ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): abc.key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in abc.key.
Your public key has been saved in abc.key.pub.
The key fingerprint is:
9e:e2:46:c0:9a:ac:fe:fb:ea:ec:ee:66:00:39:91:f8 root@domain.tld
The key's randomart image is:
+--[ RSA 2048]----+
|..               |
|+                |
| + .             |
|+ E o            |
|.o o .  S        |
| .+   .. .       |
| ..  .. o        |
|. .o ...         |
|..OX+o.          |
+-----------------+

Here I've omit passphrase twice by pressing Enter. Now I have abc.key and abc.key.pub files. Let's make them readable by me only:
chmod 600 abc.key*

Open the abc.key.pub:
ssh > cat abc.key.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDppADcp53HZ4KF7EsNcfV1qM4WtuYEeHWjAXsFqJwHd7loyKYnORHtAMtd78+cSHTiAycLeNqX9xRh/lPlhifeovxJ8th6c4W7cXNWalmz6q+RkDE8ZznmcNSvrMToLm7oivdsBDiPIBbiOtunKRQ2TsNZ72RJuC3RlrmUakWp9RcrQMFAvyxkzJYmm4fTSozosA2/NaHn0qIm/5Ed9I5BQ9IzRQLgzsXCtBTQY83aBcYLk+AzhQiM45AV1mOGzYAkgXu6Uo3P9jDxi2DE1priW8SnKEXhrTEmNDAZDkDRAz1Go/lGnENslqLZ0URs5spGtHGhcWt9DmSjVGbbGvpP user@domain.tld

Copy the whole line and paste it to the /home/user/.ssh/authorized_keys on the remote host.
Now try:
ssh -i /path/abc.key user@remote.host

Yep, now you have been logged in without keyboard authentication at all. You can do that trick everywhere you  have used ssh.


text:
Q: Mapstruct AnnotationProcessor with IntelliJ and Gradle I am trying to get the Mapstruct annotation processor to work in IntelliJ in a Gradle project.
Ideally, I would expect for all configuration to be in the gradle-file and that anyone could just import the project into IntelliJ and get a complete setup without having to set any preferences manually.
But I am okay with compromises on that.
I am using IntelliJ 2018.3 and Gradle 5.0 with Java 11 (i.e. the latest and greatest). The Mapstruct version is 1.2.0.FINAL.
What I have done:

*

*Configured the Mapstruct annotation processor in my build.gradle:
compile "org.mapstruct:mapstruct-jdk8:${mapstruct_version}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"

*Selected "Delegate IDE build/run actions to Gradle" in the Preferences under "Build, Execution, Deployment -> Build Tools -> Gradle -> Runner"
In the directory build/classes/java/main/com/myapp/mypackage/mapper/ I see a MyMapperImpl.class and a MyMapperImpl.java, so code generation seems to work.
Now I would expect that when I select my annotated abstract MyMapper class and press ctrlH, that the generated MyMapperImpl appears in the hierarchy view.
If I manually mark build/classes/java/main/ as a "generated sources" directory (which I really don't want to have to do, see above), the class still does not appear in the hierarchy. But the source code is marked with a lot of errors, as no classes from my project are found, apparently.
Needless to say: I can flawlessly run tests that use the mapper, both from IntelliJ and the command line.

A: Use this, my team is also using mapstruct and we use it in our
build.gradle, you will need to bring the idea plugin for gradle as well
def generatedSources = "$buildDir/generated"
def generatedOutputDir = file("$generatedSources")

/*
 create generated .java files in different folder than classes
 In IntelliJ 2016.3.x: Enable Annotation Processing, then set generated sources,
 relative to module output dir, at path '../../generated'
 */
compileJava {
    doFirst {
        generatedOutputDir.exists() || generatedOutputDir.mkdirs()
        options.compilerArgs = [
                '-s', "${generatedSources}"
        ]
    }
}

idea {
    module {
        downloadSources = true
        // tell intellij where to find generated sources
        sourceDirs += generatedOutputDir
    }
}

You will able to run your code even without Gradle runner with this workaround


text:
Q: Gulp 4 sass forget to signal async completion I am trying to build my sass with gulp sass and i get the error:
The following tasks did not complete: build, gulpSass
Did you forget to signal async completion?
function sass() {
  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(buildDir));
}

gulp.task('build', gulp.series(
  clean,
  sass,
  html,
  images
));

What is the problem?

A: Although I cannot see the rest of your code, the problem most likely has to do with a naming collission. I assume you are aliasing the gulp plugin as sass. If you did this then there are two variables using the same name.
var sass = require('gulp-sass');
function sass() { ... }

The latter overrides the first. So when you call gulp.task('build', gulp.series(...,sass,...)); It's assuming you're calling the last function. Which has no return statement.
Easily solved by either renaming the alias, to something like var nodesass = require('gulp-sass'); or renaming the function.

A: series or gulp.parallel, you have to use async keyword before your function or else you can declare your function with callback as given below.
function sass(cb) {
  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(buildDir));
cb();
}

Use this logic in your other functions as well.


text:
Q: Using a foreach loop in LaTeX glossary to create a list of acronyms I would like to use a foreach loop to create a list of acronyms in a LaTeX document. I expect the code should look something like this but it does not work (it nearly works):
\documentclass{article}
\usepackage{pgffor}
\usepackage[acronym]{glossaries}

\makeglossaries

\foreach \x/\y in {
DOC/document,
ACR/acronym,
VV/very very,
}
{\newacronym{\x}{\x}{\y}}

\begin{document}

\section{Document Body}

A \gls{DOC} with lots of unexplained \glspl{ACR} is \gls{VV} annoying.

\printglossary[type=\acronymtype]

\end{document}

For reference, here is an example of a working foreach loop and acronym glossary:
\documentclass{article}
\usepackage{pgffor}
\usepackage[acronym]{glossaries}

\makeglossaries

\newacronym{DOC}{DOC}{document}
\newacronym{ACR}{ACR}{acronym}
\newacronym{VV}{VV}{very very}

\begin{document}

\section{Document Body}

A \gls{DOC} with lots of unexplained \glspl{ACR} is \gls{VV} annoying.

\section{Foreach Loop}

\foreach \x/\y in {
DOC/document,
ACR/acronym,
VV/very very,
}
{\textbf{\x} \y\\}

\printglossary[type=\acronymtype]

\end{document}

A: You would need to expand \x and \y before you hand them off to \newacronym.
In this case, it would be as simple as
\foreach \x/\y in {
  DOC/document,
  ACR/acronym,
  VV/very very%
}{%
  \edef\z{\noexpand\newacronym{\expandonce\x}{\expandonce\x}{\expandonce\y}}%
  \z
}

The name of \z doesn't matter (it even could be \x or \y) since it is forgotten after the loop.
Be careful with pgffor however, since its body is grouped, local assignments will not survive. The glossaries package evidently does them globally, though.

With LaTeX3 you can use \exp_args:Nooo which would expand each of the three arguments once before using them with \newacronym:
\ExplSyntaxOn
\NewDocumentCommand\MakeAcronym{ m m }{
  \exp_args:Nooo \newacronym#1#1#2
}
\ExplSyntaxOff

\foreach \x/\y in {
  DOC/document,
  ACR/acronym,
  VV/very very%
}{%
  \MakeAcronym{\x}{\y}%
}

If you don't have to use the full power of \foreach (mainly calculating values and remembering others) you can use the .list handler which would still allow the ... syntax (not that it is really applicable here).
This does expand the values before it is handed off to /GJ/new acros which is why you simply can (and must) use #1 and #2 then.
Code
\documentclass{article}
\usepackage{pgffor}
\usepackage[acronym]{glossaries}

\makeglossaries

\pgfkeys{
  GJ/new acros/.code args={#1/#2}{%
    \newacronym{#1}{#1}{#2}%
  },
  GJ/new acros/.list={
    DOC/document,
    ACR/acronym,
    VV/very very%
  }
}

% \ExplSyntaxOn
% \NewDocumentCommand\MakeAcronym{ m m }{
%   \exp_args:Nooo \newacronym#1#1#2
% }
% \ExplSyntaxOff

% \foreach \x/\y in {
%   DOC/document,
%   ACR/acronym,
%   VV/very very%
% }{%
%   \MakeAcronym{\x}{\y}%
% }

% \foreach \x/\y in {
%   DOC/document,
%   ACR/acronym,
%   VV/very very%
% }{%
%   \edef\z{\noexpand\newacronym{\expandonce\x}{\expandonce\x}{\expandonce\y}}%
%   \z
% }

\begin{document}
\section{Document Body}
A \gls{DOC} with lots of unexplained \glspl{ACR} is \gls{VV} annoying.
\printglossary[type=\acronymtype]
\end{document}

Output


text:
Q: Powershell start-job formatting issue This is my first time using start-jobs, it is not working properly, am I using it wrong?
$dagName = "dag Name";
$dagObject = Get-DatabaseAvailabilityGroup -Identity $dagName;

$servers = New-Object System.Collections.ArrayList;
foreach($server in $dagObject.Servers)
{
    $servers.Add($server) | Out-Null;
}

$getExchangeServers = @();
$getMailboxDatabases = @();
$getMailboxDatabasesWithStatus = @();

Start-Job -ScriptBlock {foreach ($server in $servers) {$getExchangeServers += get-exchangeserver $server;}}
Start-Job -ScriptBlock {foreach ($server in $servers) {$getMailboxDatabases += Get-MailboxDatabase -Server $server;}}
Start-Job -ScriptBlock {foreach ($server in $servers) {$getMailboxDatabasesWithStatus += Get-MailboxDatabase -Server $server -Status;}}


text:
Q: Win+Shift+Arrow keys stretches my window across both monitors instead of moving the window to the other monitor? (Windows 10) (Somehow I wasn't able to find any solution by googling, so I'm asking here.)
Win + Shift + Right / Left Arrow used to work correctly for me for a long time to swap my window to my second monitor quickly, but since a few months ago it started stretching the window across both monitors, making the shortcut useless for me. I can still manually drag a window with the mouse, but for my workflow I need to be able to switch back and forth fast. The problem happens with any application that has a maximized window.
I have a laptop with Windows 10 and a XP-Pen drawing tablet as my second monitor. Disconnecting and reconnecting the monitor or trying other monitors still keeps the problem.

A: So NVIDIA does seem to be the common link here. However, instead of Quadro View which another person had responded above was the NVIDIA feature causing the issue for them. For me, it was NVIDIA Desktop Manager. I noticed the exact same issue of the Win + Shift + Right / Left shortcut stretching a window across all monitors instead of moving it, the exact same day I enabled NVIDIA desktop manager. As soon as I disabled it using the similar method the user who responded regarding Quadro View used, the issue was resolved. This process was to Right click, select NVIDIA Desktop Manager and select to disable it, and this solved the issue right away.

A: It was happening to me too for the last 2 weeks. Today I just tried to turn off the Quadro view in NVIDIA Graphics. Could you please try it if you have the same graphics too?
Right-click on the desktop and select Quadro View

And then keep it disabled as shown in the screenshot:


text:
Q: Binary parsing in Swift like Preon in Java I need to parse binary data using Swift. Can anybody tell me how to implement something like the Java Preon library in Swift?
QByte, here is more information....
I am developing an application to program radios. The program must read and write data from a variety of radios and, of course, each radio manufacturer encodes the data in a different way. The program must be able to 1. Read the data over a serial port using the protocol used by the radio, 2. Parse the data. There needs to be a language to specify the data format for a particular radio , 3. Decode the data and populate objects with the parsed and decoded data, 4. Allow the user to edit the data, 5. Encode the modified data back to the data format needed by the radio, 6. Write the changed configuration data back to the radio. The parsing code needs to perform items 2, 3, and 5. I know how to do the other items.
At first I thought Preon could perform items 2, 3, and 5. I have just found that Preon is unable to encode the data. Since Preon is unsupported, I now doubt Preon will be usable.
Because the data format is different for each manufacturer, the data is represented in a variety of ways. One radio simply encodes the data as ASCII characters. So a frequency of 144MHz might be transmitted as ASCII characters '144000000'. A Boolean value would be expressed as an ASCII 0 or 1. Other radios encode the data in bits. Numbers are expressed as 16 bit unsigned shorts, 32 bit unsigned integers,  or BCD numbers. Boolean values use 1 bit.
I could hard code the routines to parse, decode, and encode, however this is difficult to document and modify and it makes it difficult to add new radios.
So, does this explanation help you understand what I am trying to do?
Does anyone know of any libraries that can be used with Swift to accomplish these tasks?


text:
Q: How do I convert this function from C to C#? I am halfway done with converting this function from c to c# but I am totally lost as to what the middle computational line does.
            y -= m < 3;

C Version
 int DayOfWeek(int d, int m, int y)
        {
            static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
            y -= m < 3;
            return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
        }

C# Version
 int DayOfWeek(int d, int m, int y)
        {
            int[] t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
            y -= m < 3;
            return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
        }

1) I understand y -= m is equivalent to y = y - m but what does "<" do? Is it an expression?
2) How do I convert the rest of this to c#?
Thank you everyone, for clarification this is for a degree program.

A: y -= (m < 3) ? 1 : 0;

or more readibly
if (m < 3) y -= 1;

or even
if (m < 3) --y;

It's some C code using the fact that conditionals return 1 or 0 as a value. Fix as shown.
Edit: I now see the comments saying this code is obfuscated. I guess I'm such an old C hat I found it immediately obvious on reading it, not that I recommend writing it that way.
Or we can do this thing the really ovbious way:
int DayOfWeek(int d, int m, int y) => (new DateTime(y, m, d)).DayOfWeek;

A: I am unfamiliar with C# syntax, but in C
m < 3

evaluates to 0 or 1. The line
y -= m < 3;

is equivalent to
if(m < 3) { y--; }

A: int DayOfWeek(int d, int m, int y)
{
   var dt = new DateTime(y,m,d);
   return (int) dt.DayOfWeek;
}


text:
Q: Does picking a language to learn really matter? They all use similar techniques to solve problems? College student about to major in CS. Just want to know if it really matter what language you learn first?
Seems to me CS and the nature of our work is about problem solving. Different language seems to differ in syntax, libraries you can use, etc. etc. But when it comes down to it, if you know how to solve a particular problem in one language, you could do it in other languages as well right? I mean surely some languages are better tools and can do a more elegant job, but at the end of the day the ideas are still the same right?

A: It doesn't matter what language you use. The algorithm underneath is the main thing that matters.


text:
Q: Multi-stage build - switching image from python to ubuntu I am doing multi-stage build currently with:
FROM python:3.9.6-slim AS base
RUN apt update -y && apt install -y build-essential
COPY requirements.txt .
RUN pip install -r requirements.txt --prefix=/install --no-warn-script-location

FROM python:3.9.6-slim
COPY --from=base /install /usr/local
...

Now I wanted to switch to ubuntu:20.04 image, however there is a difference:

*

*With python image modules get installed to /usr/local/lib/python3.9/site-packages and sys.path contains /usr/local/lib/python3.9

*With ubuntu image modules get installed to /usr/local/lib/python3.8/site-packages, but sys.path contains /usr/local/lib/python3.8/dist-packages and Python is not able to find the modules

Now I read a bit about site-packages vs dist-packages, but I'm still confused. Maybe I could do a simple mv, but it seems a bit hacky... So how to make it work in a clean way?


text:
Q: How can I convert decimal value 20.00 to 2000 using replace [Visual Basic 2010]? How can I convert a decimal value that end with X0.00  to  X000?
Here are the other sample values and their output and remarks.
'value              output      remarks

    'num1 = 50.45        5045       Correct

    'num2 = 34.50        3450       Correct

    'num3 = 20.00         20         Wrong

    Dim Num As Double = 10.0
    Dim testing As String = Replace(Replace(FormatNumber(Num), "0.00", "0"), ".", "")

    MessageBox.Show(testing)

The Value of Num3 should be "2000".
Thanks.

A: try this
Dim testing As String = Num3.ToString("#.00").Replace(".","")


text:
Q: Using Promises in for loops JavaScrMipt nodeJS i'm trying to use a Promise function on a for loops, but i keep getting nulls,
I've succeded to solve the issue with Promise.ALL and it's working on my three objects, but i need to write a function with over then 50 objects and this solution doesn't seems right.
advice? thanks.
The Promise function
function getPOIbyID(id) {
    return new Promise(function (resolve, reject) {
        DButilsAzure.execQuery("select * from POI where ID='" + id + "'").then(function (responsePOI) {
            let poi = responsePOI[0];
            return DButilsAzure.execQuery("select Rank, body, Date from ReviewsPoi where POIid=" + id + " order by Date desc").then(function (responseREV) {
                let rev = responseREV;
                let lastTwo = [];
                for (let i = 0; (i < responseREV.length && i < 2); i++) {
                    lastTwo[i] = responseREV[i];
                }
                let returnPOI = {
                    "Name": poi.Name,
                    "Description": poi.Description,
                    "Rank": poi.Rank,
                    "UsersWatching": poi.UserWaching,
                    "Picture": poi.Picture,
                    "Reviews": lastTwo
                }
                resolve(returnPOI);
            }).catch(function (err) {console.log (err) })
        }).catch(function (err) { console.log (err)})
    });
}

the initial code:
router.get('/Random3', function (req, res) {
    DButilsAzure.execQuery("select ID from POI").then(function (responseID) {
        let retArr = [];
        for (let i=0; i<3; i++) {
            let tmpID = Math.floor(Math.random() * (responseID.length));
            getPOIbyID(responseID[tmpID].ID).then(function (responsePOI) {
                    retArr[i] = responsePOI;
                if (i === 2)
                    res.json(retArr);
            }).catch(function (err) { console.log (err)})
        }
    })
})

the solution:
router.get('/Random3', function (req, res) {
    DButilsAzure.execQuery("select ID from POI").then(function (responseID) {
        let retArr = [];
        let usedrans=[];
        let count=0;
        var promise1=new Promise(function(resolve,reject) {
            let tmpID = Math.floor(Math.random() * (responseID.length));
            while(usedrans.includes(tmpID))
                tmpID = Math.floor(Math.random() * (responseID.length));
            usedrans[count]=tmpID;
            count++
            resolve(getPOIbyID(responseID[tmpID].ID))
        })
        var promise2=new Promise(function(resolve,reject) {
            let tmpID = Math.floor(Math.random() * (responseID.length));
            while(usedrans.includes(tmpID))
                tmpID = Math.floor(Math.random() * (responseID.length));
            usedrans[count]=tmpID;
            count++
            resolve(getPOIbyID(responseID[tmpID].ID))
        })
        var promise3=new Promise(function(resolve,reject) {
            let tmpID = Math.floor(Math.random() * (responseID.length));
            while(usedrans.includes(tmpID))
                tmpID = Math.floor(Math.random() * (responseID.length));
            usedrans[count]=tmpID;
            count++
            resolve(getPOIbyID(responseID[tmpID].ID))
        })
        Promise.all([promise1,promise2,promise3]).then(function(values){
            res.send(values);
        })
    })


text:
Q: How to access values from the constructor in an array of objects I have a react component maintoolbar.tsx that has a grid object passed to it as a prop
import React from 'react';
import { Grid } from '../grid';

interface PropsInterface {
  grid: Grid;
}

const MainToolbar: React.FC<PropsInterface> = (props: PropsInterface) => {
  const { grid } = props;
  const test = grid.mainToolbar.shapes[0].name;
//                                       ^ doesnt return the name
  const newNode = () => {
    grid.newNode();
  };

  return (
    <div className='main-toolbar'>
     ...
    </div>
  );
};

export { MainToolbar };

This is what I get returned, but how to do I access the value of this.name??
class Square {
  constructor(nodes) {
    this.name = 'square';

The grid object I'm getting from the props has an array of objects
import { Square } from './components/square';
class Grid {
  constructor() {
    this.mainToolbar = {
      shapes: [Square],
    };
  }
}
export { Grid };

And finally square
class Square {
  name: string;

  constructor(nodes: NodesInterface) {
    this.name = 'square';
  }
}

export { Square };

if a do   console.log(grid.mainToolbar.shapes);
i get this [f] thing ive not seen before

If I do console.log(grid.mainToolbar.shapes[0], ' type ' , typeof grid.mainToolbar.shapes[0]); i get

UPDATE
Adding
interface MainToolbarInterface {
  [key: string]: any;
}
class Grid
  mainToolbar: MainToolbarInterface;

  constructor() {
    this.mainToolbar = {
      shapes: [new Square(this)],
    };
  }

gives me the name, obviously any is not right, what shoujld it be?

A: In your Grid constructor. You have
constructor() {
  this.mainToolbar = {
    shapes: [Square],
  };
}

This is making shapes = an array with the Square class as its first element.
Try
constructor() {
  this.mainToolbar = {
    shapes: [new Square()],
  };
}

If you were not wanting to initialize it there, and this was the type definition. Then instead
constructor() {
  this.mainToolbar = {
    shapes: [],
  }: {
    shape: Square[]
  };
}

After update. For the interface type.
interface MainToolbarInterface {
  shapes: Array<Square>;
}

class Grid
mainToolbar: MainToolbarInterface;

constructor() {
  this.mainToolbar = {
    shapes: [new Square(this)],
  };
}

or shapes: Square[]; if you prefer.


text:
Q: Cannot POST / With Post request from non '/' site I am new to Node and am having trouble with the POST functionality.
I have a simple website, where I have the following lines:
app.get('/sign',(req,res)=>{
    res.sendFile(path.join(__dirname, 'static', 'index.html'));
});

app.post('/sign', (req,res)=>{
    res.send("Success!")
});

The get request works perfectly fine, but when I post the data in the form back, instead of getting a success message, I get Cannot POST /.
When doing the same from the '/' directory with app.get('/', etc.)
it works fine.
This is the content of the 'index.html' file:
<form action = '/' method='POST' id="form">

        Email address
        <input type="email" class="form-control" name="email">

        Password
        <input type="password" class="form-control" name="password">

    <button type="submit" class="btn btn-default">Submit</button>
</form>

A: The action attribute specifies the URL the form data will be posted to.
You have said to post it to /.
Your server side code provides a route for /sign but not /.
You need your URLs to match. Either change action="/" to action="/sign" to be explicit about where you are posting it to or remove the action attribute entirely so it posts to the current url (which is /sign since that is the route of the GET handler that provided the HTML document containing the form).


text:
Q: How to Update Categories that Already Exists in Magento Database Using Custom Script I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description

1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE

Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{

    $odd = array();

     foreach ($var as $k => $v) {
        if ($k % 2 !== 0) {
            $odd[$k] = $v;
        }
    }
    return $odd;
}
function even($var)
{
    $even = array();
     foreach ($var as $k => $v) {
        if ($k % 2 == 0) {
            $even[$k] = $v;
        }
    }
    return $even;
}

function strcount($str,$sy){
    $ch=  explode($sy, $str);
    return count($ch);
}

$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
    if(!in_array($valtest,$row_config)){
    if($count == 0){
        $count++;
        continue;
    }

    $count++;
    $filterd_data=array_filter($line);
    $odd_cell_data=odd($filterd_data);
    $even_cell_data=even($filterd_data);
   $config=array();
   $string='';
    $intialID=$even_cell_data[0];
    foreach($odd_cell_data as $key=>$val){

        if(!in_array($val,$config)){

            $config[] = $val;
            $data['general']['name'] =$val;
            $data['general']['meta_title'] = "";
            $data['general']['meta_description'] = "";
            $data['general']['is_active'] = "";
            $data['general']['url_key'] = "";
            $data['general']['is_anchor'] = 0;
            $data['general']['position'] =1 ;
            $storeId = 0;
            $string .=$val.'~';
            if(!array_key_exists($string, $row_config)){
            $catID=createCategory($data, $storeId);
            $catgoryID[$string]=$catID;
            $row_config[$string]=$parID;

            } else {
               $parID =$row_config[$string] ;
                $row_config[$string]=$row_config[$string];
            }

            if( strcount($string,'~')==2){
                $parID=1;
             }
           $int[$string]=$parID;

           assignCat($catgoryID[$string],$parID);
           $parID = $catgoryID[$string];

            sleep(0.5);
            unset($data);

        }

    }

    }

}

//This Function is used for create each category
function createCategory($data, $storeId) {
    $category = Mage::getModel('catalog/category');
    $category->setStoreId($storeId);
    if (is_array($data)) {
        $category->addData($data['general']);

        if (!$category->getId()) {

            $parentId = $data['category']['parent'];

            if (!$parentId) {
                if ($storeId) {
                    $parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
                } else {
                    $parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
                }
            }

            $parentCategory = Mage::getModel('catalog/category')->load($parentId);
            $category->setPath($parentCategory->getPath());
        } if ($useDefaults = $data['use_default']) {
            foreach ($useDefaults as $attributeCode) {
                $category->setData($attributeCode, null);
            }
        }
        $category->setAttributeSetId($category->getDefaultAttributeSetId());
        if (isset($data['category_products']) && !$category->getProductsReadonly()) {
            $products = array();
            parse_str($data['category_products'], $products);
            $category->setPostedProducts($products);
        } try {
            $category->save();
            $category = Mage::getModel('catalog/category')->load($category->getId());
            $category->setPosition($data['general']['position']);
            $category->addData($data['general']);
            $category->save();
            echo "Suceeded
 ";
        } catch (Exception $e) {
            echo "Failed
";
        }
    }
    return $category->getId();
}
//This Function is used for moving category under respective parent
 function assignCat($id, $parent){
    $category = Mage::getModel( 'catalog/category' )->load($id);
    Mage::unregister('category');
    Mage::unregister('current_category');
    Mage::register('category', $category);
    Mage::register('current_category', $category);
    $category->move($parent);
    return;
}