text:
Q: Spring Cloud Gateway custom route I'm trying define a route using spring cloud gateway for the following scenario:
http://gateway-url/service-url?token=foo_bar => gets forwarded to the service url.
http://gateway-url/service-url => gets forwarded somewhere else
this is what i got so far.
@Bean
public RouteLocator customRouteLocator( RouteLocatorBuilder builder,
                                        RouteServiceForwardingFilter forwardingFilter) {

    return builder.routes()
            .route(r ->
                    r.query("token")
                            .filters(f -> {
                                f.filter(forwardingFilter, ROUTE_TO_URL_FILTER_ORDER + 1);
                                return f;
                            })
                            .uri("http://google.com:80")
                            .id("token_route"))
            .build();
}

and this is the Filter I created
@Component
public class RouteServiceForwardingFilter implements GatewayFilter {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    try {
        String forwardUrl = exchange.getRequest().getURI().toString();
        forwardUrl = forwardUrl.substring(0, forwardUrl.lastIndexOf("?"));
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI(forwardUrl));
        return chain.filter(exchange);
    } catch (URISyntaxException e) {
        exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return Mono.empty();
    }
}

}

A: So after a bit of looking here and there I came up with this implementation which does exactly what I want.
I edited the filter described in the question like this:
/**
 * Checks whether the user is using a valid token or not.
 * If the token is a valid one, a header named AUTHENTICATED is added
 * to the request and the user is forwarded to the same url with the new request.
 * If not, we forward to the same url but removing the token from it.
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String forwardUrl = exchange.getRequest().getURI().toString();
    String queryParam = exchange.getRequest().getQueryParams().getFirst(Constants.TOKEN);
    try {

        // 1 means he is connected
        if (queryParam.equals("1")) {
            ServerHttpRequest request = exchange.getRequest().mutate().
                    header(Constants.AUTHENTICATED, "true").
                    build();
            return chain.filter(exchange.mutate().request(request).build());
        }

        if (forwardUrl.contains("?")) {
            forwardUrl = removeQueryParam(forwardUrl, Constants.TOKEN);
        }
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI(forwardUrl));
        return chain.filter(exchange);
    } catch (URISyntaxException e) {
        return Mono.empty();
    }
}

/**
 * Removes a query param and its value from a given url
 * @param   url   the url to be modified.
 * @param   queryParam   the parameter to be removed.
 * @return  the url wihtout the query param to be removed
 *          or the same url in case that query param isn't in that given url
 */
public static String removeQueryParam( String url, String queryParam ) {
    String result = "";
    String[] urlParts = url.split("\\?");
    if (urlParts.length >= 2) {
        String[] urlParams = urlParts[urlParts.length - 1].split("&");
        for (String urlParam : urlParams) {
            String[] param = urlParam.split("=");
            if (!param[0].equals(queryParam)) {
                result += urlParam + "&";
            }
        }
        result = urlParts[0] + (result.length() > 0 ? "?" + result.substring(0, result.length() - 1) : "");
    } else {
        result = url;
    }

    return result;
}

Then I added these two routes:
/**
 * Adds custom routes to the application
 */
@Bean
public RouteLocator customRouteLocator( RouteLocatorBuilder builder,
                                        SimpleLoggingFilter loggingFilter,
                                        RouteServiceForwardingFilter forwardingFilter) {

    return builder.routes()
            .route(r ->
                    r.query(Constants.TOKEN).negate()
                            .filters(f -> {
                                f.filter(loggingFilter);
                                try {
                                    f.redirect(HttpStatus.UNAUTHORIZED, new URL("http://www.example.com/401"));
                                } catch (MalformedURLException e) {
                                    LOGGER.error(e.getMessage());
                                }
                                return f;
                            })
                            .uri("http://www.example.com/401")
                            .id("WITHOUT_token"))
            .route(r ->
                    r.query(Constants.TOKEN)
                            .and()
                            .header(Constants.AUTHENTICATED).negate()
                            .filters(f -> {
                                f.filter(loggingFilter);
                                f.filter(forwardingFilter, Constants.ROUTE_TO_URL_FILTER_ORDER + 1);
                                return f;
                            })
                            .uri("http://localhost:8008")
                            .id("with_token"))
            .build();
}

and that solved it. I hope this helps someone else.


text:
Q: Error when adding microsoft.kinect to XBOX Project iam trying to develop a new  Xbox game using microsoft kinect SDK 1.5 for windows.
when i create a new XBOX360 project and add Microsoft.Kinect as a reference->type using Microsoft.Kinect and Build,  it gives me an error telling:
Warning 1   The primary reference "Microsoft.Kinect" could not be resolved because it has an indirect dependency on the framework assembly "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0,Profile=Client". To resolve this problem, either remove the reference "Microsoft.Kinect" or retarget your application to a framework version which contains "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089".    Xbox360Game1

and also, with system.dll, system.core.dll
all of these libraries are V2 when adding a new XBox Project.
how can i solve this problem.
Thanks in advance.

A: I have bad news for you.
It's not possible develop apps or games for Xbox with the Kinect SDK.
It's sad, i know.
The only way to create Xbox games with Kinect is with the XDK (if I'm correct) and it's only for certified professionals.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens when one user approves and two reject a suggested edit? User A rejects an edit. User B approves it, then User C rejects it again.
Does this have consequences for User B? Will they lose the right to approve/reject edits?

A: There's no automatic process for this; just like people can disagree about a post, voting it down while others vote it up, people can disagree about a suggested edit as well.
If a user habitually reviews 'wrongly' and you notice this, you can flag one of their posts for moderator attention.

A:
Does this have consequences for User B? Will he lose the right to approve/reject edits?

No, why should it be so? Disagreement is ubiquitous and natural, that's why more than a single OP is involved.
User B might fail on audits, which are frequently strayed in their review queue, this would have consequences of throttling and banning them from reviews.


text:
Q: Gatsby Global SCSS not being applied My Gatsby project's styling from global.scss file is not being applied.
I have a global stylesheet called global.scss that is located in src/styles/ and then I am also using component-scoped scss modules.
In my gatsby-browser.tsx file, I am importing the global file like so:
import './src/styles/global.css'

However, this does nothing. I am not getting my styles from that file applied to any of my pages. Why won't importing a global stylesheet actually work? I've tried it with plain css instead of scss to no avail...
Here is my gatsby-browser.tsx file
import * as React from 'react'
import { PrismicProvider } from '@prismicio/react'
import {
  PrismicPreviewProvider,
  componentResolverFromMap,
} from 'gatsby-plugin-prismic-previews'
import './src/styles/global.scss'
import { GatsbyBrowser, Link } from 'gatsby'
import { linkResolver } from './src/utils/linkResolver'
import IndexPage from './src/pages'
import PageTemplate from './src/pages/{prismicPage.url}'
import ArticleTemplate from './src/pages/{prismicArticle.url}'

interface Props {
  element: React.ReactNode
}

const wrapRootElement: GatsbyBrowser['wrapPageElement'] = ({
  element,
}: Props) => (
  <PrismicProvider
    internalLinkComponent={({ href, ...props }) => (
      <Link to={href} target={props.target} rel={props.rel}>
        {props.children}
      </Link>
    )}
  >
    <PrismicPreviewProvider
      repositoryConfigs={[
        {
          repositoryName: process.env.PRISMIC_REPO_NAME ?? '',
          linkResolver,
          componentResolver: componentResolverFromMap({
            homepage: IndexPage,
            page: PageTemplate,
            article: ArticleTemplate,
          }),
        },
      ]}
    >
      {element}
    </PrismicPreviewProvider>
  </PrismicProvider>
)

export default wrapRootElement

A: Have you tried importing it in your Layout component? Despite your approach should work the preferred way (according to the docs) is through the Layout component:
import React from "react"
import "../styles/global.scss"

export default function Layout({ children }) {
  return <div>{children}</div>
}


text:
Q: Use of undeclared identifier "update" When I run the app I'm working only one error occurs:

Use of undeclared identifier "update"

Here's the code in ViewController.m where the error occurs:
- (void)update {
        NSTimeInterval secondsSinceLastDraw = -([self.lastUpdateTime timeIntervalSinceNow]);

        self.pacmanYVelocity = self.pacmanYVelocity - (self.acceleration.x * secondsSinceLastDraw);
        self.pacmanXVelocity = self.pacmanXVelocity - (self.acceleration.y * secondsSinceLastDraw);

        CGFloat xDelta = secondsSinceLastDraw * self.pacmanXVelocity * 500;
        CGFloat yDelta = secondsSinceLastDraw * self.pacmanYVelocity * 500;

        self.currentPoint = CGPointMake(self.currentPoint.x + xDelta,
                                        self.currentPoint.y + yDelta);

        [self movePacman];

        self.lastUpdateTime = [NSDate date];

        - (void)movePacman {
            self.previousPoint = self.currentPoint;

            CGRect frame = self.pacman.frame;
            frame.origin.x = self.currentPoint.x;
            frame.origin.y = self.currentPoint.y;

            self.pacman.frame = frame;

            // Rotate the sprite
            CGFloat newAngle = (self.pacmanXVelocity + self.pacmanYVelocity) * M_PI * 4;
            self.angle += newAngle * kUpdateInterval;

            CABasicAnimation *rotate;
            rotate                     = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
            rotate.fromValue           = [NSNumber numberWithFloat:0];
            rotate.toValue             = [NSNumber numberWithFloat:self.angle];
            rotate.duration            = kUpdateInterval;
            rotate.repeatCount         = 1;
            rotate.removedOnCompletion = NO;
            rotate.fillMode            = kCAFillModeForwards;
            [self.pacman.layer addAnimation:rotate forKey:@"10"];
        }
    }
}

A: The problem is that you have your movePacman method inside of your update method. You can't have methods inside other methods. Separate them:
- (void)update {
    NSTimeInterval secondsSinceLastDraw = -([self.lastUpdateTime timeIntervalSinceNow]);

    self.pacmanYVelocity = self.pacmanYVelocity - (self.acceleration.x * secondsSinceLastDraw);
    self.pacmanXVelocity = self.pacmanXVelocity - (self.acceleration.y * secondsSinceLastDraw);

    CGFloat xDelta = secondsSinceLastDraw * self.pacmanXVelocity * 500;
    CGFloat yDelta = secondsSinceLastDraw * self.pacmanYVelocity * 500;

    self.currentPoint = CGPointMake(self.currentPoint.x + xDelta,
                                    self.currentPoint.y + yDelta);

    [self movePacman];

    self.lastUpdateTime = [NSDate date];
}

- (void)movePacman {
    self.previousPoint = self.currentPoint;

    CGRect frame = self.pacman.frame;
    frame.origin.x = self.currentPoint.x;
    frame.origin.y = self.currentPoint.y;

    self.pacman.frame = frame;

    // Rotate the sprite
    CGFloat newAngle = (self.pacmanXVelocity + self.pacmanYVelocity) * M_PI * 4;
    self.angle += newAngle * kUpdateInterval;

    CABasicAnimation *rotate;
    rotate                     = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotate.fromValue           = [NSNumber numberWithFloat:0];
    rotate.toValue             = [NSNumber numberWithFloat:self.angle];
    rotate.duration            = kUpdateInterval;
    rotate.repeatCount         = 1;
    rotate.removedOnCompletion = NO;
    rotate.fillMode            = kCAFillModeForwards;
    [self.pacman.layer addAnimation:rotate forKey:@"10"];
}


text:
Q: Domain Authentication Error I have installed and configured the ipa-server and in my machine I'm running fedora workstation 30. After installing the ipa-client on my machine and well configure it I can not authenticate myself with the credentials that I have on the domain server. as you can see in the attached images, when allocating the machine in the domain gave an error like:
'failed to update dns records
missing a reverse record(s) for address(es)
could not update dns sshfp records' (please consult the attachments for better understandig)
I've removed the machine and re-allocated it in the domain and the problem persists, tried other machines that gave the same error but after upgrading three times I was able to authenticate. but in this my machine in question the authentication problem persists. but only in the password, because the user name it recognizes immediately.
-solutions already applied:
1-constant updating of the system;
2-reinstallation and reconfiguration of the machine;
3-reboot the computer countless times.
I hope someone here can help me, first to better understand this type of error, which causes and also to solve the same urgently, I have to deliver some work soon.


text:
Q: Twitter4j getHomeTimeline(Paging) is not retrieving what i want My objective is to get tweets from a Timeline, just one at a time, using Paging within getHomeTimeline method, and starting from the newest.
It happens that when I do not use Paging I get the expected 20 results, but when I use Paging to get just one tweet I get 0 results.
This is my code snippet:
Twitter twitter = getTwitterObject();
Long maxid = prefs.getLong(MAXTWEETID2, Long.MAX_VALUE); //Initially is MAX_VALUE
Long sinceid = prefs.getLong(MINTWEETID2, 1L); //Initially is 1
Paging paging = new Paging(1, 1, sinceid, maxid);
statuses = twitter.getHomeTimeline(paging);

I want to use the previous Paging with sinceId and maxId because I want to play with cursoring to constrain my query in successive lookups.
But I have also tried using:
Paging paging = new Paging(1, 1);

Same void result.
I have searched the web and this forum without getting any clue about constraints regarding the use of Paging while searching the Timeline of a user.

A: It looks like this is something to do with setting max_id to Long.MAX_VALUE. If instead you set max_id to Long.MAX_VALUE - 1 you should see results. This may be a bug in the API.
I would suggest not setting the count so low. API calls are expensive and you will hit rate limits quickly. For example, this API call only allows 15 calls in each 'rate limit window' (currently 15 minutes). You can find out more about rate limiting here.
Finally, getHomeTimeline(Paging) does not support all of the parameters offered by Paging. It does support since_id, max_id and count but not page - it will be ignored. This is the case for most of the API calls in Twitter4J. You can find out what parameters are supported per API call by referring to Twitter4J's API Support Matrix documentation.


text:
Q: При вызове хука на уничтожение окна не происходит запись в файл SetWindowsHookEx( WH_CBT, func, dll, 0)

Вызывает функцию, срабатывающую при уничтожении окна:
extern "C" __declspec(dllexport) LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HCBT_DESTROYWND)
    {
        FILE* file;
        fopen_s(&file, "C:\\file.txt", "a+");
        if( file == NULL )
            MessageBox(NULL, TEXT("Can't open"), TEXT("File"), MB_ICONERROR);
        fprintf(file, "chaa\n");
        fclose(file);
    }
    return (CallNextHookEx(NULL, nCode, wParam, lParam));
}

Функция и проверка на уничтожение срабатывает, но при этом не происходит записи в файл. При этом он существует и доступен для чтения/записи. Почему так? И ещё маленький вопрос: на какие окна срабатывает HCBT_DESTROYWND? Когда закрываешь проводник, либо косынку/paint вызова функции не происходит.

A:
fopen_s(&file, "C:\\file.txt", "a+");

Не надо без админских прав писать в корень системного диска.
Измени путь на такой, который

*

*точно доступен для записи пользователю без админских прав

*не подпадает под системную виртуализацию

*не зависит от текущего каталога


text:
Q: Postgres stored procedure(function) confusion I'm pretty new to Postgres and SQL as a whole and could use a bit of help with a function here.
I have this table:
CREATE TABLE car_rentals(
plate       varchar(10)     NOT NULL,
start_date  date            NOT NULL,
end_date    date            NOT NULL,
license_nr  varchar(10)     NOT NULL,
CONSTRAINT unq_car_rentals_start UNIQUE (plate, start_date),
CONSTRAINT unq_car_rentals_end UNIQUE (plate, end_date));

What i need is for a function to take as input plate, start date and end date and
throw an error if the table contains any row with the same plate where the rental period is different
from but overlaps with the given period.
I found this document on reporting errors but I'm not sure how to properly format the function in order to implement what I need.
https://www.postgresql.org/docs/9.6/plpgsql-errors-and-messages.html

A: You don't need a trigger to achieve this. Postgres supports so called exclusion constraints exactly for this purpose:
create table car_rentals
(
  plate       varchar(10)     NOT NULL,
  start_date  date            NOT NULL,
  end_date    date            NOT NULL,
  license_nr  varchar(10)     NOT NULL,
  constraint no_overlapping_ranges
     exclude using gist (plate with =, daterange(start_date, end_date, '[]') with &&)
);

The constraint definition in details:

*

*plate with = for rows with the same plate number

*daterange(start_date, end_date, '[]') with && - fail if there are rows with an overlapping range.

As the constraint includes the = operator, you need to install the extension btree_gist in order to create the above constraint:
As a superuser run:
create extension btree_gist;

in the database where you want to create the car_rentals database (you only need to do this once).
Online example

A: The WHERE condition of a query you could use in a trigger could be:
WHERE daterange(start_date, end_date, '[]') && daterange($1, $2, '[]')  -- overlaps
  AND (start_date <> $1 OR end_date <> $2)  -- is not equal
  AND plate = $3

Here $1, $2 and $3 are placeholders for the data against which you want to check, and the query becomes simple by using the "overlaps" range operator &&.


text:
Q: get request works in browser, not in PhoneGap Build I've looked at other examples on so and it looks like I'm doing everything right but obviously I am missing something. When run on my desktop it runs great. Once bundled into an app via PhoneGap Build, it no longer works :( wondering if anyone can spot why. All its really doing is picking out unique items from an xml response and listing them. Thanks
Mike
<!DOCTYPE HTML>

    <title>TestApp</title>

    <meta name = "viewport" content = "width = device-width, initial-scale = 1">
    <link rel="stylesheet" href="jquery/jquery.mobile-1.4.0.min.css" />

Current Status:

                <button onclick="loadXMLDoc('http://login.etherios.com/ws/DiaChannelDataFull')">Refresh Sensor Data</button>

A: I gave up on this and decided to go in another direction.


text:
Q: Error querying database after uninstallation + reinstallation: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' I get an error when querying my database after deleting my old version of MySQL and reinstalling the newest one.
I am using:
MySQL Ver 8.0.23 for macos10.15
My app is in Next.js and it was working fine before this. I'm running it on localhost. It uses serverless-mysql to connect:
const mysql = require('serverless-mysql')

const db = mysql({
  config: {
    host: process.env.MYSQL_HOST,
    database: process.env.MYSQL_DATABASE,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
  }
})

The test connection works perfectly fine in MySQL Workbench.
Things I've tried:

*

*Resetting the password.

*Uninstalling MySQL again and using the Legacy Password Encryption. This makes the plugin for the root user "mysql_native_password".

*Creating a new user, granting them all permissions, and trying with their credentials

This might be overkill but here is what the user looks like after all of this:
COMMAND:
use mysql;
select * from user where User="root";

RESULT:
[
    {
        "Host" : "localhost",
        "User" : "root",
        "Select_priv" : "Y",
        "Insert_priv" : "Y",
        "Update_priv" : "Y",
        "Delete_priv" : "Y",
        "Create_priv" : "Y",
        "Drop_priv" : "Y",
        "Reload_priv" : "Y",
        "Shutdown_priv" : "Y",
        "Process_priv" : "Y",
        "File_priv" : "Y",
        "Grant_priv" : "Y",
        "References_priv" : "Y",
        "Index_priv" : "Y",
        "Alter_priv" : "Y",
        "Show_db_priv" : "Y",
        "Super_priv" : "Y",
        "Create_tmp_table_priv" : "Y",
        "Lock_tables_priv" : "Y",
        "Execute_priv" : "Y",
        "Repl_slave_priv" : "Y",
        "Repl_client_priv" : "Y",
        "Create_view_priv" : "Y",
        "Show_view_priv" : "Y",
        "Create_routine_priv" : "Y",
        "Alter_routine_priv" : "Y",
        "Create_user_priv" : "Y",
        "Event_priv" : "Y",
        "Trigger_priv" : "Y",
        "Create_tablespace_priv" : "Y",
        "ssl_type" : "",
        "ssl_cipher" : ?,
        "x509_issuer" : ?,
        "x509_subject" : ?,
        "max_questions" : 0,
        "max_updates" : 0,
        "max_connections" : 0,
        "max_user_connections" : 0,
        "plugin" : "mysql_native_password",
        "authentication_string" : "*E7CF5215B32CCDA122352F3A92E9F73131E28662",
        "password_expired" : "N",
        "password_last_changed" : "2021-02-24 18:54:52",
        "password_lifetime" : null,
        "account_locked" : "N",
        "Create_role_priv" : "Y",
        "Drop_role_priv" : "Y",
        "Password_reuse_history" : null,
        "Password_reuse_time" : null,
        "Password_require_current" : null,
        "User_attributes" : null
    }
]

Would really appreciate any help anyone can offer, this bug is destroying my sanity. Let me know if I can provide any more details.

A: The way I solved this problem was I manually entered my password in my code instead of the ENV file. It worked. When I console logged the ENV file to see why that wasn't working, it was because I was putting it in a string, for ex: MYSQL_PASSWORD = "password". It SHOULD be: MYSQL_PASSWORD = password
So if anyone is struggling, check that the ENV variables are set up correctly, and manually put them in to rule out any ENV issues.


text:
Q: Does "... induces same topology" mean there is a homeomorphism between them? The following text is from Munkers' Topology:

Well, we can define two sets of real numbers, $I_1=(0,1)$ and $I_2=(0, \infty)$ which are homeomorphic as we can find a homeomorphism between them in standard topology. We can define $\bar{d}$ on space $I_1=(0,1)$ and $d$ on space $I_2=(0, \infty)$. But then they won't be homeomorphic anymore since there won't be a homeomorphism between those two space in metric topology since there is no bijective function between them. So how they are same topology, after all? I think the last paragraph of the proof in the text is not rigorous argument.

A: "Induces the same topology" means that the topologies are identical collections of subsets of $X$, in other words a subset of $X$ is open with respect to the first topology if and only if it is open with respect to the second topology. This is equivalent to saying that the identity map on $X$ is a homeomorphism from one topology to the other.
Note: Your example of $I_1$ and $I_2$ are two different metric spaces based on two different sets. That's an entirely different context from the text you pasted into your question, namely of two different metrics on the same set $X$.

A: The two spaces you mention are indeed homeomorphic.  In particular, we can take the following homeomorphism between them:
$$
f:(0,1) \to (0,\infty)\\
f(x) = x/(1 - x)
$$


text:
Q: Examples of a working ITestCaseProvider implementation for NUnit? Does anyone have any working examples of an ITestCaseProvider?
The samples I've come across, don't get picked up by the any test runnings - GUI, Console or Resharper (I've put the assembly in all the right places).
I've added Debugger.Break to them all, in an attempt to force the debugger to kick in, but nothing so far.
I guess I'm after a step-by-step guide, if anyone either has one, or as come across one.
Thanks,
Kieron

A: I got my ITestCase provider working from this blog here and dropping my assembly here:
C:\Program Files (x86)\NUnit 2.6.3\bin\addins
Unfortunately it only works within the nunit GUI. ReSharper (v8.2) persists to be a pain by not loading it even though I also put my assembly here:
C:\Program Files (x86)\JetBrains\ReSharper\v8.2\Bin\addins
Would love to see a test framework with much easier extension points and easy ReSharper integrations.


text:
Q: Compare two 3d Numpy array and return unmatched values with index and later recreate them without loop I am currently working on a problem where in one requirement I need to compare two 3d NumPy arrays and return the unmatched values with their index position and later recreate the same array. Currently, the only approach I can think of is to loop across the arrays to get the values during comparing and later recreating. The problem is with scale as there will be hundreds of arrays and looping effects the Latency of the overall application. I would be thankful if anyone can help me with better utilization of NumPy comparison while using minimal or no loops. A dummy code is below:
def compare_array(final_array_list):
    base_array = None
    i = 0
    for array in final_array_list:
        if i==0:
            base_array =array[0]
        else:
            index = np.where(base_array != array)

            #getting index like (array([0, 1]), array([1, 1]), array([2, 2]))
            # to access all unmatched values I need to loop.Need to avoid loop here

        i=i+1

    return [base_array, [unmatched value (8,10)and its index (array([0, 1]), array([1, 1]), array([2, 2])],..]

# similarly recreate array1 back
def recreate_array(array_list):
    # need to avoid looping while recreating array back
    return list of array #i.e. [base_array, array_1]

# creating dummy array
base_array = np.array([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]])
array_1 = b = np.array([[[1, 2,3], [3, 4,8]], [[5, 6,7], [7, 8,10]]])
final_array_list = [base_array,array_1, ...... ]

#compare base_array with other arrays and get unmatched values (like 8,10 in array_1) and their index
difff_array  = compare_array(final_array_list)

# recreate array1 from the base array after receiving unmatched value and its index value
recreate_array(difff_array)

A: I think this may be what you're looking for:
base_array = np.array([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]])
array_1 = b = np.array([[[1, 2,3], [3, 4,8]], [[5, 6,7], [7, 8,10]]])

match_mask = (base_array == array_1)
idx_unmatched = np.argwhere(~match_mask)

# idx_unmatched:
#  array([[0, 1, 2],
#         [1, 1, 2]])

# values with associated with idx_unmatched:
values_unmatched = base_array[tuple(idx_unmatched.T)]

# values_unmatched:
#  array([5, 9])

A: I'm not sure I understand what you mean by "recreate them" (completely recreate them? why not use the arrays themselves?).
I can help you though by noting that ther are plenty of functions which vectorize with numpy, and as a general rule of thumb, do not use for loops unless G-d himself tells you to :)
For example:

*

*If a, b are any np.arrays (regardless of dimensions), the simple a == b will return a numpy array of the same size, with boolean values. Trues = they are equal in this coordinate, and False otherwise.

*The function np.where(c), will convert c to a boolean np.array, and return you the indexes in which c is True.
To clarify:
Here I instantiate two arrays, with b differing from a with -1 values:
Note what a==b is, at the end.
>>> a = np.random.randint(low=0, high=10, size=(4, 4))
>>> b = np.copy(a)
>>> b[2, 3] = -1
>>> b[0, 1] = -1
>>> b[1, 1] = -1
>>> a
array([[9, 9, 3, 4],
       [8, 4, 6, 7],
       [8, 4, 5, 5],
       [1, 7, 2, 5]])
>>> b
array([[ 9, -1,  3,  4],
       [ 8, -1,  6,  7],
       [ 8,  4,  5, -1],
       [ 1,  7,  2,  5]])
>>> a == b
array([[ True, False,  True,  True],
       [ True, False,  True,  True],
       [ True,  True,  True, False],
       [ True,  True,  True,  True]])

Now the function np.where, which output is a bit tricky, but can be used easily. This will return two arrays of the same size: the first array is the rows and the second array is the columns at places in which the given array is True.
>>> np.where(a == b)
(array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], dtype=int64), array([0, 2, 3, 0, 2, 3, 0, 1, 2, 0, 1, 2, 3], dtype=int64))

Now you can "fix" the b array to match a, by switching the values of b ar indexes in which it differs from a, to be a's indexes:
>>> b[np.where(a != b)]
array([-1, -1, -1])
>>> b[np.where(a != b)] = a[np.where(a != b)]
>>> np.all(a == b)
True


text:
Q: Skyrim: Everything Is Not Permitted
Possible Duplicate:
Why can I sometimes take half of a shops items while the oher half is considered stealing?

I've noticed that upon meeting certain people and doing a quest for them to earn their trust, certain things that would be considered stolen are able to be obtained without any trouble and are not labeled as stolen. Though I can't recall the name I remember there was a quest in which you sent a message to a woman about why mining operations were slow and that the shipment would be there soon. After, if you go back to the quest giver's house you can take all the ingots and ore in his house and despite it saying "Steal" at the bottom, he does not care and lets you obtain them without trouble. Are there any other situations like this where you may take an NPC's item with their consent so to say?


text:
Q: Tons of "Attempting to kill operation" messages in log I am running a Mongo (v4.4.3) sharded setup. I have two shards as PSA replica. Shard1 contains most data and is usually very busy. I noticed that there were tons of "Attempting to kill operation" in the logs. It resulted in 20-30GB of log file a day. I am pretty sure we don't issue any opKill commands. We do a lot of upserts though. The messages would go away if we shut down the secondary. As soon as the secondary syncs up, the messages show up again. The messages are printing a few hundred times per second.  It seems to use a lot more CPUs than usual.
Is it an issue? How can we turn off the messages?
One of the examples:
{
  "t": {
    "$date": "2021-02-07T10:44:39.035-05:00"
  },
  "s": "I",
  "c": "COMMAND",
  "id": 4615602,
  "ctx": "conn59830",
  "msg": "Attempting to kill operation",
  "attr": {
    "operationKey": {
      "uuid": {
        "$uuid": "3bc054fe-e267-4290-8572-7e4052399011"
      }
    }
  }
}

A: The reason behind these messages is usually read hedging -- a method which mongos instance uses to increase performance that involves secondary reads to be "forked" across all members of the replica set, using the fastest result and cancelling the others. It was introduced in MongoDB 4.4. Read hedging can be disabled in your driver (check out read preference configuration for your specific driver) or globally using the readHedgingMode parameter in mongos configuration. I must warn you, that in theory, disabling read hedging could lower performance, to the level of pre-4.4 MongoDB, but in our testing we found read hedging produces negligible performance boost.


text:
Q: Using-directive class static functions? I am using an API that has a lot of functions in a class named TCODConsole as static functions. Now I thought that it was in a namespace, so I wrote: using namespace TCODConsole;. Then I found out that TCODConsole ain't a namespace, but a class.
Is there a way to import those functions in a similar way as you would use using namespace?

A: No, there is no shortcut way to call myStaticFun() instead of MyClass::myStaticFun(). You cannot do that with class. It's a class, not a namespace. But you can write something like a wrapper. That is you will add functions with same name and call the static methods from that functions. Something like this:
class MyClass {
    static void fun();
};

void fun() {
    MyClass::fun();
}

// call it
fun();

Not a very good way. Personally I think it is better to stick with the class instead of doing this.

A: I can't think of a clean way to do it, but I can think of a kinda ugly hack that will work, as long as the code using it is part of a class (and if TCODConsole really contains only static member functions). Let's say you are bar(), a member function of the class Foo, and you want to call a function baz() which is a static member of TCODConsole without fully-qualifying it. What you can do is to privately derive Foo from TCODConsole:
class Foo : private TCODConsole
{
    void bar()
    {
        baz();
    }

};

Yeah, that's ugly. :(
If you want to use Boost.PP (the Boost Preprocessor macro library - you don't need to compile or include anything else from Boost to use it), you can probably make a less ugly but quite a bit more convoluted macro which will "import" these functions for you, by wrapping them with inline functions inside another namespace (which you can then import at will). It would still require you to explicitly specify the name each of the functions you want to "import", so your code (minus the macro) will look something like this:
namespace TCODStatic
{
    IMPORT_FROM_TCOD(foo)
    IMPORT_FROM_TCOD(bar)
    IMPORT_FROM_TCOD(baz)
    IMPORT_FROM_TCOD(spaz)
}

and then you'll be able to write using namespace TCODStatic; anywhere you want.

A: Though I may misunderstand the question,
if shortening the qualification is the objective,
does typedefing like the following meet the purpose?
struct TCODConsole {
  static void f();
  static void g();
};

int main() {
  typedef TCODConsole T;
  T::f();
  T::g();
}

Alternatively, if the class TCODConsole can be instantiated,
since static member function can be called with the same form as
non-static member function, the following code might meet the purpose:
int main() {
  TCODConsole t;
  t.f();
  t.g();
}

A: Short answer: not without using macros.  There is no mechanism in the C++ language proper to do something like this:
class A
{
public:
  static void foo();
};

// ...

using A;
foo();

You could use a macro to build these expressions for you:
#define FOO() (A::foo())

FOO();

I would discourage this however, because it can become a maintennence nightmare is you make extensive use of such macros.  You end up with code like this:
FOO();
BAR();
SUPERGIZMO(a, b, c);

...where none of these things are defined as first-class names anywhere in the program.  You've lost all type checking, the code uses a "secret language" that only you know, and it becomes difficult to debug, extend and fix.
EDIT:
You could write a kind of bridge.  Like this:
class FooBar
{
public:
  static void gizmo();
};

namespace Foo
{
  void gizmo() { FooBar::gizmo(); };
};

using namespace Foo;

gizmo();


text:
Q: Email Validation in Registrraion Form in javascript I have One Register-form for creating Account.In Email Field How Can i Check Enter Email is Real Email Id or Fake Email Id without Sent Any Email.And Also when User Leave The Field Validation will be start.Any idea please Share me....

A: You can't do this work with js(without sedn email):
i recommend to send a code to your user rmail and verify that.
this way is good to valid email and register user.
note : if you want to know is the email is in email pattern you can do with html and js :
html way :
<input type="email" name="email"  placeholder="Your email">

js way :
How to validate email address in JavaScript?


text:
Q: Is it possible to make dynamically VStack in the HStack when screen width ends Basically, my requirement place array of string into Text horizontally but when screen width can not contain next Text I need to move it into next Line (I know it will be VStack then) as shown in the pic blow

is it possible in SwiftUI


text:
Q: Sprint Work Items - Agile Scrum What types of tasks can be included and tracked as work items in the Sprint Backlog?
Can Analysis, Review and Unit Testing (of a user story) be included or can only core Coding tasks be included and tracked in the Sprint backlog?
Basically I am breaking down user stories into technical tasks to update the Sprint backlog and would like to know if tasks having non-coding roles can be updated and tracked in the sprint backlog.

A: You have these tasks that you want to track as work items.  Be careful of doing this.
Why?  You're starting to concretize a process.  There's a slippery slope here.  As soon as you start concretizing the process, you stop being actually Agile and start creating an inflexible waterfall of mandatory sequential steps.
If you think these things are so important that you have to write them down or the developers will forget them, then you're not giving your developers the responsibility to be agile, or the authority to make their own decisions.
You're treating them as untrustworthy.

*

*Analysis of a user story.  They're going to do this anyway.  Why write it down?  Will they forget?  The point is understanding.  Not documentation.  Not time management.

*Review of code.  You want them to do this.  You have to create the culture where this is done and the results are rewarding.
If the results of a code review are "your code sucks, do it again", then no one participates and it doesn't get done except by fiat.
If the results of a code review are "a new best practice for everyone to learn from" plus "perhaps you should rethink this according to other best practices", maybe people will participate.

*Unit testing is part of a sprint without any question or discussion.
Indeed, it is -- perhaps -- the most important part of a sprint.  Unit tests come first, before almost any other code.  You don't need to say this.  Indeed, the act of saying it makes a claim that your developers can't be trusted to test.
When you feel the urge to write down tasks for the programmers, then you have to also think through the question why.
Why do you have to write this down? What aren't they doing?
Here's the important part.
Why aren't they doing this in the first place?
Are they not analyzing?  Why not?  Are you making it hard to analyze?  Are the users not making themselves available?
Are they not doing code reviews?  Why not?  What's the road block to code reviews?  Not enough time?  Not enough cooperation?  Not enough reward?  What's stopping them?
Are they not doing unit tests?  Why not?  What's the road block to testing?  Not enough time?  Not enough flexibility?  Not enough positive feedback for doing tests first?
Why do you feel the need to "control" and "coerce" your developers?  Why aren't they doing this on their own?

A:
What tasks that can be included and tracked as work items in the Sprint Backlog?

As per Scrum Guide ->In the planning meeting part 2, the Team identifies tasks. These tasks are the detailed pieces of work needed to convert the Product Backlog into working software. Tasks should have decomposed so they can be done in less than one day. This task list is called the Sprint Backlog.
So whatever task which meets the above guideline needs to be included.

Can Analysis, Review and Unit Testing (of a user story) be included or can only core Coding tasks be included and tracked in the Sprint backlog?

Yes, they can and should be included if doing them leads to converting the Backlog to Working Software. Scrum NEVER suggests to include only coding tasks in a Sprint Backlog. In fact Scrum asks the team to be cross functional.

Basically I am breaking down user stories into technical tasks for updating the Sprint backlog and would like to know if tasks having non-coding roles can be updated and tracked in the sprint backlog.

This sounds suspicious to me. Is it just 'You' who breaks down tasks? It should be the whole Team breaking down tasks in the second part of the planning meeting. Again non coding tasks can be included in a Sprint.
Just to give you a realistic example: In my Web Development Team a typical Backlog had the following tasks.
1. Define and Discover
2. Design and Create Test Matrix
3. Write Unit Tests to Test Matrix
3. Code to make Unit Tests pass
4. Test
5. Regression Test
6. Debug
7. Go over 'Working Software with PO (if required to make sure this is what PO wants)
EDIT
One more point about tasking.
The tasks added during planning should constantly be broken down/updated/renamed when necessary. The whole point of this is to add a transparent set of decomposed pieces of things to do, which when done completely, eventually leads to working software following QA standards, most efficiently and effectively. These tasks should be picked up and worked on cross functionally and should not be blocked amongst team members.
Hope this helps!

A: The short answer is - whatever works best for your team and the user story in question.
For example, if we're working on refactoring a piece of code as part of a user story, we may break out a separate task to handle putting it under test first.  But if it's new dev, we infer that it will be under test (and usually done with TDD) as part of our process.
Other examples include sometimes breaking out a separate task to cover time spent for coordination vs. coding, integration testing with external vendors, etc. - basically, any discreet and measurable task that helps make up that specific story (including some of the examples you have included above).
Bottom line is that there is not a set formula for what every story should have, rather tailor the tasks based on the individual needs of each story (even of those tasks are not code related).

A: If you create task for Analysis, Coding, Review, Testing, etc. in each user story you will get close to something called Scrumfall (each iteration divided to waterfall stages). It is one of the Scrum smells. Basically such activities should be included in single task: "Do something" means do everything you need to complete "something" = you are professional developer and you know (or it is said by policy) what has to be done to complete task.
That is general case. Sometimes you indeed need to divide tasks to "activities" but first you should start with common process and use this tool only if you have real reason - for example spike task in one iteration and real task in second iteration.
Edit: I used dividing tasks into activities once. We didn't do TDD but tests were written after completing the task. So each development task was paired with testing task to show that it could be done by another developer and sometimes in parallel with development. But the responsibility of testing by another developer was team decision and for complex tasks they really did that.

A: If you focus all the effort you are applying to task tracking to splitting your stories smaller (1-3 points) then you will working on becoming more agile.  Small stories have almost no need for task level estimates or tracking.  Your PO gets the benefit of being able to prioritize smaller sets of features and you get to focus on delivering value instead of documenting obvious steps repetitively.  Certainly tracking a team's agreed upon standard practices by the hour per story is not at all useful.


text:
Q: Trigger not executing @future method for bulk transactions I'm wondering can anyone help? I have an after insert, after update trigger on Contact that calls an @future method in a helper class to create portal users for contacts.
In an attempt to prevent passing duplicate lists contacts to this method to create users for (caused by the same Trigger code generating the same list of contacts to create as users for insert & update transactions) I set a flag to true after the first pass of the Trigger to indicate that I don't want the same action done in a second pass. After my workflows run they update the contact record and so cause the after update of the same trigger to fire & this does prevent the calling of the @future method in my helper class a second time - so this ensures that the create user code is only called once.
This all works fine in my test class code for both single & mass update tests, however, when I try to do an import via dataloader I notice that the @future method never gets executed. The trigger code does execute and checking debug logs confirms that the call is made to the @future method from my calling code in my Trigger, but for some reason it never fires the code in the @future method. If I do some manual single insert/update transactions on Contact records through the UI, the @future method does get executed.
Can anybody show me the error of my ways? Without wanting to pollute my question with lines & lines of code, here is the snippet at the end of my trigger code where I attempt to call the helper class & fire the @future method to create users for my list of contacts:
if(myContacts.size() > 0 && !ProcessorControl.isAlreadyModified()){
    System.debug('Total number of users to be created: ' + myContacts.size());
    JSONcontacts = JSON.serialize(myContacts); //Serialize list of contacts into JSON string to pass into @future method
    PortalUserHelper.createUser(JSONcontacts); //Call the Helper class and invoke the @future method
    ProcessorControl.setAlreadyModified();  //Set external static flag to true to indicate Trigger has already been executed
}

Thanks in advance for any help that you can provide me in figuring out what I'm doing wrong.
Kind Regards,
Brian.


text:
Q: Scrapy: excluding some text in the scrape I am new to scrapy, and have spent ages trying to solve what I think should be two simple questions.
(1) I am trying to scrape this website:
https://www.reuters.com/article/us-vanburen-iraq-commentary/commentary-the-tragedy-of-the-u-s-victory-in-iraq-idUSKBN1FF2XW
Specifically, I am trying to scrape just the article's text (so no pictures, captions, title, etc...). The code I am using is:
response.css('div.body_1gnLA p::text').extract()

The problem is that at the bottom of the article, there is an "about the author" section that gets included in the scrape, which I do not want. The specific text I do not want is the following:
"Peter Van Buren, a 24-year State Department veteran, is the author of We Meant Well: How I Helped Lose the Battle for the Hearts and Minds of the Iraqi People and Hooper's War: A Novel of WWII Japan. @WeMeantWell
The views expressed in this article are not those of Reuters News."
(2) In the article, some text is hyperlinked. For example, in the first sentence
"Iraqi Prime Minister Haider al-Abadi declared victory over Islamic State on Dec. 9, 2017"
declared victory is hyperlinked. When I use the code I wrote above to scrape, it gives me
"Iraqi Prime Minister Haider al-Abadi   over Islamic State on Dec. 9, 2017"
Notice that the hyperlinked part, "declared victory", is missing. How can I fix this? I only want the full sentence's text to be scraped; I don't care about the href part.
Much appreciated if anyone could help!

A: One possible way:
def parse(self, response):

    paragraphs = []

    for p in response.xpath('//div[@class="body_1gnLA"]/p'):
        p_text = p.xpath( 'string(.)' ).extract_first()
        paragraphs.append(p_text)

    article = "\n".join(paragraphs)
    print(article)


text:
Q: Show that $\{ x \in X: \langle w, x\rangle = b \}$ has dimension one less than $X$ Consider the hyperplane
$$
H := \left\{\mathrm x \in X: \langle \mathrm{w, x}\rangle = b \right\},
$$
and suppose that $\mathrm{e_1} \dots, \mathrm{e_n}$ is a basis for $X$. $H$ isn't necessarily a subspace of $X$ - it need not contain the zero vector - but if one looks up a "Hyperplane" on Wikipedia it is stated that a hyperplane is an affine subspace of $X$.  Is it possible to explicitly derive a basis of $n-1$ vectors for this affine subspace $H$; thereby showing that the dimension of $H$ is at most $n-1$?
Thanks!


text:
Q: Iterate through regular expression array in Javascript How can I use an array of Regex expressions and iterate that array with 'exec' operation. I did initialize an array with various regular expressions like this:
var arrRegex = new Array(/(http:\/\/(?:.*)\/)/g, /(http:\/\/(?:.*)\/)/g);

Now I created a for loop that does this:
 for(i=0;i<arrRegex.length;i++){
     arrRegex[i].exec(somestring);
 }

The thing is that this doesn't seems to work.  I don't want to use it hardcoded like this:
  (/(http:\/\/(?:.*)\/)/g).exec(somestring);

When using the array option, the '.exec' function returns null. When I use the hardcoded option it returns the matches as I wanted.

A: The exec() returns the match so you should be able to capture it.
somestring = 'http://stackoverflow.com/questions/11491489/iterate-through-regular-expression-array-in-javascript';
var arrRegex = new Array(/(http:\/\/(?:.*)\/)/g, /(http:\/\/(?:.*)\/)/g);
for (i = 0; i < arrRegex.length; i++) {
    match = arrRegex[i].exec(somestring);
}

match is an array, with the following structure:
{
    [0] = 'string matched by the regex'
    [1] = 'match from the first capturing group'
    [2] = 'match from the second capturing group'
    ... and so on
}

Take a look at this jsFiddle http://jsfiddle.net/HHKs2/1/
You can also use test() instead of exec() as a shorthand for exec() != null. test() will return a boolean variable depending on whether the regex matches part of the string or not.

A: What you probably want to do is to capture the first group:
for(i=0;i<arrRegex.length;i++){
  var someotherstring = arrRegex[i].exec(somestring)[1];
  // do something with it ...
}

BTW: That is my guess, not sure what you are trying to do. But if you are trying to get the host name of a URL you should use /(http:\/\/(?:.?)\/)/g. The question mark after .* makes the previous quantifier (*) ungreedy.


text:
Q: Preserve paragraph marks while capitalzing - RegEx p = re.compile(r'((?<=[\.\?!]\s)(\w+)|(^\w+))')
def cap(match):
    return(match.group().capitalize())
capitalized_1 = p.sub(cap, Inputfile)

with codecs.open('o.txt', mode="w", encoding="utf_8") as file:
  file.write(capitalized_1)

I am using Regex to capitalize letters after . ? ! which the code above does. But it takes away paragraph marks(page break pilcrow) and lumps it into one big paragraph.
How to preserve the paragraph marks and prevent clumping?
Input file:

on the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. you can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. when you create pictures, charts, or diagrams, they also coordinate with your current document look.
you can easily change the formatting of selected text in the document text by choosing a look for the selected text from the quick styles gallery on the home tab. you can also format text directly by using the other controls on the home tab. most controls offer a choice of using the look from the current theme or using a format that you specify directly.

Current output

On the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look. You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the quick styles gallery on the home tab. You can also format text directly by using the other controls on the home tab. most controls offer a choice of using the look from the current theme or using a format that you specify directly.

Expected output:

On the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look.
You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the quick styles gallery on the home tab. You can also format text directly by using the other controls on the home tab. Most controls offer a choice of using the look from the current theme or using a format that you specify directly.

Edit 1:
import re,codecs
def capitalize(match):
    return ''.join([match.group(1), match.group(2).capitalize()])

with codecs.open('i.txt', encoding='utf-8') as f:
    text = f.read()

pattern = re.compile('(^|[.?!]\s+)(\w+)?')

print(pattern.sub(capitalize, text))

Throws error while i try to read it from a file based on answer 1 approach.
return ''.join([match.group(1), match.group(2).capitalize()])
AttributeError: 'NoneType' object has no attribute 'capitalize'

A: You can do it like this:
import re

def capitalize(match):
    return ''.join([match.group(1), match.group(2).capitalize()])

text = """on the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. you can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. when you create pictures, charts, or diagrams, they also coordinate with your current document look.

you can easily change the formatting of selected text in the document text by choosing a look for the selected text from the quick styles gallery on the home tab. you can also format text directly by using the other controls on the home tab. most controls offer a choice of using the look from the current theme or using a format that you specify directly."""

pattern = re.compile('(^|[.?!]\s+)(\w+)?')

print(pattern.sub(capitalize, text))

Output
On the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look.

You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the quick styles gallery on the home tab. You can also format text directly by using the other controls on the home tab. Most controls offer a choice of using the look from the current theme or using a format that you specify directly.

Notes

*

*(^|[.?!]\s+) means capture a . (dot), ? or ! followed by one or more whitespaces characters (tab, space, etc). The ^ means the start of the string; so in full this group means the start of the sentence or a .?! followed by a whitespace.

*(\w+)? means one or more word characters

*The capitalize function then preserves what was matched on the first group and capitalize the second group (the word).


text:
Q: iptables bidrectional nat / twice nat for smtp we use a linux firewall with multiple external ip-addresses.let's say we have this:
webserver (www.blabla.com)   : (ext)10.0.0.1 -> (int)172.99.0.2
mailserver (mail.blabla.com) : (ext)10.0.0.2 -> (int)172.99.1.2

this routings is done with simple port forwarding.
but if the mailserver sends a mail it uses the first external ip-address (10.0.0.1).
it works quite well, but some smtp-servers treat our mails as spam.
because 10.0.0.1 is not covered with mail.blabla.com (this is fix).
i read some thing about bidirectional nat to accomplish this:
pseudo logic:
if destination port == smpt and source is internal 172.99.1.2 {
   set external address 10.0.0.2
}

do u know how to do it?
is this a way to do it:
iptables -t nat -A POSTROUTING -s $INTERNAL_NET -d ! $INTERNAL_NET -dport SMTP -j SNAT --to $EXTERNAL_IP

A: Yes, this is basically the firewall rule you need. Watch out, it's  --dport, i.e. you need a double dash.
An alternative would be to ask your ISP to put another reverse DNS record in place (also called PTR) for the second IP address, and then have a MX record using the same IP address with a higher value, so that delivery from outside is always attempted at the real server first.

A: i would use iptables and iproute:
1.use iptables to mark the packets coming from mail server and going out to any, port 25
iptables -A PREROUTING -i <mailsrv_iface> -t mangle -p tcp --dport 25 -j MARK --set-mark 25

2.properly route the marked packets through the right interface
echo 25 mailgw >> /etc/iproute2/rt_tables
ip ru add fwmark 25 table mailgw
ip ro add default via <correct_mailgw_ip> dev <correct_mailgw_iface> table mailgw

A: Have you considered forwarding the IP address to the mail server.  Then it would be sending from the desired address.  In that case you would not be using NAT for the mail server.  Check the documentation for Shorewall for some examples.


text:
Q: How to include version and author information in Dart Native on windows How do I include version number, author information and other application metadata in a compiled dart native application?
I have included it in the pubspec.yaml file but does not show up when checking the properties of the compiled exe in windows.
I am running dart 2.2 on Windows 10 in VS Code.
Any help would be appreciated.


text:
Q: How can i add button in menu (In Android Studio) I am trying to add "button" to menu in my code, but the button is not working, i think i am doing something wrong, please correct me.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/activity_main"
            android:icon="@drawable/ic_home"  />
        <item
            android:icon="@drawable/ic_near"  />
        <item
            android:icon="@drawable/ic_setting"  />
        <Button
            android:icon="@drawable/ic_money"
            android:id="@+id/btn_remove_ads" />
        <item
            android:id="@+id/nav_review"
            android:icon="@drawable/ic_action_name"  />
        <item
            android:id="@+id/nav_share"
            android:icon="@mipmap/ic_share"  />
        <item
            android:id="@+id/nav_email"
            android:icon="@drawable/ic_action_email"  />
    </group>

</menu>

A: You must set width and height. The button should be red underlined in Android Studio and usually tells you whats wrong, when you click the red bulb.
 <Button
        android:id="@+id/whatever"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>

A: You cant add a Button in menu.xml, you must add a < Item> and change his icon, and handle the click in onOptionsItemSelected method.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.nav_1:
        TODO()
        return true;
    case R.id.nav_2:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

See more - Android Menus


text:
Q: Sending FormData with a binary data by using jQuery AJAX I'd want to send a FormData by using jQuery AJAX, like:
var uploadFormData = new FormData();
uploadFormData.append("name","value");

$.ajax({
    url : "(URL_target)",
    type : "POST",
    data : uploadFormData,
    cache : false,
    contentType : false,
    processData : false,
    success : function(r) {
        alert("Success!");
    }
});

But I also want to send a binary data by using jQuery AJAX, like:
var data = (...);

$.ajax({
    url: "(URL_target)",
    type: "POST",
    data : data,
    cache : false,
    contentType: "application/octet-stream",
    processData: false,
    success : function(r) {
        alert("Success!");
     }
});

How can I combine them into one data and send it out?

A: You can append binary data to FormData object as a Blob, File, ArrayBuffer object, or data URI
var uploadFormData = new FormData();
var data = (...);
uploadFormData.append("name","value");
uploadFormData.append("data", new Blob([data], {type:"application/octet-stream"}));

$.ajax({
  url : "(URL_target)",
  type : "POST",
  data : uploadFormData,
  cache : false,
  contentType : false,
  processData : false,
  success : function(r) {
    alert("Success!");
  }
});


text:
Q: Should overfitting always be avoided? Suppose we have 2 models..
1st model with training accuracy of 0.85
1st model with validation accuracy of 0.78
2nd model with training accuracy of 0.79
2nd model with validation accuracy of 0.77.
Which of the model should be preferred? Or shall i prefer 2nd model even though 1st one is having a higher accuracy?

A: From what you have shared, I believe you should pick the first one since it has higher accuracy on the validation data. The reason is that you are optimizing your models with a loss function which aims to decrease the training loss. Therefore, it can overfit to your data to yield good accuracy scores on your training loss whereas in reality it cannot generalize to data out of your training data. In what you have shared I see that you have 2 metrics at your hand; namely, the training loss and the validation loss. When you are working on models, you should also have a test dataset which is separate from these two. You would train on your training data, and fine-tune(pick hyper parameters) for your model by trying to increase the performance on the validation data. After you have picked your model, you should evaluate it regarding its performance on the test dataset which you have not introduced to your model up to this point. It would show you really how your model generalizes to unseen data. The reason you do this is because when training you optimized your model regarding its performance on the training set. When picking the best hyper-parameters you were biased to do well on the validation set. Whereas, you have never seen its performance on the test dataset therefore, it in a sense reflects real world situations that your model would face if it were to be deployed. Hope this helps.


text:
Q: How does arithmetic floating point rounding in RISC-V work? I am currently working on my own RISC-V (rv64gc) emulator. Everything went smoothly so far, however the floating point rounding mode is giving me a headache.
The RV ISA comprises of the following 5 floating point rounding modes:

*

*RNE (Round to Nearest, ties to Even)

*RTZ (Round towards Zero)

*RDN (Round down / towards negative infinity)

*RUP (Round up / towards positive infinity)

*RMM (Round to Nearest, ties to Max Magnitude)

When thinking about the instructions that convert floats to integers (e.g. FCVT.W.S), these modes all make sense. However these aren't the only ones with encoded rounding modes. The instructions converting integers to floats also have a 3 bit encoding space for the rounding mode, as well as all the floating point arithmetic instructions do.
Now lets say we got 2 floats and want to add them together. If one of them is a large number and the other is a small number with lots of digits after the floating point, we might exceed the storage capacity of a float. Whenever this happens, are the lowest bits/digits just discarded? If yes, why would there be a rounding mode given then? Otherwise, how would the different modes work and what would they round to?
Generally rounding after discarding (which kinda is a must do without any extra bits available) makes no sense really, since after the least significant bits have been discarded, there is no need to further decrease precision by rounding because the storage is now enough for what's left of the original number. So is the rounding happening before the last bits are cut off and the resulting zeros are then discarded?
Example:
Imagine we have a Mantissa of 011010111 after adding two numbers, but actually a Mantissa's size is 8 bits at max (So we have to get rid of 1 bit).
RNE: Option 1 is 011010110 (down), Option 2 is 011011000 (up)
This is a tie: Which option would it choose?
After any of both options no further data is lost because only a 0 is discarded.
RTZ: Only option is 011010110 (towards Zero / down)
The last zero can now be discarded without any further data lost.
RDN and RUP: Dependent on the sign bit, there always is only one way to go and the last bit will turn to 0 so no further data is lost when discarding that bit.
RMM: This always has only one option too (away from 0 / up in this example).
When looking at another example with a 0 currently set as least significant bit, does it simply not round because incrementing/decrementing the number would actually increase precision here?
In case there is rounding happening before bits are discarded, does the CPU just temporarily hold a bigger result when the instructions are executed which is then used to get the rounded result of the correct size?
If I got something wrong fundamentally please correct me, likewise any help is appreciated!!

A: For RNE, 011010111 would round to 011010110 if and only if there were no other 1s that underflow.  011010110 is even because the LSb is 0.  RNE is the most common and default mode (per IEEE):
       LGRS
011010111??
        ^^^
        underflow bits

L = LSb
G = "Guard bit"
R = "Rounding bit"
S = "Sticky bit" (is "latched", once set to 1 it stays at 1)

LGRS
x11x round up
x101 round up
0100 tie, round to even which in this case is down
1100 tie, round to even which in this case is up


text:
Q: Blue Prism, C# variable lifetime code stage I am trying to use the code stage in C# inside Blue Prism. I am using a custom object that I would like to be able to pass from one code stage to another inside Blue Prism.
I cant serialize my object, therefore I can't use Blue Prism Variable as output.
Here is my question: How can I keep a variable lifetime from one code stage to another? From my understanding, a variable gets removed from the heap whenever it is not referenced anymore in the code.
Any hint?
Thank you!

A: If you define the variable in the 'Global Code' then you can access it from code stages anywhere in your object.


text:
Q: Error bars not plotting correctly on barplot I am having trouble getting my error bars to plot correctly. Here is my data frame:
> d
         Date Plate.1 Plate.2 Plate.3 Plate.4 Plate.5 Plate.6 Plate.7 Plate.8 Sum Average        SE Treatment
1  2014-10-15       2       2       0       5       8      11      11       0  39   4.875 1.6304852         1
2  2014-11-12       5       4      11       6       7       2       9       6  50   6.250 0.9955257         1
3  2014-12-11       1       0       0       0       0       0       0       1   2   0.250 0.1636634         1
4  2015-02-11       0       0       4       0       2       1       0       1   8   1.000 0.5000000         1
5  2015-03-09       0       0       0       0       0       0       0       0   0   0.000 0.0000000         1
6  2014-10-15      30      22      24      19      10      16      19      42 182  22.750 3.4369318         2
7  2014-11-12       8       5       4       9      12      23      14      10  85  10.625 2.1207942         2
8  2014-12-11       0       5      21      19       2       9       4       0  60   7.500 2.9215945         2
9  2015-02-11      16      11       5       8       5      17       0       0  62   7.750 2.3126207         2
10 2015-03-09       0       0       0       1       0       0       0       0   1   0.125 0.1250000         2

I am using this code to produce a grouped barplot:
ggplot(d, aes(x=Date, y=Average, fill = Treatment)) +
  geom_bar(position="dodge", stat="identity") +
  geom_errorbar(aes(ymin=Average-SE, ymax=Average+SE),
                width=.2,
                position = position_dodge(.9))

For some reason the error bars are not plotting correctly and the graph looks like this:

Hopefully the solution is a simple one, however it is eluding me. Thanks in advance for any help!

A: Updated in light of your comment - for this type of plot, you can assign the value for position_dodge to a variable and use that for all subsequent plots.
I hit on the value of 20 with a little trial and error; if the other data you're working with is very different numerically, you may need to fine tune this.
d <- data.frame(Date=c("2014-10-15", "2014-11-12", "2014-12-11",
                "2015-02-11", "2015-03-09", "2014-10-15",
                "2014-11-12", "2014-12-11", "2015-02-11",
                "2015-03-09"),
                Average=c(4.875, 6.250, 0.25, 1, 0,
                22.75, 10.625, 7.5, 7.75, 0.125),
                Treatment=c(rep(1, 5), rep(2, 5)),
                SE=c(1.6304852, 0.9955257, 0.1636634, 0.5, 0,
                3.4369318, 2.1207942, 2.9215945, 2.3126207, 0.125))
d$Date <- as.Date(d$Date)
d$Treatment <- factor(d$Treatment)
library(ggplot2)
pd1 <- 20
ggplot(d, aes(x=Date, y=Average, fill=Treatment)) +
    geom_bar(width=pd1,
             position=position_dodge(pd1),
             stat="identity") +
    geom_errorbar(aes(ymin=Average-SE, ymax=Average+SE),
                  width=pd1 / 2,
                  position=position_dodge(pd1))

giving:

I think the problem you were having is that using position="dodge" allows ggplot2 to calculate an 'optimal' dodge. However you need to see/state the value explicitly to pass it as an argument to geom_errorbar.
Setting the width in geom_bar to the same value as position_dodge in both geom_bar and geom_errorbar (here pd1 <- 20) overcomes this.


text:
Q: How does distinguishability of boxes change the number of ways to distribute n objects into separate boxes I was going through problems related to distributing n distinguishable objects all into boxes, a in the first, b in the second, c in the third where a+b+c = n. The solutions I've seen usually comes to the form of $\frac{n!}{a!b!c!}$  I am wondering, for this solution to be true,  are the boxes distinguishable or not distinguishable?
If a, b, c etc. are all different similar to this problem, it seems like we would need to multiply the factorial of the number of boxes to $\frac{n!}{a!b!c!...}$ if the boxes are distinguishable? What if we specify, like in the question, that the $a$, $b$ ... objects must go into specific boxes, does that make the boxes distinguishable (and yet per the solution we would suppress the 5! term)?
For this problem, the number of ways to distribute 13 cards to four people is $\frac{52!}{13!^4}$. If I split the deck into 4 specific sets of 13 (and label each set as A, B, C, D), doesn't $\frac{52!}{13!^4}$ include the combination where one person gets A, another gets B, then C, then D, as well as one person getting D, then C, then B, then A (and all other permutations of these four sets). In this case, it seems like the people are distinguishable?
Edit:
With respect to the duplicate, I have some followup questions.
For partitions of all different sizes, why does whether the ordering matter or not not change the solution of $\frac{n!}{n_1!n_2!\dots n_r!}$?
The duplicate states that if the partitions are of equal sizes, then an r! term must be in the denominator to discount for order (I assume this means the r boxes are indistinguishable?). However, in the poker problem I linked above, the number of ways to distribute 13 cards to 4 people was given as $\frac{52!}{13!^4}$ even though I don't think the people were considered distinguishable in that problem. I feel like I'm missing something?

A: Consider the case of having distinguishable boxes, which we can just label $A, B, C$. We can arbitrarily decide to fill $A$ first, then $B$, then $C$.
How many ways can we put $a$ elements in box $A$? That is well-known to be $n \choose a$. Now how many ways can we put $b$ of the remaining $n-a$ elements in box $B$?. This is well-known to be $n - a \choose b$. And finally, how many ways can be put the remaining $c$ elements in box $C$? Obviously $1$.
Since these are independent, the total number of ways to do all three is their product $${n\choose a}{n - a \choose b}1 = \frac{n!}{a!(n-a)!}\frac{(n-a)!}{b!(n-a-b)!} = \frac {n!}{a!b!c!}$$
I.e., the formula $\frac {n!}{a!b!c!}$ counts the number of ways of distributing $n$ objects among distinguishable boxes (and similarly when there are more boxes).
When the boxes are indistinguishable, it becomes more complicated. But first note that if $a \ne b, b \ne c, c \ne a$, then the boxes are automatically distinguishable! $A$ is the box that will end up with $a$ elements, $B$ is the box that will end up with $b$ elements, and $C$ is the box that will end up with $c$ elements.
Now if all three of $a,b,c$ are the same (so $n=3a$), then the boxes become indistinguishable, so we have to divide by the possible arrangements of the boxes to get the count in this case: $$\frac{(3a)!}{3!a!^3}$$
If $a$ is different, but $b = c$, then $A$ is distinguishable, but $B$ and $C$ are not, so we have to divide by the possible arrangements of $B$ and $C$:
$$\frac{n!}{2!a!b!^2}$$


text:
Q: Does TIME_WAIT affect dynamic ports? I've read a bit about TIME_WAIT connections, and know they should be harmless to my server (connection closed, so no resource connected with this socket).
Recently, my server reached the magic number of 60k ports in TIME_WAIT state; and I'm wondering if I'll run out of free ports?
My server uses dynamic local ports from this pool set in kernel:
# sysctl net.ipv4.ip_local_port_range
net.ipv4.ip_local_port_range = 32768    61000

When creating a new connection will it use one of the TIME_WAIT ports? or try to bind with a different, open port?
If I set this variable to ports 1024-65535, What would happen if I have some application running on ports in that range?
This is not a question how to minimize the wait of TIME_WAIT connection states.
Current kernel modifications:
# sysctl net.ipv4.tcp_tw_recycle
net.ipv4.tcp_tw_recycle = 0
# sysctl net.ipv4.tcp_tw_reuse
net.ipv4.tcp_tw_reuse = 1
# sysctl net.ipv4.tcp_fin_timeout
net.ipv4.tcp_fin_timeout = 30
# sysctl net.ipv4.tcp_timestamps
net.ipv4.tcp_timestamps = 1
# sysctl net.ipv4.tcp_sack
net.ipv4.tcp_sack = 1


text:
Q: NullPointerException in Tree? public class Node {

  int value;
  List<Node> childNodes;

  Node(int x) {
    value = x;
  }
}

Above is the definition of the tree node and we have a tree.
Node root = new Node(0);
Node n1 = new Node(1);
root.childNodes.add(n1);  Line 1

This is how I construct the initial tree structure in main, however, I got a nunllpointerexception in line 1. Anybody knows the reason?

A: where is childNodes initiated?
root.childNodes.add(n1);  Line 1

must throw a NPE.
add this in your Node class and it will work:
List<Node> childNodes = new ArrayList<>();

or
Node root = new Node(0);
Node n1 = new Node(1);
root.childNodes = new ArrayList();
root.childNodes.add(n1);


text:
Q: Using StringBuilder to Append Contents of a List Box to a Text File I am trying to create a programme in visual studio where, once you press a button, the contents of a ListBox are added to a text file.
I am currently using a StringBuilder to do this as my professor has told me this is the easiest and quickest way -I am aware I can use StreamWriter as well.
Dim CreateReciept As New System.Text.StringBuilder

CreateReciet.Append(lstOrderForm.Text & vbCrLf)

System.IO.File.WriteAllText("order_receipt.txt", Text.ToString())

Process.Start("order_receipt.txt")

This is my code as of now; however, when I run it, it produces a blank form rather than the contents of the list box.

A: You are looking at the wrong thing. ListBox.Text will only provide the text of the currently selected item:

When the value of this property is set to a string value, the ListBox searches for the item within the ListBox that matches the specified text and selects the item. You can also use this property to determine which items are currently selected in the ListBox. If the SelectionMode property of the ListBox is set to SelectionMode.MultiExtended, this property returns the text of the first selected item. If the SelectionMode property of the ListBox is not set to SelectionMode.None, this property returns the text of the first selected item.

Instead loop through the ListBox.Items collection:

This property enables you to obtain a reference to the list of items that are currently stored in the ListBox. With this reference, you can add items, remove items, and obtain a count of the items in the collection. For more information about the tasks that can be performed with the item collection, see the ListBox.ObjectCollection class reference topics.

Lastly don't use Text.ToString, that won't work. Instead use your StringBuilder:
Dim sb As New StringBuilder

For Each item In lstOrderForm.Items
    sb.Append(item.ToString() & vbCrLf)
Next

System.IO.File.WriteAllText("order_receipt.txt", sb.ToString())

Process.Start("order_receipt.txt")

The code produces the following output for me:

A: Try the following instead:
Dim CreateReciet As New System.Text.StringBuilder

CreateReciet.Append(lstOrderForm.Text & vbCrLf)

System.IO.File.WriteAllText("order_receipt.txt", CreateReciet.ToString())

Process.Start("order_receipt.txt")

As I said above though, your stringbuilder isn't doing anything useful, so you could just write:
System.IO.File.WriteAllText("order_receipt.txt", lstOrderForm.Text & vbCrLf)
Process.Start("order_receipt.txt")


text:
Q: Trouble with deserializing Avro data in Scala I am building an Apache Flink application in Scala which reads streaming data from a Kafka bus and then performs summarizing operations on it. The data from Kafka is in Avro format and needs a special Deserialization class. I found this scala class AvroDeserializationScehema (http://codegists.com/snippet/scala/avrodeserializationschemascala_saveveltri_scala):
package org.myorg.quickstart
import org.apache.avro.io.BinaryDecoder
import org.apache.avro.io.DatumReader
import org.apache.avro.io.DecoderFactory
import org.apache.avro.reflect.ReflectDatumReader
import org.apache.avro.specific.{SpecificDatumReader, SpecificRecordBase}
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.java.typeutils.TypeExtractor
import org.apache.flink.api.common.serialization._
import java.io.IOException

class AvroDeserializationSchema[T](val avroType: Class[T]) extends DeserializationSchema[T] {
  private var reader: DatumReader[T] = null
  private var decoder : BinaryDecoder = null

  def deserialize(message: Array[Byte]): T = {
    ensureInitialized()
    try {
      decoder = DecoderFactory.get.binaryDecoder(message, decoder)
      reader.read(null.asInstanceOf[T], decoder)
    }
    catch {
      case e: IOException => {
        throw new RuntimeException(e)
      }
    }
  }

  def isEndOfStream(nextElement: T): Boolean = false

  def getProducedType: TypeInformation[T] = TypeExtractor.getForClass(avroType)

  private def ensureInitialized() {
    if (reader == null) {
      if (classOf[SpecificRecordBase].isAssignableFrom(avroType)) {
        reader = new SpecificDatumReader[T](avroType)
      }
      else {
        reader = new ReflectDatumReader[T](avroType)
      }
    }
  }
}

In my streaming class i use this as follows:
val stream = env
        .addSource(new FlinkKafkaConsumer010[String]("test", new
AvroDeserializationSchema[DeviceData](Class[DeviceData]), properties))

where DeviceData is an Scala case class defined in the same project
/** Case class to hold the Device data. */
case class DeviceData(deviceId: String,
                    sw_version: String,
                    timestamp: String,
                    reading: Double
                   )

I get the following error on compiling the StreamingKafkaClient.scala class
Error:(24, 102) object java.lang.Class is not a value
        .addSource(new FlinkKafkaConsumer010[String]("test", new
AvroDeserializationSchema[DeviceData](Class[DeviceData]), properties))

Also tried
val stream = env
        .addSource(new FlinkKafkaConsumer010[String]("test", new
AvroDeserializationSchema[DeviceData](classOf[DeviceData]), properties))

With that i get a different error:
Error:(21, 20) overloaded method constructor FlinkKafkaConsumer010 with alternatives:
  (x$1: java.util.regex.Pattern,x$2: org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String] <and>
  (x$1: java.util.regex.Pattern,x$2: org.apache.flink.api.common.serialization.DeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String] <and>
  (x$1: java.util.List[String],x$2: org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String] <and>
  (x$1: java.util.List[String],x$2: org.apache.flink.api.common.serialization.DeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String] <and>
  (x$1: String,x$2: org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String] <and>
  (x$1: String,x$2: org.apache.flink.api.common.serialization.DeserializationSchema[String],x$3: java.util.Properties)org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010[String]
 cannot be applied to (String, org.myorg.quickstart.AvroDeserializationSchema[org.myorg.quickstart.DeviceData], java.util.Properties)
        .addSource(new FlinkKafkaConsumer010[String]("test", new AvroDeserializationSchema[DeviceData](classOf[DeviceData]), properties))

I am completely new at Scala (this is my first scala program) so i know i am missing something fundamental here. As i try to learn Scala could someone please point out what am i doing wrong. My intent is to basically read avro encoded data from Kafka into Flink and do some operations on streaming data. I could not find any examples of the usage of AvroDeserializationSchema class, seems to me this is something that should be natively built into Flink packages.

A: In order to get a class object in Scala, you want classOf[DeviceData], not Class[DeviceData]
new AvroDeserializationSchema[DeviceData](classOf[DeviceData])

I could not find any examples of the usage of AvroDeserializationSchema class

I found one (in Java)
Also, it looks like in Flink 1.6 release, they will add this class rather than you copying from elsewhere. FLINK-9337 & FLINK-9338
As mentioned in the comments, if you would like to use the Confluent Avro Schema Registry rather than giving a class type, see this answer, or refer to the code in the above Github link
Additionally, if you are running Kafka 0.11+ (or Confluent 3.3+), then you should ideally be using FlinkKafkaConsumer011 along with the class you are deserializing to
new FlinkKafkaConsumer011[DeviceData]


text:
Q: How to use Maven Profile Name as a variable I need to build a war file that can call a JDBC connection depending on it's profile name.
When I build with the dev profile, I need it to call the dev.properties file. And when I build with the prod profile, I need it to read from the prod.properties file.
The idea that I came up with is to use the profile name as a variable somehow, but I can't figure out how to do it.
POM.XML
<profile>
    <id>dev</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <profile-id>dev</profile-id>
    </properties>
</profile>
<profile>
    <id>prod</id>
    <properties>
        <profile-id>prod</profile-id>
    </properties>
</profile>

servlet-context.xml
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>classpath:${profile-id}.properties</value>
    </property>
</bean>
<property name="dataSourceProperties">
    <props>
        <prop key="url" >${jdbc}</prop>
        <prop key="user">user</prop>
        <prop key="password">password</prop>
        <prop key="implicitCachingEnabled">true</prop>
    </props>
</property>

A: You must use the filtering concept of maven. See http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
Add to your pom something like:
  <resource>
    <directory>directory.to.servlet/servlet-context.xml</directory>
    <filtering>true</filtering>
  </resource>

By replacing directory.to.servlet with the real directory


text:
Q: Replace email domain for the guest accounts in Azure AD I am looking to replace email domain (suffix after @) for the guest users in Azure AD via Powershell. As an example, i need to change email address for jdoe from jdoe@abc to @jdoe.xyz
I tried below command but it is not working.
Get-AzureADUser | where {$.UserType -eq 'Guest' -and $.mail -match "@abc.com"} |
ForEach-Object  { Set-AzureADUser -ObjectId $($_.ObjectId) -MailNickName "abc@xyz" }
The above might be an incomplete command. Someone suggest what would be the right approach here?

A: I tried to reproduce the same in my environment to Replace email domain for the guest accounts in Azure AD using Powershell:
To change the email domain for user accounts that have the account type "guest" in Azure Ad using Powershell, you can use below script.

*

*Connect to Azure AD using connect-AzureAd cmdlet.

*Use the below cmdlet to retrieve the user accounts the have account type "guest"
Get-AzureAdUser -Filter "accountEnabled eq true and userType eq'Guest'"

Full PowerShell Script
Install-Module AzureAD
Connect-AzureAD
$guestAccounts = Get-AzureAdUser -Filter "accountEnabled eq true and userType eq 'Guest'"
foreach ($guestAccount in $guestAccounts) {
$newUPN = $guestAccount.UserPrincipalName.Replace("@olddomain.com","@newdomain.com")
Set-AzureADUser -ObjectId $guestAccount.ObjectId -UserPrincipalName $newUPN
}
Get-AzureAdUser -Filter "accountEnabled eq true and userType eq 'Guest'"

User UserPrincipal domain changed successfully.


text:
Q: Can a diagram be created from deadlock xml extracted from the ring buffer in SQL Server 2008? In later versions of SQL_Server, we view the event file in the object browser to look at deadlock diagrams. This particular client has SQL 2008 (compatibility 2005) and the only copy of deadlocks have been extracted from the ring buffer using the below script:
SELECT
   xed.value('@timestamp', 'datetime2(3)') as CreationDate,
   xed.query('.') AS XEvent
FROM
(
   SELECT CAST([target_data] AS XML) AS TargetData
   FROM sys.dm_xe_session_targets AS st
   INNER JOIN sys.dm_xe_sessions AS s
      ON s.address = st.event_session_address
   WHERE s.name = N'system_health'
         AND st.target_name = N'ring_buffer'
) AS Data
CROSS APPLY TargetData.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]') AS XEventData (xed)
ORDER BY CreationDate DESC

The format is not compatible with our xdl viewers. Is there any way to get a diagram from the returned XML below?:
<event name="xml_deadlock_report" package="sqlserver" id="123" version="1" timestamp="2018-07-04T00:15:14.667Z">
  <data name="xml_report">
    <type name="unicode_string" package="package0" />
    <value><deadlock>
 <victim-list>
  <victimProcess id="process3cf048"/>
 </victim-list>
 <process-list>
  <process id="process3cf048" taskpriority="0" logused="0" waitresource="PAGE: 11:1:45050737" waittime="3573" ownerId="19491756" transactionname="user_transaction" lasttranstarted="2018-07-04T01:14:58.003" XDES="0x31b45b400" lockMode="S" schedulerid="4" kpid="2280" status="suspended" spid="72" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2018-07-04T01:05:29.587" lastbatchcompleted="2018-07-04T01:05:29.587" clientapp="SQLAgent - TSQL JobStep (Job 0x3404686D1D7A2F478F69577F5EEBAE41 : Step 1)" hostname="ae-es" hostpid="5340" loginname="ae\rmsSYSTEM" isolationlevel="read committed (2)" xactid="19491756" currentdb="11" lockTimeout="4294967295" clientoption1="673185824" clientoption2="128056">
   <executionStack>
    <frame procname="" line="2177" stmtstart="149730" stmtend="150314" sqlhandle="0x03000b00389b050021b69200bca300000100000000000000">
    </frame>
    <frame procname="" line="92" stmtstart="8170" stmtend="9080" sqlhandle="0x03000b00dea9f7571cb80601e6a300000100000000000000">
    </frame>
    <frame procname="" line="53" stmtstart="4514" stmtend="5792" sqlhandle="0x03000b00333d1b553bc7b200d3a300000100000000000000">
    </frame>
    <frame procname="" line="2" stmtstart="6" sqlhandle="0x01000b00b5d2e138601f5208040000000000000000000000">
    </frame>
   </executionStack>
   <inputbuf>

exec EBB_PSF_ImportSales &apos;G:\progra~1\es\winrms\import&apos;   </inputbuf>
  </process>
  <process id="process4483b88" taskpriority="0" logused="6076" waitresource="PAGE: 11:1:132712" waittime="11747" ownerId="19493225" transactionname="user_transaction" lasttranstarted="2018-07-04T01:15:03.157" XDES="0x1344f8cc0" lockMode="S" schedulerid="6" kpid="5948" status="suspended" spid="64" sbid="0" ecid="0" priority="0" trancount="3" lastbatchstarted="2018-07-04T01:15:03.157" lastbatchcompleted="2018-07-04T01:15:03.153" lastattention="2018-07-03T23:45:37.360" clientapp="ECommerce WebService" hostname="ae-es" hostpid="3472" loginname="rmsSYSTEM" isolationlevel="read committed (2)" xactid="19493225" currentdb="11" lockTimeout="4294967295" clientoption1="673187936" clientoption2="128056">
   <executionStack>
    <frame procname="" line="359" stmtstart="36280" stmtend="39240" sqlhandle="0x03000b00bdc1b416537f2601dfa700000100000000000000">
    </frame>
    <frame procname="" line="79" stmtstart="4356" stmtend="4452" sqlhandle="0x03000b00f6e5a817d68c2601dfa700000100000000000000">
    </frame>
    <frame procname="" line="1" stmtstart="98" sqlhandle="0x01000b00c20b1a2dd036be87000000000000000000000000">
    </frame>
    <frame procname="" line="1" sqlhandle="0x000000000000000000000000000000000000000000000000">
    </frame>
   </executionStack>
   <inputbuf>

(@p0 xml,@p1 xml output,@RETURN_VALUE int output)EXEC @RETURN_VALUE = [dbo].[EBB_PSFXML_Process] @xml = @p0, @xml_out = @p1 OUTPUT   </inputbuf>
  </process>
 </process-list>
 <resource-list>
  <pagelock fileid="1" pageid="45050737" dbid="11" objectname="" id="lockdb734b80" mode="IX" associatedObjectId="72057595923464192">
   <owner-list>
    <owner id="process4483b88" mode="IX"/>
   </owner-list>
   <waiter-list>
    <waiter id="process3cf048" mode="S" requestType="wait"/>
   </waiter-list>
  </pagelock>
  <pagelock fileid="1" pageid="132712" dbid="11" objectname="" id="lock80131400" mode="IX" associatedObjectId="72057594217758720">
   <owner-list>
    <owner id="process3cf048" mode="IX"/>
   </owner-list>
   <waiter-list>
    <waiter id="process4483b88" mode="S" requestType="wait"/>
   </waiter-list>
  </pagelock>
 </resource-list>
</deadlock>
</value>
    <text />
  </data>
</event>

A: Yes. That's XML embedded in XML, so you need to extract and un-escape the deadlock XML with a query like:
select cast(@doc.value('(/event/data/value/.)[1]', 'nvarchar(max)') as xml) deadlock

Then open the XML results in SSMS and save the file with an .xdl extension.  Then re-open it with SSMS and you'll see the deadlock graph.

A: Thanks to David Browne's answer, the following statement returns the correctly formatted XML:
SELECT
   xed.value('@timestamp', 'datetime2(3)') as CreationDate,
   cast(XEventData.xed.value('(data/value)[1]', 'nvarchar(max)') as xml) as DeadlockGraph2
FROM
(
   SELECT CAST([target_data] AS XML) AS TargetData
   FROM sys.dm_xe_session_targets AS st
   INNER JOIN sys.dm_xe_sessions AS s
      ON s.address = st.event_session_address
   WHERE s.name = N'system_health'
         AND st.target_name = N'ring_buffer'
) AS Data
CROSS APPLY TargetData.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]') AS XEventData (xed)
ORDER BY CreationDate DESC


text:
Q: FTDI Vinculum code read out protection I designed a USB dual host based on a FTDI's VNC2-32L1B. I'd want to protect its firmware from being read/copied cause it contains pretty sensitive data (private keys, etc.), but the VNC2 has no read out protection option at all - everyone who has a debugger interface is able to download the flash image.
So my question is wheter is there any hardware or software possiblity to protect the chip from readout? I've thought about cutting out the programming pins and writing my own bootloader, but I'd prefer a simpler or (perhaps) better solution.
Thanks in advance for any ideas.

A: How you approach this depends, of course, on who your adversary is and how valuable the information would be to them. Is your adversary the Mossad, or your neighbor's kid? Storing nuclear launch codes clearly requires a different level of protection than storing the password for your lawn sprinkler automation system :)
Cutting the programming pins will only make the task slightly harder; even a moderately-determined attacker could etch away the plastic and connect to the pins. I realize cost is an issue here, but you may consider putting the code on a microcontroller that does support readout protection, which will protect you against a casual adversary, but of course not against a well-funded one.
The problem of how to protect secrets (keys etc.) on hardware devices that are not always under the owner's physical control is a very large topic, with solutions ranging in price over several orders of magnitude.  Perhaps if you gave some more detail I could point you to the right information, but as it stands, all I can say really is "it depends".


text:
Q: Qt vector size remains same I have two classes: point and mainwindow.
I declared pointer of point class in mainwindow.h as:
point *item;

I create an object of point class in mainwindow.cpp:
void MainWindow::drawPoint(){
    item = new point;
    scene->addItem(item);
}

This function enables painting of point in qgraphicsscene.
There is a vector that stores QPointF values in point class. The storage class is the type of vector.
QVector<storage> point_vector;

set_point()  is defined in storage class that sets the value of point p1.
storage store_point;
store_point.set_point(p1);
point_vector.push_back(store_point);

On iterating the vector in mainwindow.cpp,
for(it = item->point_vector.begin(); it != item->point_vector.end(); it++)
{
    qDebug() << "size" << item->point_vector.size() << "\n";
}

Even though I create multiple points in the scene, the size of vector always remains 1.
I think this might be happening because every time the function drawPoint() is called, the previous object of point class is over-ridden.
I am unable to figure out how to resolve this issue. Any help will be appreciated.
Relevant Code
http://www.paste.org/74408

A: Your code is spread out too much, you should try creating proper classes...
As far as I can see, the "point_vector" that gets pushed back items is a local variable declared / defined in  point.cpp
You did not post point.h file, but I am guessing that it has point_vector defined as part of the class point... But you are not using the point_vector member variable in the cpp, you are using the locally declared one
It would be easier to see if, like the comments on your question say, you posted a more complete portion of the code.


text:
Q: No changes to original dataframe after applying loop I have a list of dataframes such that
df_lst = [df1, df2]

I also created a function which removes the rows with '0' in the dataframe:
def dropzeros(df):
    newdf = df[df['x']!=0.0]
    return newdf

I tried applying this through a loop and placed an assignment variable within the loop, but the original dataframe remained unchanged even after running the loop.
for df in df_lst:
    df = dropzeros(df)

I also tried using list comprehensions to go about it
df_lst = [dropzeros(df) for df in df_lst]

I know the function works since when i apply print(len(df)) before and after the command dropzeros(df) there was a drop in the len, however, may I know how might I go about this problem such that my original dataframe is altered after running the loop?

A: That's because the variable df in your for loop does not reference a value in your list. You are creating a variable df afresh each iteration of your loop.
You can assign via enumerate and pipe your function:
for idx, df in enumerate(df_lst):
    df_lst[idx] = df.pipe(dropzeros)