text:
Q: Redirect rule Apache multiple Custom post type to posts I read the related questions above but no answers...so here is my problem :
I recently created several custom post types . They are 13 of them located located in /news/ folder.
For some personal reasons, yesterday I decided not to use the Custom post type anymore and rather re-write all of them as a "usual post" in my WP blog.
So the 13 Custom PT are now duplicated.
I could have delete them but they are already indexed by Google and their URL's are already around on the web, so I want to maintain them for a while to be sure that I do not loose any traffic of course.
The problem is that this morning, Google web master tool did not like all these duplicated contents at all.
I need to redirect all the 13 URL's to the new posts created.
How can I redirect 13 URL's to 13 new URL's ? Is this rule enough ? Should I also mention not to follow the Custom Type URL ?
Here is the construction of the URL's:
CUSTOM POST TYPES :
www.mysite.com/myblog/news/custom-post-type-title/
URL OF THE NEW DUPLICATED ARTICLE :
www.mysite.com/myblog/post-type-title
Thank you in advance for your help,
Cheers.

A: To tell Google about duplicates, use code 301 when redirecting with RewriteRule (add [R=301] at the end of it) to denote "Permanently moved" on all URLs except for the currently valid one.


text:
Q: Fetch the data from Date and Time Calculated column I am trying to fetch the result from list based on 3  conditions( Month Name,Employee,Department).
In my SharePoint List(Month Name is calculated column fetching month from column "Joining Date") .
Below is the caml query trying to get fetech the value using column(Month Name) but found no luck.I had gone through the internal of the column "Month Name" and I see "Month" as internal name
can any one help me in knowing what went wrong in below code
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='Employee'/><Value Type='Text'>" + Employee + "</Value></Eq><Eq><FieldRef Name='Department'/><Value Type='Text'>" + Department+ "</Value></Eq><Eq><FieldRef Name='Month Name'/><Value Type='Calculated'>" + monthname+ "</Value></Eq></And></Where></Query></View>")

A: You can only nest two Eq directly in one And statement, so you need to add another And statement, like this:
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='Employee'/><Value Type='Text'>" + Employee + "</Value></Eq><And><Eq><FieldRef Name='Department'/><Value Type='Text'>" + Department+ "</Value></Eq><Eq><FieldRef Name='Month Name'/><Value Type='Calculated'>" + monthname+ "</Value></Eq></And></And></Where></Query></View>")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculation of curvature in the level set method I understand that the gradient of the unit normal vector is the curvature, but how was equation (4) in the link below derived?
https://math.mit.edu/classes/18.086/2007/levelsetnotes.pdf


text:
Q: Instanced rendering to texture array Is it possible to render to multiple textures (i.e. cube map faces, or cascaded SMs) with one draw call? I can bind a texture slice (or a cubemap face) to framebuffer, but that doesn't seem to let me render to more than one slice per call.
I can't use geometry shaders as they aren't supported in webgl, unfortunately.

A: In WebGL? No. Desktop GL and OpenGL ES can use layered framebuffers to render to faces of a cubemap or layers of an array texture. But not WebGL 1.0 or 2.0.
You can of course bind different slices to the same framebuffer as distinct attachments, but each fragment you render goes to all of those slices. You can use write masks to turn off writing to specific framebuffers, but not within a draw call. So that's probably not what you want.
It certainly isn't going to help with shadow maps.


text:
Q: flask api auth middleware not working with POST method I have a basic flask api in which I have implemented a middleware to check for authorization header (used firebase_admin sdk for authentication). Now it works perfectly for any GET request, but doesn't work for an endpoint which is a POST request. Below is some relevant code related to my problem:
@app.route('/is_subscribed', methods=['POST'])
@check_auth
def is_subscribed():
    if request.method == 'POST':
        user = request.user
        try:
            itemId = request.get_json()['item_id']

            subscriptions = db. \
                                collection('users'). \
                                document(user['uid']). \
                                get(). \
                                to_dict()['subscriptions']

            if itemId in subscriptions:
                return {
                    'message': 'User is subscribed to this item',
                    'status': 'success',
                    'data': True
                }, 200
        except Exception as e:
            return {
                'message': 'Error checking subscription',
                'status': 'error'
            }, 400

check_auth middleware:
def check_auth(f):
    @wraps(f)
    def wrap(*args,**kwargs):
        if not request.headers.get('authorization'):
            return {'message': 'No authorization token provided'}, 400
        try:
            user = auth.verify_id_token(request.headers['authorization'])
            request.user = user
        except:
            return {'message':'Invalid token provided.'}, 400
        return f(*args, **kwargs)
    return wrap

Whenever I hit this endpoint is_subscribed I get a 400 request in my server logs:
127.0.0.1 - - [13/Aug/2022 11:12:09] "POST /is_subscribed HTTP/1.1" 400 -
I cannot identify what is the exact thing which is causing this, but if I remove this check_auth middleware, it works but now the route is unauthenticated and no access to user data, defeating the whole purpose...
Can someone provide some insights or any solution?
EDIT-1:
Frontend request:
const BASE_URL = 'http://127.0.0.1:5000';

const api = axios.create({
    baseURL: BASE_URL,
});

export const isSubscribed = async ({
    itemId,
    token,
}: {
    itemId: string;
    token: string;
}) => {
    try {
        const response = await api.post(
            '/is_subscribed',
            {
                item_id: itemId,
            },
            {
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    authorization: `${token}`,
                },
            },
        );
        return response.data;
    } catch (error) {
        showToast('Error checking subscription status', 'error');
        return null;
    }
};

The request always executes under catch...


text:
Q: How to set jquery modal to show every 3 days with cookie? I built a modal that I want to show every 3 days. I installed the jquery cookie plugin from https://github.com/carhartl/jquery-cookie and have set up a test, but it always shows that the cookie exists even though it's set to expire after 5 seconds. What am I doing wrong?
jQuery(document).ready(function( $ ) {

$.cookie('modal', '1', { expires: 5000 });

if( $.cookie('modal') === null ) {  // if expired / non-existent
    alert('not exists');
}
else{
    alert('exists');
}
});

NEW CODE
if($.cookie('modal') == null){
    alert('not exists');
    $.cookie('modal', '1', { expires: 3 });
}
else{
    alert('exists');
}


text:
Q: Applescript: Wait for an action/event to complete I am writing a script to download Free/non-Free applications from iTunes Store.
For each download , it is taking 5 to 10 seconds.
For example:
repeat 1000 times
download_app()
end repeat
on download_app()
download stuff ....
delay 10
end download_app
For downloading one application 1000 times, it is taking big amount of time and I want to optimize this timing. Instead of using delay 10, is there any other way to do this ?
Is there an way to get downloading status / busy status of iTunes?
Please suggest.
Advanced Thanks
Rahman

A: I don't have a specific solution, however the following code may provide a useful example:
tell application "System Events"
    tell application process "Safari"
        repeat
            if (accessibility description of (get properties of button 1 of text field 1 of splitter group 1 of group 2 of tool bar 1 of window 1)) does not contain "stop" then exit repeat
        end repeat
    end tell
end tell

This code pauses a script until a webpage has finished loading. It does so by entering an infinite loop and breaking out of the loop upon reaching a condition.
The condition appears rather complex, but it really checks something simple. At the right side of the Safari URL field there's a stop/reload button. While the page is loading, it shows a stop icon. Once the page stops loading, it shows a reload icon. Hence, when we no longer see the stop icon, the page must have finished loading.
Most of the code rather cryptically navigates the GUI to identify the button described. The term accessibility description is used to identify the current state of the button. The accessibility description is what is spoken aloud to handicapped (e.g. visually impaired) individuals who are running Mac OS X under accessibility mode. Naturally, while the page is loading the button is described as "stop."
If some interactive aspect of the iTunes GUI changes (most likely a button) when a download completes, you can detect its change of state in a similar fashion and use that as a cue to continue the script.
Hope that helps. (My example implementation of the code. I have found it to be ridiculously precise—the script continues instantaneously after the page finishes loading.)
Disclosure: Not my original code—I found it somewhere on the internet.


text:
Q: DynamoDB Global Secondary Index Timeout Using Terraform I'm experiencing a timeout in index creation using the following configuration on Terraform v0.13.6 and using AWS provider version 3.42.0:
resource "aws_dynamodb_table" "TestDB" {
  name             = "TestDB"
  billing_mode     = "PAY_PER_REQUEST"
  hash_key         = "..."
  range_key        = "..."

  attributes {...}
  global_secondary_index {...}
  timeouts {
    create = "2h"
    delete = "2h"
    update = "2h"
  }

I get the following error when working with a large amount of items in the table:
Error: error waiting for DynamoDB Table (TestDB) Global Secondary Index (TestIndex) creation: timeout while waiting for state to become 'ACTIVE' (last state: 'CREATING', timeout: 20m0s)

The most relevant issue I could find was: https://github.com/hashicorp/terraform-provider-aws/issues/5471, which seems to resolve timeout issues when indices need to be updated by using the timeout specified in the aws_dynamodb_table.timeouts block . This is described in the documentation.
In my case, I believe I need the timeout for creating an index needs to be longer. And for reference, terraform is being run on CircleCI. I believe the 20 min timeout comes from terraform defaults: https://www.terraform.io/plugin/sdkv2/resources/retries-and-customizable-timeouts.
Is there a way to extend the timeout on GSI creation using terraform?


text:
Q: MongoDB should I create my own ID key column? In MongoDB there seems to be a default _id column, but it stores the object ID. Should I be making my own auto-incrementing id column to reference across collections as foreign keys?

A: The default _id column is the primary key of the document. And it stores an ObjectId, but it can contain something else, it's up to you.
There is a reason why mongo developers use that as a default primary key (it's more performant if multiple processes insert simultaneously) and if you don't understand the reasons you better not experiment with something else.
It is a perfectly good foreign key.


text:
Q: How does Eclipse pull metadata from Standard Objects I want to do what Eclipse is doing: pull metadata for Standard objects. I basically need to inspect what Views, WebLinks, and Validation Rules Opportunity has in my org. For Custom objects I do the following:
SFDCMetadata.RetrieveRequest rr = new SFDCMetadata.RetrieveRequest();
        SFDCMetadata.Package package = new SFDCMetadata.Package();
        SFDCMetadata.PackageTypeMembers ptm = new SFDCMetadata.PackageTypeMembers();
        ptm.name = "CustomObject";
        ptm.members = new string[] { "*" };
        package.types = new SFDCMetadata.PackageTypeMembers[] { ptm };

        rr.singlePackage = true;
        rr.unpackaged = package;
        SFDCMetadata.AsyncResult res = port.retrieve(sh, null, rr);
        Thread.Sleep(1500);
        SFDCMetadata.RetrieveResult retRes = port.checkRetrieveStatus(sh, null, res.id);
        while (!retRes.done)
        {
            Thread.Sleep(1000);
            retRes = port.checkRetrieveStatus(sh, null, res.id);
        }
        List<FileInfo> fis = DecompressToFiles(retRes.zipFile, folderName);

But I get back only a collection of custom objects. How do I retrieve the standard objects, like Eclipse does:

How do they do it?

A: You have to specify the <Member>such as Account for each custom object when requesting the CustomObject.
See this post:
http://luigimontanez.com/2008/custom-fields-on-standard-objects-in-the-force-com-ide/
Hope that helps.

A: You retrieve it just like a custom object - using the name CustomObject
You need to add some additional member to the PackageTypeMembers
ptm.members = new string[] { "*", "StandardObjectName" };
so for instance setting
ptm.members = new string[] { "*", "Account" };
should return the account meta data
I found this reference that provided the information
http://blog.nathanwisman.com/2012/01/master-list-of-metadata-api-xml.html


text:
Q: C:\Users\Admin>pipenv --python 3.9 "pipenv" не является внутренней или внешней командой, исполняемой программой или пакетным файлом C:\Users\Admin>pip install pipenv
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pipenv in c:\users\admin\appdata\roaming\python\python39\site-packages (2021.5.29)
Requirement already satisfied: virtualenv-clone>=0.2.5 in c:\users\admin\appdata\roaming\python\python39\site-packages (from pipenv) (0.5.6)
Requirement already satisfied: setuptools>=36.2.1 in c:\program files\python39\lib\site-packages (from pipenv) (56.0.0)
Requirement already satisfied: pip>=18.0 in c:\users\admin\appdata\roaming\python\python39\site-packages (from pipenv) (21.2.2)
Requirement already satisfied: certifi in c:\users\admin\appdata\roaming\python\python39\site-packages (from pipenv) (2021.5.30)
Requirement already satisfied: virtualenv in c:\users\admin\appdata\roaming\python\python39\site-packages (from pipenv) (20.7.0)
Requirement already satisfied: backports.entry-points-selectable>=1.0.4 in c:\users\admin\appdata\roaming\python\python39\site-packages (from virtualenv->pipenv) (1.1.0)
Requirement already satisfied: platformdirs<3,>=2 in c:\users\admin\appdata\roaming\python\python39\site-packages (from virtualenv->pipenv) (2.2.0)
Requirement already satisfied: filelock<4,>=3.0.0 in c:\users\admin\appdata\roaming\python\python39\site-packages (from virtualenv->pipenv) (3.0.12)
Requirement already satisfied: six<2,>=1.9.0 in c:\users\admin\appdata\roaming\python\python39\site-packages (from virtualenv->pipenv) (1.16.0)
Requirement already satisfied: distlib<1,>=0.3.1 in c:\users\admin\appdata\roaming\python\python39\site-packages (from virtualenv->pipenv) (0.3.2)
здраствуйте помогите пожалуйста  как установить пакет управления виртуальным окружениям пайтон
и как создать среду
а то вилазит код:
C:\Users\Admin>pipenv --python 3.9
"pipenv" не является внутренней или внешней
командой, исполняемой программой или пакетным файлом.

A: Для начала установим pipenv с помощью pip
pip install pipenv

После установки создаю папку для вирт.среды примеру 'text' и захожу в неё,после этих действий я указываю версию интерпретатора:
pipenv --python 3.9

Команда автоматически создаст виртуальное окружение и после можно активировать виртуальное окружение:
pipenv shell


text:
Q: Database stored on a shared drive I have to make a database for 250 students which will have around 100-200 columns. Now its not possible to install MYSQL or anything like that on the server.All we can get is a shared folder on the server. The client side can have anything installed. There will be around 5-10 clients who will add,edit or delete the records. I though about SQLite as an option. Is there any security issues with it???
I need a database to be accessed by a 5 to 10 clients. We do not have a full server per se but rather a shared folder on a server. We therefore cannot install any server-side software, only client-side.

A: I would use SQLite. You could also use MS Access but consider that problems with old MS Access databases are common in companies where Access where used on the late nineties.

A: Have a look at the following questions here

*

*https://superuser.com/questions/111798/small-database-recommendation-free

*Free database for small datawarehouse
You will find enough information to get you started.
Else look at these

*

*SQLite

*HSQLDB


text:
Q: What does this mean grammatically? There was no one who would not talk ill of him.
What does this "would" mean grammatically?

A: It probably means the writer isn't a native speaker of English. The "double negative" phrasing is clumsy, but might be excused if it weren't for the "misuse" of the verb to talk. Usage figures from Google Books...

"talk ill of him" - 2890 results
"speak ill of him" - 103,000 results

In fact it's much worse than even those figures would suggest - the vast majority of those 2890 results are from non-native speakers, deliberately archaic-sounding texts, or were written over a century ago.
As to the semantic content, if we "cancel out" the negatives no-one and not speak ill, we end up with...

"Everyone spoke badly of him" (i.e. - everyone would say bad things about him)

It can either mean that's what they would say (if asked their opinion), or that's what they habitually said (not necessarily only when asked). There's no way to say for sure, but it makes no real difference here. See this previous answer for more on would do = habitually did.

A: "Would" here means "was willing to" or "was likely to."
So, rephrased, your sentence is equivalent to either/both of the following:

There was no one who was not willing to talk ill of him.
There was no one who was not likely to talk ill of him.

For clarification, let me add a name:

There was no one who was not likely to talk ill of John.

Therefore, if you ask anybody what he or she thinks about John, you will receive a bad opinion about John.


text:
Q: Black screen after sudo systemctl stop gdm I had a problem with my NoMachine Programm so I decided to use the possible solutions from their website: https://knowledgebase.nomachine.com/AR03P00973
I tried the commands in the graphical desktop environment:
sudo systemctl stop lightdm and sudo systemctl stop display-manager and both put me in a blackscreen where I couldn't do anything except rebooting my PC. After I rebooted my PC there was no blackscreen anymore. Then I tried the command: sudo systemctl stop gdm and after this command I'm still in the blackscreen even after rebooting. And I also cant see my cursor. I can't even get to the Bios because the screen is just black. Maybe switching between the TTY screen is working but I cant tell since I cant see what is happening. I dont know what to do. I now know that I shouldn't have used these commands in the normal graphical desktop environment.
I'm using the Version 20.04.3

I'm afraid none of these solutions helped. I turned my PC on tried all the TTY screens but all of them gave me a black screen. I even tried to log in, open the console, and type in the command for restarting the display-manager but no matter what I did there was still no video signal. I'm using the version: 20.04.3

A: Whenever you stop your display manager, you need to do so through a TTY console so that you don't lose your session. You will need to go to a TTY screen and log in with your username and password so you can run commands.
Press CTRL+ALT+F4 to open a TTY screen (TTY4).
Then, sign in with your username and password.
Now, you can run the commands listed in the help article.
sudo systemctl stop display-manager
sudo /etc/NX/nxserver --restart

I'm not sure which screen this will start the GUI. The GUI usually runs on TTY1 or TTY2 but sometimes runs on TTY7.
Use CTRL+ALT+F1 to get to TTY1, CTRL+ALT+F2 to get to TTY2, or CTRL+ALT+F7 to get to TTY7. Try all three of these to see if you can find a working session.
Alternatively, to get back to a normal GUI desktop, you can always startup your display manager using the following command:
sudo systemctl restart display-manager

and your default Ubuntu desktop or login screen should be on TTY1 or TTY2 or possibly TTY7.

A: I finally found out what the problem was. The problem was something in the BIOS so I had to reset my BIOS manually and everything worked again. Nonetheless I want to thank everyone who tried to help me.


text:
Q: Gitlab: The goal you specified requires a project to execute but there is no POM in this directory I try gitlab CI for building and running my tests.
I use the Default .gitlab-ci.yml:
# This file is a template, and might need editing before it works on your project.
---
# Build JAVA applications using Apache Maven (http://maven.apache.org)
# For docker image tags see https://hub.docker.com/_/maven/
#
# For general lifecycle information see https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
#
# This template will build and test your projects as well as create the documentation.
#
# * Caches downloaded dependencies and plugins between invocation.
# * Verify but don't deploy merge requests.
# * Deploy built artifacts from master branch only.
# * Shows how to use multiple jobs in test stage for verifying functionality
#   with multiple JDKs.
# * Uses site:stage to collect the documentation for multi-module projects.
# * Publishes the documentation for `master` branch.

variables:
  # This will supress any download for dependencies and plugins or upload messages which would clutter the console log.
  # `showDateTime` will show the passed time in milliseconds. You need to specify `--batch-mode` to make this work.
  MAVEN_OPTS: "-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  # As of Maven 3.3.0 instead of this you may define these options in `.mvn/maven.config` so the same config is used
  # when running from the command line.
  # `installAtEnd` and `deployAtEnd` are only effective with recent version of the corresponding plugins.
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"

# Cache downloaded dependencies and plugins between builds.
# To keep cache across branches add 'key: "$CI_JOB_NAME"'
cache:
  paths:
    - .m2/repository

# This will only validate and compile stuff and run e.g. maven-enforcer-plugin.
# Because some enforcer rules might check dependency convergence and class duplications
# we use `test-compile` here instead of `validate`, so the correct classpath is picked up.
.validate: &validate
  stage: build
  script:
    - 'mvn $MAVEN_CLI_OPTS test-compile'

# For merge requests do not `deploy` but only run `verify`.
# See https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
.verify: &verify
  stage: test
  script:
    - 'mvn $MAVEN_CLI_OPTS verify site site:stage'
  except:
    - master

# Validate merge requests using JDK7
validate:jdk7:
  <<: *validate
  image: maven:3.3.9-jdk-7

# Validate merge requests using JDK8
validate:jdk8:
  <<: *validate
  image: maven:3.3.9-jdk-8

# Verify merge requests using JDK7
verify:jdk7:
  <<: *verify
  image: maven:3.3.9-jdk-7

# Verify merge requests using JDK8
verify:jdk8:
  <<: *verify
  image: maven:3.3.9-jdk-8

# For `master` branch run `mvn deploy` automatically.
# Here you need to decide whether you want to use JDK7 or 8.
# To get this working you need to define a volume while configuring your gitlab-ci-multi-runner.
# Mount your `settings.xml` as `/root/.m2/settings.xml` which holds your secrets.
# See https://maven.apache.org/settings.html
deploy:jdk8:
  # Use stage test here, so the pages job may later pickup the created site.
  stage: test
  script:
    - 'mvn $MAVEN_CLI_OPTS deploy site site:stage'
  only:
    - master
  # Archive up the built documentation site.
  artifacts:
    paths:
    - target/staging
  image: maven:3.3.9-jdk-8

pages:
  image: busybox:latest
  stage: deploy
  script:
    # Because Maven appends the artifactId automatically to the staging path if you did define a parent pom,
    # you might need to use `mv target/staging/YOUR_ARTIFACT_ID public` instead.
    - mv target/staging public
  dependencies:
    - deploy:jdk8
  artifacts:
    paths:
    - public
  only:
    - master

When i run the Pipeline it fails and i get the following error:
2288 [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/builds/IceCristall/the-great-triggering). Please verify you invoked Maven from the correct directory. -> [Help 1]
org.apache.maven.lifecycle.MissingProjectException: The goal you specified requires a project to execute but there is no POM in this directory (/builds/IceCristall/the-great-triggering). Please verify you invoked Maven from the correct directory.
Here is the Complete log:
Running with gitlab-runner 11.2.0-rc2 (1644837a)
  on docker-auto-scale ed2dce3a
Using Docker executor with image maven:3.3.9-jdk-8 ...
Pulling docker image maven:3.3.9-jdk-8 ...
Using docker image sha256:9997d8483b2fc521a4159feab922546dda0c5c22b5084f86dfab48f123ae4364 for maven:3.3.9-jdk-8 ...
Running on runner-ed2dce3a-project-7913048-concurrent-0 via runner-ed2dce3a-srm-1534626556-3eb27695...
Cloning repository...
Cloning into '/builds/IceCristall/the-great-triggering'...
Checking out e41a61bd as master...
Skipping Git submodules setup
Checking cache for default...
FATAL: file does not exist
Failed to extract cache
$ mvn $MAVEN_CLI_OPTS test-compile
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
Maven home: /usr/share/maven
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.14.48-coreos-r2", arch: "amd64", family: "unix"
2053 [INFO] Error stacktraces are turned on.
2152 [INFO] Scanning for projects...
2252 [INFO] ------------------------------------------------------------------------
2253 [INFO] BUILD FAILURE
2253 [INFO] ------------------------------------------------------------------------
2254 [INFO] Total time: 0.133 s
2254 [INFO] Finished at: 2018-08-18T21:12:14+00:00
2286 [INFO] Final Memory: 6M/56M
2287 [INFO] ------------------------------------------------------------------------
2288 [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/builds/IceCristall/the-great-triggering). Please verify you invoked Maven from the correct directory. -> [Help 1]
org.apache.maven.lifecycle.MissingProjectException: The goal you specified requires a project to execute but there is no POM in this directory (/builds/IceCristall/the-great-triggering). Please verify you invoked Maven from the correct directory.
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:84)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
2299 [ERROR]
2299 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
2299 [ERROR]
2299 [ERROR] For more information about the errors and possible solutions, please read the following articles:
2300 [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MissingProjectException
ERROR: Job failed: exit code 1

When i understand this log correct the project is Copy from my repository in the Docker container under the path:/builds/IceCristall/the-great-triggering
now the mvn command is executed and didnt find the pom.xml
Im a bit confused because the pom.xml is in the "the-great-triggering" folder.
Also i cant find where i can define this path in my ci config File.
Anyone have sugestions on what the problem ist and where i can search for it?

A: The error message says: "there is no POM in this directory (/builds/IceCristall/the-great-triggering). ".
Are you sure that you have your pom.xml file committed and push to the required branch of your repo?


text:
Q: Java - Handling Listeners I'm relatively new to graphical user interfaces and I've created an interface that implements the functionality of a basic calculator. These methods include: add(), subtract(), multiply(), and divide(). I'm getting an error within my actionPerformed method that's saying "the method add(int, int) in the type Operate is not applicable for the arguments (int)." I've tried including the variables I've passed into my public class Operate and I still receive this error. How can I resolve this?
Here's my code for this method:
JButton btnNewButton_10 = new JButton("+");
btnNewButton_10.setFont(new Font("Helvetica Neue", Font.PLAIN, 15));
btnNewButton_10.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        int myFunction = calculate.add(Integer.parseInt(textDisplay.getText())); // The error is specifically underlining the keyword "add"
        textDisplay.setText("");

A: You're attempting to add 1 int, apparently your add function wants to add two ints together.

A: Ìt seems your add method takes 2 int arguments but you have only passed in one.
You need something like this instead:
int myFunction = calculate.add(Integer.parseInt(textDisplay.getText()), myOtherIntNumber);


text:
Q: How to draw lines across datapoints of an existing D3 Chart I am working on a D3 Chart that looks like this:

Fair warning: I am very new to D3. What I need to do now is to connect all datapoints across the z-axis with a line. So for all ages I want a line that starts at z = 0 and finishes at z = 4, that passes through all spheres, where z represents Capital Type. The end goal is to have a chart that resembles a surface area plot. I have looked at how to draw lines on D3 but I keep getting very generic things:
//Make an SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);

//Draw the line
var circle = svgContainer.append("line")
.attr("x1", 5)
.attr("y1", 5)
.attr("x2", 50)
.attr("y2", 50);

What I need is a way to loop through all my datapoints and draw lines between them. This is how I declare my datapoints variables (var datapoints represents the vertical lines alone and var newDataPoints represents the blue spheres on top of each one:
var datapoints = scene.selectAll(".datapoint").data( rows );
datapoints.exit().remove()

var newDatapoints = datapoints.enter()
.append("transform")
.attr("class", "datapoint")
.attr("scale", [sphereRadius, sphereRadius, sphereRadius])
.append("shape");
newDatapoints
.append("appearance")
.append("material");
newDatapoints
.append("sphere")`

Thanks in advance for any help!


text:
Q: Toggling multiple DIVs with jQuery I have three info panels (divs with IDs of panel-one, panel-two and panel-three, all with the class info-panel) which I want to have slide in and out on the click of a link (these have the IDs toggle-one, toggle-two and toggle-three, all with the class toggle). If one of the divs is showing when one of the other links is clicked, I want to hide the visible div and show the new one. If the div's own link is clicked, I want to toggle the show/hide. I'm using the following code to do this:
HTML:

One

Two

Three

jQuery:
$("#toggle-one").click(function () {
    if($("#panel-two").is(":visible")) {
        $("#panel-two").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    } else if($("#panel-three").css("z-index", "9997").is(":visible")) {
        $("#panel-three").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    }
    $("#panel-one").css("z-index", "9998").toggle("slide", {direction: 'up'}, 750);
    return false;
});

$("#toggle-two").click(function () {
    if($("#panel-one").is(":visible")) {
        $("#panel-one").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    } else if($("#panel-three").is(":visible")) {
        $("#formlink").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    }
    $("#panel-two").css("z-index", "9998").toggle("slide", {direction: 'up'}, 750);
    return false;
});

$("#toggle-three").click(function () {
    if($("#panel-one").is(":visible")) {
        $("#panel-one").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    }  else if($("#panel-two").is(":visible")) {
        $("#panel-two").css("z-index", "9997").hide("slide", {direction: 'up'}, 750);
    }
    $("#panel-three").css("z-index", "9998").toggle("slide", {direction: 'up'}, 750);
    return false;
});

It works, but it's very verbose and won't scale well - managing three divs of info is fine, but if/when the time comes to add more, it's going to turn into a major pain to maintain. I've tried using an approach like the one outlined in Show/Hide Multiple Divs with Jquery, but can't seem to get it to work properly - the toggle and hide behaviours don't work well (hidden dive show when they shouldn't then immediately hide and things like that). Likewise, I can't seem to get the example shown in Jquery toggle on 3 divs to work, either.
I'm sure there's a much cleaner way to do this, but as I'm a bit of a jQuery and javascript n00b, I don't really know how to go about tidying it up. What's the best way to tackle this?

A: Wrap your panels in a
 with an id of panels:

and this should work:
$(".toggle").on('click', function() {
    var $panel = $('#panels').children().eq($(this).parent().index());

    $panel.toggle("slide", {direction: 'up'}, 750);
    $panel.siblings().hide("slide", {direction: 'up'}, 750);

    return false;
});

A: Taking a steer from what Blender posted, I ended up going with this:
HTML:

One

Two

Three

jQuery:
$(".toggle").click(function() {
    var $toggled = $(this).attr('href');

    $($toggled).siblings(':visible').hide("slide", {direction: 'up'}, 750);
    $($toggled).toggle("slide", {direction: 'up'}, 750);

    return false;
});

Happy with that... 27 lines of javascript down to 6, and it all seems to work! But again, many thanks are due to Blender, since I never would have got to this point otherwise.

A: thats how I'd do it :
$("info-panel").click(function(){

    //put your div in memory
    var chosen = $(this);

    //Slide down all the toggle div or hide them
    $('.info-panel').slideUp('slow', function(){);

    //open the div you wanted
    chosen.slideToggle('slow',function(){});
}

then, to activate it :
function openDiv(divId){
$("#"+divId).click();
}

on the html, after the a href="#" ... set the onclick attribute
a href="#" onclick="openDiv('panel-one')"


text:
Q: What is this component in series with my water heater's thermocouple? The other day we had our water heater go out and the issue was diagnosed to a faulty thermocouple.  When the repair man removed the faulty thermocouple he noticed the following disk-like component in series about mid-way down the copper tubing.
This device had one of its two terminals broken off of the bottom (not shown) and was most certainly the cause for the failure.  The repair man's replacement thermocouple had no such device inline and when asked what this was he replied it was a transistor.  I very much doubt this device is a transistor as there are only two, not three, terminals but I didn't want to argue.
So, what exactly is this component and what is it's function?  As stated, the replacement thermocouple does not have this but it appears to be functioning correctly.

A: An easier way than soldering the two ends of thermocouple is to just replace with a new universal TC (~$12 HomeDepot). A fusible link soldered in series with the TC presents a weak mechanical link
.
The torque from attaching the threaded end to the burner valve control can easily tear the solder bond and create an open or even worse, an intermittent TC connection (that's what happened in my case). Either case results in a pilot light that does not stay lit, which means no main gas flow to burner.

A: If I was a betting man, I'd suggest that it's a low-melting-point alloy such as Wood's Alloy designed to melt and open the circuit from the thermopile (thus closing the gas valve) in case of a house fire or fire under the water heater, but I have no evidence to support that premise!
Possibly 180°C is the melting point.
Edit: Okay, evidence gathered. See Amazon review here,

The funny thing is AO Smith replacement thermo-couples don't even come with the thermal fuse!!! But you don't really need the thermal link, and this generic thermo-couple will work just fine for your water heater (as long as it's the correct length). So measure the length of your bad one and make sure. Because the longer they are, the higher the resistance, and your gas control valve is designed for the correct length.
Finally, if you feel you just gotta have the thermal fuse (cause
  your'e afraid you just can't keep the area clean under your water
  heater...and dust or debris collecting under your water heater, may
  start an un-controlled fire), then for about $20 more, you can get the
  complete kit which includes the thermo-couple (with thermal-fuse
  link), the pilot tube, and a piezo-electric ignitor.

and this Amazon photo (which is the item referenced in the review).

You might want to discuss this with your repair service company- it appears they may have compromised the overall safety by replacing the original safety device with an inferior generic replacement. It also sounds like the guy they sent out was a dolt- "transistor"!

A: This Fusible link you are referring to is a high limit link. If your water heater gets to hot. This high limit will burn thru. You have to understand that at the gas valve where the thermocouple screws in. There is a valve high limit. If your thermocouple gets to hot, the valves high limit will shut down the flow of gas.
  There is NO such thing as a "fire fusable link" to be used incase of a fire under your water heater. I replace this style of thermocouple all the time with the standard style thermocouple.  I've never had a problem with the heater.
 Petaluma California  Plumber for over 40 years...

A: I fixed my fusible link on my Maytag(Whirlpool) water heater. After inspecting the
old link, which fell off when I touched it, I found it had rusted thus breaking the connection. I tried to get a new link or get advise on what to do but I had to figure this one out for myself.
Since most thermocouples do not come with a fusible link I took the two ends of wire left on the thermocouple wire and soldered them together. It worked perfectly.  The fusible link only tripped in the event of a house fire or blockage. I SOLDERED it so if a fire did break out it would melt thus shutting off the gas anyway. I keep my basement and water heater clean and free of debris so hopefully no fire there. I am not recommending this as a perfect fix  I found it hard to spend $90 plus to replace only a hearing aid battery size part and I believe I am as safe as I ever was.
Thanks
  Lennie


text:
Q: Angular2 pipe dynamic value not taking I have a json like this
[{
  "id": 9156,
  "slug": "chicken-seekh-wrap",
  "type": "dish",
  "title": "Chicken Seekh Wrap",
  "cuisine_type": [2140]
},
{
  "id": 9150,
  "slug": "green-salad",
  "type": "dish",
  "title": "Green Salad",
  "cuisine_type": [2141]
}]

I created a pipe like this to filter by cuisine type in angular2
@Pipe({
      name: 'filter',
      pure: false
 })
 export class FilterPipe implements PipeTransform {
     transform(items: any[], selectedId: any): any {
     if(selectedId === -1)
           return items;
    return items.filter(item => item.cuisine_type[0] === selectedId);

  }
 }

And in the ionic view  I have used it like this
<ion-card *ngFor="let cat of selectedCats">
            <ion-card-header>
              {{cat}}
            </ion-card-header>
            <ion-card-content>
                <ion-list class="checkbox-list" *ngIf="dishes ?.length > 0">
                  <ion-item class="checkbox-item" *ngFor="let dish of dishes | filter:cat">

                    <ion-label>{{dish.title}}</ion-label>
                      <ion-checkbox [formControlName]="dish.id"></ion-checkbox>

                  </ion-item>
                </ion-list>
            </ion-card-content>
</ion-card>

When I am using pipe value as static like its working
 <ion-item class="checkbox-item" *ngFor="let dish of dishes | filter:2140">

but when I am using it dynamically its not showing any result
<ion-item class="checkbox-item" *ngFor="let dish of dishes | filter:cat">

A: The problem is not caused by Angular, but by your code
item.cuisine_type[0] === selectedId

being overly specific about accepted values
item.cuisine_type[0] == selectedId

is more forgiving by allowing type coercion before the comparison.
This means, that cat is probably a string '2140' and item.cuisine_type[0] a number.
If you pass it as | filter:2140" it's passed as number and matches item.cuisine_type[0].


text:
Q: Required keys for multiple objects I've enum for my i18n object like:
export enum I18NKeys {
  EN = 'en',
  CS = 'cs',
  DE = 'de'
}

And I would like to have an object that has keys of I18NKeys and there will be custom keys inside that object like
export const content = {
  en: {

  },
  cs: {

  },
  de: {

  }
}

I'm trying to create a generic typescript that once I've keyed in one of the I18NKeys object. So I would like to be sure that others have the same key.
export const content = {
  en: {
   title: "Hello"
  },
  cs: {

  },
  de: {

  }
}

So this will throw me an error till I've put title on all other keys.

A: You can try
export const content: Record<I18NKeys, {title: string}> = {
...
}

And of course, you can change {title: string} to any types you want or even generics to suit your need.

A: Looks like this, you can use the ? to describe the optional field.
export enum I18NKeys {
    EN = "en",
    CS = "cs",
    DE = "de"
}

interface I18NContent {
    title?: string;
}

const content: Record<I18NKeys, I18NContent> = {
    en: {
        title: "foo"
    },
    cs: {},
    de: {}
}

playground


text:
Q: Export data to csv format file in mac app I'm new to mac app development.
I have set of data in the nstableview and i need to save this data in .cs format progarmmatically.
-(IBAction)exportInvoice:(id)sender
{
    AppDelegate *appDelegate = [NSApp delegate];
     NSString *tempStr = [NSString stringWithFormat:@"%@", [OrderModel getInitialOrderBITToDisplay:[appDelegate getDBPath]]];
    NSArray* commaSeparatedObjects = [tempStr componentsSeparatedByString:@","];
    //NSString *commaSeparatedObjects = [tempStr componentsJoinedByString:@","];
    NSLog(@"%@",commaSeparatedObjects);

    NSSavePanel *pdfSavingDialog = [NSSavePanel savePanel];

    [pdfSavingDialog setRequiredFileType:@"csv"];

    if ( [pdfSavingDialog runModalForDirectory:nil file:nil] == NSOKButton ) {
       // NSData *dataForPDF = [self exportPdfData];
        NSData *dataForPDF = [NSKeyedArchiver archivedDataWithRootObject:commaSeparatedObjects];
        NSLog(@"%@",dataForPDF);
        [dataForPDF writeToFile:[pdfSavingDialog filename] atomically:NO];

    }
}

Can anyone help me to sort the problem?

A: You should check out CHCSVParser: https://github.com/davedelong/CHCSVParser
Hope that helps.


text:
Q: MySQL slow query log: huge query time, no lock time, minuscule number of rows scanned I have a slow query log item with the following:
Query_time: 55  Lock_time: 0  Rows_sent: 739  Rows_examined: 739

No one in my group can explain it besides a guess about packet loss. Is there a common cause or set of causes for result like the above?

A: I'm going out on a limb here, but did you do an 'EXPLAIN' on this query?
If not, run "EXPLAIN" to see what the execution plan is. This will give you hints on optimization or indexing.
E.g. SOMETHING LIKE
EXPLAIN SELECT a.field1,b.field1 FROM tableA a LEFT JOIN tableB b ON b.a_id = a.id;

The result will be a nicely formatted report.
You may find there's unnecessary complexity in the query that can be pushed to the application or just factored out.

A: Do you have the query cache enabled? I found this (closed) bug and one reason given for the long behavior was an improperly configured query cache.
http://dev.mysql.com/doc/refman/5.0/en/query-cache-status-and-maintenance.html

A: I think it's network latency. I would see queries in my slow-log that I ran directly on the server and they would return immediately. After scratching my head for a while, I tried logging in remotely to the server and running a query that would return data. The query then took much longer to return. If you turn on profiling, you can see that the greatest amount of time was spent in 'sending data'.

A: my idea is to diagnose the entire database with some deeper-monitoring tool - I'm using nms express (free). http://bit.ly/nwwdKS

A: I'd say this really depends on the query itself, while you're only scanning 739 rows in your table and returning all 739, it depends on a few things. One how much RAM mysql had to work with for that thread/query. Also it depends on the query itself. Imagine a query with 20 inner joins and another 20 where clauses your result set would be limited but the amount of work to pair down those result sets would definitely be significant even if the result set is relatively small.


text:
Q: PayPay Pay later messaging showing only for 6 Month not for 4 month on live production I have added the paypal pay in 4 messaging on my website but only showing 6 month pay messaging.
and using sandbox sdk its showing proper pay in 4 message with installment amount.
Six month payment message
But need to show like below pay in 4 with installment amount.
four month payment message with installment amount
Need four month message with installment amount for live as well like sandbox.
Please suggests.
Many thanks.

A: Pay in 4 is not a "four month payment message", it is one payment every 2 weeks (across 2 months).  Those are two different offer types, and US customers may have both to choose from during their checkout.
If your messaging integration is the same, contact PayPal to ask why the Pay in 4 offer isn't shown for the production account.


text:
Q: how to delete a row from the table with a button on react? I wanted to remove a row from the table with the function 'deleteRow(btn)' when pressing the button, but I get this error 'Cannot read properties of undefined (reading 'parentNode')'. What could I add or correct to successively drop a row from a table?
App.js
class App extends React.Component{

  constructor(props) {
    super(props);

    this.state = {

      fotos: [],
      restaurantes:[],

    }

  }

   deleteRow=(btn)=> {
         var row = btn.parentNode.parentNode;
         row.parentNode.removeChild(row);
   }

   render(){

      const { fotos, restaurantes } = this.state;

         <Tabela dadosFotos={fotos} restaurante={this.deleteRow} />

   }

Tabela.js
import React from "react";

const CorpoTabela = (props) => {

const rows = props.dadosDasFotos.map((row) => {
    return(

        {row.nomeRestaurante}

             <button className="btn btn-outline-danger"
                 onClick={()=>props.restauranteAremover(row.idFoto)}>
                 Delete restaurante
             </button>

    )
})

return(
{rows}
)
}

class Tabela extends React.Component{

    render(){

        const { dadosFotos, restaurante }=this.props

        return(

                <CorpoTabela dadosDasFotos={dadosFotos} restauranteAremover={restaurante}/>

        )
    }
}

A: You should not be manipulating the DOM as this is an anti-pattern in React, instead you should update the state you are rendering from.
Delete by idFoto.
deleteRow = (idFoto)=> {
  this.setState(prevState => ({
    fotos: prevState.fotos.filter(el => el.idFoto !== idFoto
  }))
}

In the child pass the id to the delete handler.
<button className="btn btn-outline-danger"
  onClick={() => props.restauranteAremover(row.idFoto)}>
  Delete restaurante
</button>

A: In React, you generally want to try avoiding direct DOM manipulation, since this takes state management out of React, which is something you want to avoid.
Therefore, instead of trying to delete each row directly using DOM functions like remove or removeChild, it would be best to keep all of the table rows in a key in the state object.  Then, you can filter out the deleted row by filtering it out by index or through some other identifier.  Here's an example:
import { Component } from 'react'
import './styles.css'

export default class App extends Component {
  state = {
    rows: [
      { id: 1, col1: 'A', col2: 'some text' },
      { id: 2, col1: 'B', col2: 'some text' }
    ]
  }

  spliceRow = (index) => {
    this.state.rows.splice(index, 1)
    this.setState({ rows: this.state.rows })
  }

  filterRows = (id) => {
    this.setState({
      rows: this.state.rows.filter((row) => {
        return row.id !== id
      })
    })
  }

  render() {
    return (

          {this.state.rows.map((row, index) => {
            return (

                {row.col1}
                {row.col2}

                  <button onClick={() => this.spliceRow(index)}>
                    Remove row with splice
                  </button>

                  <button onClick={() => this.filterRows(row.id)}>
                    Remove row with filter
                  </button>

            )
          })}

    )
  }
}


text:
Q: How to make all my site scripts safe for browsers? Okay, so i have this problem, i tried searching it on google, had no luck.
When a browser loads my site, it says that there are unsafe scripts there, but all the scripts are working properly except google fonts. To make them work i have to click "load all scripts anyways". Is it possible to make that browsers wouldn't recognise my scripts and google fonts as unsafe? i'm hosting my site on a dropbox.


text:
Q: Convert this to Eloquent from Query Builder, joining and multiple whereor I am trying to use a search page for the record. The below is my Query Builder, I think I have a problem for the performance for query this. I am thinking to switch it to Eloquent and able to use the toArray() function to convert it.
$records = DB::table('customers')
    ->join('orders', function($join) use ($keyword)
    {
        $join->on('customers.id', '=', 'orders.cust_id')
            //customers
            ->where('name', 'LIKE', '%'.$keyword.'%')
            ->orWhere('address_street', 'LIKE', '%'.$keyword.'%')
            ->orWhere('address_street2', 'LIKE', '%'.$keyword.'%')
            ->orWhere('address_city', 'LIKE', '%'.$keyword.'%')
            ->orWhere('address_postcode', 'LIKE', '%'.$keyword.'%')
            ->orWhere('contact_mobile', 'LIKE', '%'.$keyword.'%')
            ->orWhere('contact_email', 'LIKE', '%'.$keyword.'%')
            ->orWhere('remark', 'LIKE', '%'.$keyword.'%')
            //orders
            ->orWhere('order_no', 'LIKE', '%'.$keyword.'%')
            ->orWhere('delivery_man', 'LIKE', '%'.$keyword.'%')
    })
    ->take(10)
    ->get();

I also notice the query is taking long time compare I wrote the sql statement from the query client. The result from this query was taken 4s, the sql query only took 0.3s. Below is the sql statement.
SELECT * FROM `customers`
INNER JOIN `orders` on `customers`.`id` = `orders`.`cust_id`
WHERE `name` LIKE '%keyword%' or `address_street` LIKE '%keyword%'
    or `address_street2` LIKE '%keyword%' or `address_city` LIKE '%keyword%'
    or `address_postcode` LIKE '%keyword%' or `contact_mobile` LIKE '%keyword%'
    or `contact_office` LIKE '%keyword%' or `contact_email` LIKE '%keyword%'
    or `remark` LIKE '%keyword%' or `order_no` LIKE '%keyword%'
    or `delivery_man` LIKE '%keyword%'
LIMIT 10


text:
Q: Add JMeter plugin programmatically - non gui mode I am trying to use jmeter-plugins.
Does it have to be placed only under /lib/ext folder?
Is there any way for me to refer to the plugin jar using some properties?
(like user.classpath property to refer to my custom lib)

A: If you don't want to put JMeter plugin jars in the lib/ext directory, then define the property search_paths in jmeter.properties.

A: After placing the plugin manager jar in the /lib/ext/ you need to do the following to install a particular plugin.
Download the latest cmdrunner from this URL by changing the version.
wget http://search.maven.org/remotecontent?filepath=kg/apc/cmdrunner/2.2/cmdrunner-2.2.jar

Copy the cmdrunner to jmeter/lib/ directory
mv cmdrunner-2.2.jar apache-jmeter-5.1.1/lib/

Execute the following command to generate script file PluginsManagerCMD
java -cp apache-jmeter-5.1.1/lib/ext/jmeter-plugins-manager-1.3.jar org.jmeterplugins.repository.PluginManagerCMDInstaller

After the script is generated, you can use it to install a particular plugin
apache-jmeter-5.1.1/bin/PluginsManagerCMD.sh status
apache-jmeter-5.1.1/bin/PluginsManagerCMD.sh available
apache-jmeter-5.1.1/bin/PluginsManagerCMD.sh install jpgc-tst=2.5

A: *

*Download cmdrunner in lib folder
cd apache-jmeter-5.4/lib
curl -O https://repo1.maven.org/maven2/kg/apc/cmdrunner/2.2.1/cmdrunner-2.2.1.jar

download-cmd

*Download jmeter plugin Manager in lib/ext folder
cd ext/
curl -O https://repo1.maven.org/maven2/kg/apc/jmeter-plugins-manager/1.6/jmeter-plugins-manager-1.6.jar

*Install plugins
cd ..
java  -jar cmdrunner-2.2.1.jar --tool org.jmeterplugins.repository.PluginManagerCMD install jpgc-webdriver


text:
Q: How to work around the Queue corruption when using Process.Terminate() I'm building a Python script/application which launches multiple so-called Fetchers.
They in turn do something and return data into a queue.
I want to make sure the Fetchers don't run for more than 60 seconds (because the entire application runs multiple times in one hour).
Reading the Python docs i noticed they say to be carefull when using Process.Terminate() because it can break the Queue.
My current code:
# Result Queue
resultQueue = Queue();

# Create Fetcher Instance
fetcher = fetcherClass()

# Create Fetcher Process List
fetcherProcesses = []

# Run Fetchers
for config in configList:
    # Create Process to encapsulate Fetcher
    log.debug("Creating Fetcher for Target: %s" % config['object_name'])
    fetcherProcess = Process(target=fetcher.Run, args=(config,resultQueue))

    log.debug("Starting Fetcher for Target: %s" % config['object_name'])
    fetcherProcess.start()
    fetcherProcesses.append((config, fetcherProcess))

# Wait for all Workers to complete
for config, fetcherProcess in fetcherProcesses:
    log.debug("Waiting for Thread to complete (%s)." % str(config['object_name']))
    fetcherProcess.join(DEFAULT_FETCHER_TIMEOUT)
    if fetcherProcess.is_alive():
        log.critical("Fetcher thread for object %s Timed Out! Terminating..." % config['object_name'])
        fetcherProcess.terminate()

# Loop thru results, and save them in RRD
while not resultQueue.empty():
    config, fetcherResult = resultQueue.get()
    result = storage.Save(config, fetcherResult)

I want to make sure my Queue doesn't get corrupted when one of my Fetchers times out.
What is the best way to do this?
Edit: In response to a chat with sebdelsol a few clarifications:
1) I want to start processing data as soon as possible, because otherwise i have to perform a lot of Disk Intensive operations all at once. So sleeping the main thread for X_Timeout is not an option.
2) I need to wait for the Timeout only once, but per process, so if the main thread launches  50 fetchers, and this takes a few seconds to half a minute, i need to compensate.
3) I want to make sure the data that comes from Queue.Get() is put there by a Fetcher that didn't timeout (since it is theoretically possible that a fetcher was putting the data in the Queue, when the timeout occured, and it was shot to death...) That data should be dumped.
It's not a very bad thing when a timeout occurs, it's not a desirable situation, but corrupt data is worse.

A: You could pass a new multiprocessing.Lock() to every fetcher you start.
In the fetcher's process, be sure to wrap the Queue.put() with this lock:
with self.lock:
    self.queue.put(result)

When you need to terminate a fetcher's process, use its lock :
with fetcherLock:
    fetcherProcess.terminate()

This way, your queue won't get corrupted by killing a fetcher during the queue access.
Some fetcher's locks could get corrupted. But, that's not an issue since every new fetcher you launch  has a brand new lock.

A: Why not

*

*create a new queue and start all the fetchers that will use this
queue.

*have your script actually sleep the amount of time you want the fetcher's processes to have for getting a result.

*get everything from the resultQueue - it won't be corrupted, since you didn't have to kill any process.

*finally, terminate all fetcher's processes that are still alive.

*loop !


text:
Q: WinScp: Connection has been unexpectedly closed. server sent command exit status 127 My Server is Ubuntu 14.04.5 LTS and I am able to connect SSH in Putty, but not able to connect via WinSCP.
When I try to connect via WinSCP it gives below error:
Connection has been unexpectedly closed. server sent command exit status 127

A: To access your sftp from other hosts, please make sure following is installed and configured properly.

*

*Installed OpenSSH servers

*Configured sshd_config

*

*PubkeyAuthentication yes

*Subsystem sftp internal-sftp

*Added your public key to ~/.ssh/authorized_keys

*Start the ssh server with port 22/TCP open
# /etc/init.d/sshd start

*# iptables -I INPUT -j ACCEPT -p tcp --dport 22
Finally, test
$ sftp <login>@<hostname>


text:
Q: How can I chain functions when i call it in Swift? I am beginner in swift and I'm doing exercises to learn.
I have to filter any numbers that are even, sort the array, map them to string and print the result one item per line.
The problem is, when I call the function, I´m not able to chain the closures, and it only prints the third function.
import Foundation

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) -> [Int], third: ([Int]) -> [String]) {
    first(luckyNumbers)
    second(luckyNumbers)
    third(luckyNumbers)

    third(luckyNumbers).forEach {
        print($0)
    }
}

doImportantWorkChain { number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
} second: { number in
    return number.sorted {
        return $0 < $1
    }
} third: { number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Output
7 is the lucky number
4 is the lucky number
38 is the lucky number
21 is the lucky number
16 is the lucky number
15 is the lucky number
12 is the lucky number
33 is the lucky number
31 is the lucky number
49 is the lucky number

Output I have to get
4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number

I know that I have to use: luckyNumbers.first { }.second { }
When I try to write like this Xcode give me error: value of type '(([Int]) -> [Int], ([Int]) -> [Int], ([Int]) -> [String]) -> ()' has no member 'first'
So I erase first and give me this errors:
Expected member name following '.'
Top-level statement cannot begin with a closure expression
Value of type '(_) -> _' has no member 'second'
doImportantWorkChain.first{ number in
    return number.filter {
        return $0.isMultiple(of: 2)
    }
}.second{ number in
    return number.sorted {
        return $0 < $1
    }
}.third{ number in
    return number.map {
       ("\($0) is the lucky number")
    }
}

Also I try to chain it when when I call them inside the function but doesn't work either.

A: As the first answer suggested, the issue is that the result of a closure should be used in the next closure.
The fastest way to get the output you are looking for
func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    third(second(first(luckyNumbers))).forEach {
        print($0)
    }
}

However, this is not really chaining functions together and it is doing what the first answer with and just reduces your lines of code but there is no real upgrade in this.
The right way (IMO) to get the output you are looking for
Chaining would be something that I believe one of the commenters suggested is using the filter, sort and map functions directly on luckyNumbers to get your desired output:
luckyNumbers
    .filter { $0.isMultiple(of: 2) }
    .sorted() { return $0 < $1 }
    .map { ("\($0) is the lucky number") }
    .forEach { print($0) }

A way that is chaining, will give you the desired output but I don't know why you would ever use this
If you think about what you need to do, to achieve some sort of chaining, you need to create your own higher order functions like filter, map etc with the same signatures as your closures and then executing the closures.
I did this by creating an extension for Int arrays
extension Array where Element == Int
{
    func apply(_ operation: ([Int]) -> [Int]) -> [Int]
    {
        return operation(self)
    }

    func apply(_ operation: ([Int]) -> [String]) -> [String]
    {
        return operation(self)
    }
}

Then you can achieve chaining and get your desired result
func doImportantWorkChain(first: ([Int]) -> [Int],
                          second: ([Int]) -> [Int],
                          third: ([Int]) -> [String]) {

    luckyNumbers
        .apply(first)
        .apply(second)
        .apply(third)
        .forEach { print($0) }
}

Again, this might be a nice exercise to work your brain and explore the language and its capabilities but I don't think you will ever really use this.
All three of the above ways will give you this output:
4 is the lucky number
12 is the lucky number
16 is the lucky number
38 is the lucky number

A: You are not using results from previous functions to next.
If you do so then you will end up with error on this third(luckyNumbers).forEach line as function expected [Int] and you will be going to pass [String] as output from this third(luckyNumbers) call.
To work this code, you can have following modifications and run
 let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

 func doImportantWorkChain (first: ([Int]) -> [Int], second: ([Int]) ->
    [Int], third: ([Int]) -> [String]) {
    let first_result = first(luckyNumbers)
    let second_result = second(first_result)
    let third_result = third(second_result)

    for result in third_result {
      print(result)
    }
 }

doImportantWorkChain { number in
  return number.filter {
      return $0.isMultiple(of: 2)
  }
} second: { number in
  return number.sorted {
      return $0 < $1
  }
} third: { number in
  return number.map {
     ("\($0) is the lucky number")
  }
}


text:
Q: Odd utf 8 error attempting to connect to ms sql server Connection string set up as follows:
# -*- coding: utf-8 -*-
import pypyodbc
connection = pypyodbc.connect("DRIVER={SQL Server};SERVER='MyServer';UID='uname';PWD='pwd';DATABASE='mydb'")

receiving following error:
UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-1: truncated data

A: What you need to double check is that in the odbc.ini file, the ServerName for the section is the same name in the freetds.conf file.
For instance:
odbc.ini
[old_flood]
Driver = FreeTDS
Description = RTS Old Flood
ServerName = old_flood       <----- this must be the same as the name in
freetds.conf

freetds.conf
[old_flood]                  <----- This is the same as the ServerName above
    host = <server ip address>
    port = <server port>
    tds version = 8.0

You also need to make sure the DB user you created has proper access to the Database you are trying to read/write to. For me, I just needed read access. You set this up in the Security node of the SQL Server Management Studio. Right click on the user then go to User Mapping. Check the appropriate databases, make sure to highlight the Database, then at the bottom set the database role.


text:
Q: LLDB read String I'm trying debug with lldb.
Breakpoint rule this:
breakpoint set --method '+[NSUUID UUID]'

Breakpoint 2: where = Foundation`+[NSUUID UUID], address = 0x0000000182824360
Process 850 stopped

thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 2.1
frame #0: 0x0000000182824360 Foundation+[NSUUID UUID] Foundation+[NSUUID UUID]:
-> 0x182824360 <+0>: stp x29, x30, [sp, #-0x10]!
0x182824364 <+4>: mov x29, sp
0x182824368 <+8>: adrp x8, 197124
0x18282436c <+12>: ldr x1, [x8, #0x6d8]

How can I read or print each line ?
I mean:
(lldb) p (char *) 0x182824360
(char *) $0 = 0x0000000182824360 "\xfffffffd{\xffffffbf\xffffffa9\xfffffffd\x03"

Thank you for time.

A: If you have the address of a c-string in memory, you can use the x/s ADDR command to see it displayed as a string.  But in this case you're using the address of this method as the argument - you will not get a readable string if you print assembly instructions in memory like that.  You can see the bytes of each instruction in the method with a command like disassemble -b -f.
If you want to see the source code for the method, you need to have access to the source.  Given that this looks like an AppKit method, it's unlikely that you have access to the source.  If you want to inspect or understand what this method is doing, you'll have to do it at an assembly language level.


text:
Q: what is the exact address of parity property the tables shown bellow are taken from efm32LG reference manual
https://www.silabs.com/documents/public/reference-manuals/EFM32LG-RM.pdf
i Have the main base address of 0x4000C000 inside of which i have with 0x004 offset the usartn_frame regesiter and in the 8th 9th place i have my parity properties.
What should i do with all three of those numbers in order to get the whole address to accsess the parity property ?
Thanks.


text:
Q: How come a string multiplied by negative integer results in empty string? '0424242' * -5

I understand how multiplying by strings work fundamentally, but I just stumbled on this strange fact that multiplying by negative numbers yields an empty string and thought it was interesting. I wanted to know the deeper why beneath the surface.
Anyone have a good explanation for this?

A: The docs on s * n say:

Values of n less than 0 are treated as 0 (which yields an empty
  sequence of the same type as s).

A: What would you expect multiplying a string by a negative integer?
On the other hand
# Display results in nice table
print(keyword1, " "*(60-len(keyword1)), value1)
print(keyword2, " "*(60-len(keyword2)), value2)

without being worried than keyword? be longer than 60 is very handy.

A: This behavior is probably defined to be consistent with range(-5) being []. In fact, the latter may be exactly what underlies the behavior you observe.

A: That's literally part of the definition of the operation:

The * (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.


text:
Q: How to use Pusher in Android In my application I want use pusher and for this I write below codes!
For after run application show me error for channel name!
My Activity codes :
//Pusher
            pusher.connect(object : ConnectionEventListener {
                override fun onConnectionStateChange(change: ConnectionStateChange) {
                    Log.e("Pusher", "State changed from ${change.previousState} to ${change.currentState}")
                }

                override fun onError(message: String, code: String, e: Exception) {
                    Log.e("Pusher", "There was a problem connecting! code ($code), message ($message), exception($e)")
                }
            }, ConnectionState.ALL)

            pusherChannel = pusher.subscribe(pusherChannelName)
            pusherChannel.bind(PUSHER_EVENT_NAME) { event ->
                Log.e("Pusher", "Received event with data: $event")
                val jsonObject = JSONObject(event.data)
                runOnUiThread {

                }
            }

and for channelname I write this code :
pusherChannelName = "private-chat-$roomId"

But after run application, crashed it and show me this error!
Logcat error:
 Caused by: java.lang.IllegalArgumentException: Channel name private-chat-4135687754 is invalid. Private channel names must start with "private-" and presence channel names must start with "presence-"
    at com.pusher.client.channel.impl.ChannelImpl.<init>(ChannelImpl.java:17)
    at com.pusher.client.util.Factory.newPublicChannel(Factory.java:96)
    at com.pusher.client.Pusher.subscribe(Pusher.java:258)
    at com.pusher.client.Pusher.subscribe(Pusher.java:229)
    at com.myapp.ChatActivity.onCreate(ChatActivity.kt:158)

How can I fix it?


text:
Q: Trimming string variables by reference in PHP5 I saw another post suggesting using this statement to trim string variables contained in the array:
$_POST=array_map('trim', $_POST);

However, if in the first place, the strings are not contained in an array, I would like to have a trim function that can be used like this:
$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll($a,$b,$c); //arbitrary number of string variables can be passed

I tried to write a function like this:
function trimAll() {

    $args = &func_get_args();
    foreach($args as &$arg) {
        if(isset($arg) && is_string($arg))
            $arg=&trim($arg);
    }
      //no return value is required
}

But without success, the string variables do not get trimmed after function return.
Why and how can this be done??

A: you cannot pass variable number of parameters by reference. As a workaround, try something like
list($a, $b, $c) = array_map('trim', array($a, $b, $c));

better yet, rewrite the snippet so that it doesn't require to use a bunch of variables, which is a bad idea anyways

A: This also works, but will likely make anyone you might happen to work with frustrated as its very unintuitive:
// pass variables by string name
extract(array_map('trim', compact('a', 'b', 'c')));

A: I don't think you can pass a variable-length list of args by reference.
You could pass in an array of references.
function trimAll($array) {
    foreach($array as $k => $v) {
        if(isset($array[$k]) && is_string($array[$k]))
            $array[$k]=&trim($array[$k]);
    }
}

... and suitably modify your call to create an array of references.
$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll(array(&$a,&$b,&$c));

A: I'm not convinced that this is possible using func_get_args, though a comment on it's PHP manual page suggests one possible alternative solution: http://uk3.php.net/manual/en/function.func-get-args.php#90095
However user187291's workaround looks far simpler.

A: Have you tried passing in the variables by Reference.
trimAll(&$a,&$b,&$c)

A: This works, but uses call-time pass-by-reference, which is deprecated in PHP 5.3:
function trimAll() {
    $backtrace = debug_backtrace();
    foreach($backtrace[0]['args'] as &$arg)
        if(isset($arg) && is_string($arg))
            $arg=trim($arg);
}
$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll(&$a,&$b,&$c);
echo "$a\n";
echo "$b\n";
echo "$c\n";


text:
Q: Function satisfying $f(v,w) = f(Uv,Uw)$ for any vectors $v,w$ and unitary $U$ If I have a function $f: V\times V\to \mathbb{R}$ where $V$ is an inner product space over $\mathbb{R}$ and for all unitary matrices $U \in \mathcal{L}(V)$ I have
$$f(v,w) = f(Uv,Uw)$$
can I conclude that $f$ is a function of the inner products $v\cdot w, v\cdot v, w\cdot w$ alone? I am motivated to ask this because I do not know of any other ways to combine two vectors into a real number which is invariant under $v\to U v$ (i.e. orthonormal basis independent). But I am failing to find a way to prove it. How about if the target space is not necessarily $\mathbb{R}$?

A: Yes. This is obvious if $V=0$. Suppose $V\ne0$. Pick a fixed unit vector $u\in V$. We consider three cases:

*

*$v=0$. Let $U$ be a unitary transform such that $w=\|w\|Uu$. Then $f(0,w)=f(U(0),U(\|w\|u))=f(0,\|w\|u)$. Hence it is a function in $\|w\|$.

*$v\ne0$ and $w$ is a scalar multiple of $v$. Let $U$ be any unitary transform such that $Uu=\frac{v}{\|v\|}$. Then
$$
f(v,w)
=f\left(U(\|v\|u),\ U\left(\frac{\langle w,v\rangle}{\|v\|}u\right)\right)
=f\left(\|v\|u,\ \frac{\langle w,v\rangle}{\|v\|}u\right)
$$
is a function of $\|v\|$ and $\langle w,v\rangle$.

*If $v$ and $w$ are linearly independent, $V$ is at least two-dimensional. Therefore, there exists a unit vector $u^\perp$ that is normal to $u$. Let $a=\frac{\langle w,v\rangle}{\|v\|}, b=\sqrt{\|w\|^2-\frac{|\langle w,v\rangle|^2}{\|v\|^2}}$. Then $w=a\frac{v}{\|v\|}+bv^\perp$ for some unit vector $v^\perp$ normal to $v$. Let $U$ be any unitary transform that maps $u$ to $\frac{v}{\|v\|}$ and $u^\perp$ to $v^\perp$. Then
$$
f(v,w)
=f\left(U(\|v\|u),\ U\left(au+bu^\perp\right)\right)
=f\left(\|v\|u,\ au+bu^\perp\right)
$$
is a function of $\|v\|,a$ and $b$. In turn, it is a function of $\|v\|,\|w\|$ and $\langle w,v\rangle$.


text:
Q: Python: How to import arules package from R using Rpy2 I am trying to use python with some nice functions in R. In particular I want to use read.transactions function which is found in one of the packages in R (arules)
I did the following steps
1- Open Anaconda and lunch R studio
In R studio
2- install.packages('arules', dep = TRUE)
3- loadNamespace('arules')
4- .libPaths()
Got
[1] "D:/Anaconda3/Lib/site-packages/rpy2/R/win-library/3.4"
[2] "C:/Program Files/R/R-3.4.4/library"

Now I go to jupyter notebook
In Jupyter Notebook
import rpy2
import rpy2.robjects as RObjects
from rpy2.robjects.packages import importr
utils = importr("utils")

d = {'print.me': 'print_dot_me', 'print_me': 'print_uscore_me'}
try:
    arules = importr('arules', robject_translations = d, lib_loc = "D:/Anaconda3/Lib/site-packages/rpy2/R/win-library/3.4")
except:
    arules = importr('arules', robject_translations = d, lib_loc = "C:/Program Files/R/R-3.4.4/library")

The Outcome was
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-3-5df30d28440c> in <module>()
      3 try:
----> 4     arules = importr('arules', robject_translations = d, lib_loc = "D:/Anaconda3/Lib/site-packages/rpy2/R/win-library/3.4")
      5 except:

~\Anaconda3\lib\site-packages\rpy2\robjects\packages.py in importr(name, lib_loc, robject_translations, signature_translation, suppress_messages, on_conflict, symbol_r2python, symbol_check_after, data)
    452                               _system_file(package = rname)):
--> 453         env = _get_namespace(rname)
    454         version = _get_namespace_version(rname)[0]

RRuntimeError: Error in loadNamespace(name) : there is no package called 'arules'

During handling of the above exception, another exception occurred:

RRuntimeError                             Traceback (most recent call last)
<ipython-input-3-5df30d28440c> in <module>()
      4     arules = importr('arules', robject_translations = d, lib_loc = "D:/Anaconda3/Lib/site-packages/rpy2/R/win-library/3.4")
      5 except:
----> 6     arules = importr('arules', robject_translations = d, lib_loc = "C:/Program Files/R/R-3.4.4/library")
      7

~\Anaconda3\lib\site-packages\rpy2\robjects\packages.py in importr(name, lib_loc, robject_translations, signature_translation, suppress_messages, on_conflict, symbol_r2python, symbol_check_after, data)
    451     if _package_has_namespace(rname,
    452                               _system_file(package = rname)):
--> 453         env = _get_namespace(rname)
    454         version = _get_namespace_version(rname)[0]
    455         exported_names = set(_get_namespace_exports(rname))

RRuntimeError: Error in loadNamespace(name) : there is no package called 'arules'

Which was not able to import the R package to Python
I did the same with DirichletReg and it was successful. I do not know why.
Can anyone help me with this?

A: importr looks into R_HOME directory for the installed R packages. I assume, arules package was not added in the library folder of R_HOME instead it is added in some other location let's say 'C:\Users\User_name\Documents\R\win-library\3.x.x' which might be causing the issue.
If that is the case, copy arules folder from that specific location and add into library folder of R_HOME directory. Try this approach and see whether you are able to come out of the problem.

A: Now to the last of the discovery, there is nothing like that in python, however, there is a way out to use read.transactions
groceries <- read.transactions("groceries.csv", sep = ",")
> summary(groceries)
transactions as itemMatrix in sparse format with
9835 rows (elements/itemsets/transactions) and
169 columns (items) and a density of 0.02609146

Python Jupyter notebook
1) Import the data as
import requests
url = 'https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/groceries.csv'
grocery_dataset = requests.get(url)
# Save string as txt file
f = open('grocery_dataset.txt','w')
f.write(grocery_dataset.text)
f.close()

2) Separate the data and adjust them as you wish
import csv
grocery_items = set()
with open("grocery_dataset.txt") as f:
    reader = csv.reader(f, delimiter=",")
    for i, line in enumerate(reader):
        grocery_items.update(line)
output_list = list()
with open("grocery_dataset.txt") as f:
    reader = csv.reader(f, delimiter=",")
    for i, line in enumerate(reader):
        row_val = {item:0 for item in grocery_items}
        row_val.update({item:1 for item in line})
        output_list.append(row_val)

4) save it as a Dataframe in python
import pandas as pd
grocery_df = pd.DataFrame(output_list)

hence
grocery_df.shape

will give
(9835, 169)

which represent that of the rows and columns of the summary(groceries) in R


text:
Q: Validating non-nullable property in Body as Required - AspNetCore 3.1 I am trying to validate that if a property / field is completely left off on a request that the ModelState is invalid and a BadRequest is sent back to the client, however I am struggling with handling of non-nullable types in request bodies.
Works for nullable types
[Required] public string NullableString { get; set; }

Works for non-nullable and nullable parameters
public IActionResult RequiredNonNullableIntQueryString([Required]int nonNullableInt)

public IActionResult RequiredNullableStringQueryString([Required]string nullableString)

However, it does NOT work for non-nullable types in request bodies
 public IActionResult RequiredNonNullableIntBody([FromBody]NonNullablesRequest request)

 public class NonNullablesRequest
 {
    [Required] // I have also tried [BindRequired] with the same result.
    public int NonNullableInt { get; set; }
 }

I have read:

*

*Microsoft documentation - Model Validation # [Required] validation on the server

*Good article on [Required] and [BindRequired] in ASP.NET Core MVC
The Microsoft documentation states:

The validation system in .NET Core 3.0 and later treats non-nullable parameters or bound properties as if they had a [Required] attribute. Value types such as decimal and int are non-nullable.

That's cool... However later says

On the server, a required value is considered missing if the property is null. A non-nullable field is always valid, and the [Required] attribute's error message is never displayed.

Why? This really doesn't seem to make sense. Why make sure all non-nullables are required but then ignore errors if they were not supplied?
I know many suggestions indicating that one can do the hacky workaround of the following, whereby one sets the required parameter as nullable. To me this does not seem like a reasonable solution.
 public class NonNullablesRequest
 {
    [Required]
    public int? NonNullableInt { get; set; }
 }

This just feels wrong.

*

*The datatype is not accurately representing the expectations of the request arriving

*One has to use .HasValue and .Value every time one is accessing the property to avoid "Possible Null" warnings.

*Seems like an anti-pattern to C# 8.0's Nullable reference types (C# reference)
Is there a way to configure the ModelBinding to invalidate the ModelState if non-nullable types are not supplied?
Edit 1:
It seems there is quite some debate: ASP.NET Core [Require] non-nullable types
I am not sure I agree with Chris Pratt. It is not that we expect the value to not be supplied. In fact the opposite, I want ensure the caller gives me the value. But one has to be defensive against a consumer not supplying the adequate data and therefore the system should reject the requests with a 400 BadRequest.
From this then the expected result is an int not an int?. If no data was supplied the ModelBinder should indicate that the ModelState is invalid.
I can, however, see the challenge where there are two parts 1) Deserialization and then 2) ModelBinding.

A: You could use two different classes for this.
One that represents what your web-application sends to the backend and another that represents your domain model (e.g. entity model).
Http Transport Object
 public class YourWebAppDto
 {
    [Required]
    public int? NonNullableInt { get; set; }
 }

Domain Model Object
 public class YourDomainModelObject
 {
    public int NonNullableInt { get; set; }
 }

By separating those two concerns, you can keep your domain model clean while addressing the potential invalid input of your web application.
Of course, you need a mapping between the two. We use automapper for this.
I know, this does not directly answer your question but it might help as an other way of looking at things.
Cheers, Mike


text:
Q: fibre sequence of classifying space I read Steve Mitchell's Notes on principal bundles and classifying spaces (pdf).
There is a theorem: Let $G$ be any topological group, $H$ an admissible
normal subgroup. Then there is a homotopy-fibre sequence $BH\overset{Bi}{\rightarrow }BG\overset{%
B\rho }{\rightarrow }B(G/H)$ where $i:H\rightarrow G$ is the inclusion and $%
\rho :G\rightarrow G/H$ is the quotient map.
I need a reference (an article or book, not lecture notes) for this theorem with ''admissible hypotesis''.


text:
Q: $a|b^2$ , $b^2|a^3$ , $a^3|b^4$ , $b^4| a^5$... then... Let $a$ and $b$ be positive interger such that $a|b^2$ , $b^2|a^3$ , $a^3|b^4$ , $b^4| a^5$ ... Prove that $a=b$.
Here how I tried to do it, I think it isn't the best way to approach it but anyway I failed in proving it:
EDIT: Let $a = p_1 ^{a_1} p_2 ^{a_2}  ... p_k ^{a_k}$ and $b=  p_1 ^{b_1} p_2 ^{b_2}  ... p_k ^{b_k}$ and $a_i, b_i \geq 0$ for $i$, $ 0 \leq i \leq k$. Then for a specific prime $p_i$, $a_i \leq 2b_i$, $2b_i \leq 3a_i$ , $3a_i \leq 4b_i$ and $4b_i \leq  5a_i$.... I tried to get some information from that but didn't get anything.
This question has been marked as a duplicate but it is in fact different, or maybe that's what I can directly deduce from the conditions. Just look carefully at the titles to realise that they are different.


text:
Q: What is PHP's DOM event structure? I am not sure what to really name this question, and I am sure it might not be really clear. But here it is:
What are the right procedural steps that PHP goes through when loading a single webpage? Are there call events or "something" that I can use to see the process? Maybe something along the lines, (1) server request initiated, (2) start processing PHP code, (3) finish processing PHP code, (4) start loading HTML, (5) start loading JS, (6) done loading the php?

A: Here's how it works:

*

*PHP runs

*PHP outputs stuff

*Stuff gets sent to browser.

It doesn't matter what the "stuff" is. Typically it will be HTML, but it could be an image (using imagecreate and related functions), it could be JavaScript (not sure why you'd want to do this), or even CSS (even less likely). PHP can output JSON. Heck, I seem to recall reading about PHP functions that would let you generate SWF files!
Once PHP is done running, the browser then receives what it sends and deals with it. The browser doesn't know that PHP had anything to do with it. As far as it's concerned, it is whatever the Content-Type header says it is.
This is why PHP can generate JavaScript inline (<script>alert(<?php echo 123; ?>);</script>) but not the other way around. The browser doesn't care, it just sees the result.

A: Php is a module in the webserver. You need the correct mime type .php, php5 etc. registered. Then the php script behave like a normal php installation when you run the script in the console. Hence there isn't such thing like main entry, end entry etc. Script starts from the first line.


text: Q: Google Cloud SQL Server and Node.js I am having trouble connecting a Node.js application (that uses express) I am running on my computer to Google Cloud SQL Server. How would I go about doing this? I am able to connect and make changes using SQL Server Management Studio. I have tried to connect using the public IP address in the overview tab for the database and I have tried connecting using Google cloud proxy. The former would result in an error that said ETIMEDOUT the latter would result in a handshake inactivity error. I also tried using the socketPath field and that resulted in the error ENOENT so I believe I may not be formatting the input for that field correctly. Does anyone have any insight on what I am doing wrong or have any good examples?


text:
Q: How to retrieve only status true or false in below JSON values         Console.WriteLine("mongodb localhost connecting...");
        var client = new MongoClient("mongodb://localhost");
        var db = client.GetDatabase("mobtions");

        var collection = db.GetCollection<BsonDocument>("AffiliTestStatus");
        var filter = new Dictionary<string, string>();
        filter.Add("offerid", "102030");

        dynamic records = collection.Find(new BsonDocument(filter)).ToList();

Here is my JSON response what I had read from above the code
{{ "_id" : ObjectId("5e411eca5b7dfc53ac571f71"), "offerid" : "102030", "status" : true }}

A: give this a try:
    var filter = Builders<BsonDocument>.Filter.Eq("offerid", "102030");
    var projection = Builders<BsonDocument>.Projection.Include("status").Exclude("_id");
    var options = new FindOptions<BsonDocument> { Projection = projection };
    var records = collection.FindSync(filter, options).ToList();


text:
Q: $\log(z_1z_2)=\log(z_1)+\log(z_2)$ where $z_1,z_2\in \mathbb{C}$\{0} I need to prove the set identity of the complex logarithm  $\log(z_1z_2)=\log(z_1)+\log(z_2)$ where $z_1,z_2\in \mathbb{C}$.
$\log(z_1)+\log(z_2)=${$\log|z_1|+\log|z_2|+i(\text{Arg}(z_1)+\text{Arg}(z_2)+4k\pi i|k\in \mathbb{Z}$}$\implies$ {$\log|z_1z_2|+i((\text{Arg}(z_1)+2k\pi i)+(\text{Arg}(z_2)+2k\pi i)|k\in \mathbb{Z}$}$\implies${$\log|z_1z_2|+i(\text{arg}(z_1)+\text{arg}(z_2))|k\in \mathbb{Z}$}$\implies${$\log|z_1z_2|+i(\text{Arg}(z_1z_2)+2k\pi i)|k\in \mathbb{Z}$}$\implies$$\log(z_1z_2)$
This is wclearly wrong I guess but this is how I tried to approach it. Would aprreciate any answers.Thanks a lot

A: Right away your first line is not correct, because $$\log z_1 + \log z_2 = \log |z_1| + \log |z_2| + i(\operatorname{Arg} z_1 + \operatorname{Arg} z_2) + 2\pi i k_1 + 2 \pi i k_2,$$ where $k_1, k_2 \in \mathbb Z$; that is, the branch of the two logs do not necessarily come from the same value of $k$.

A: It is true that
$$\log(z_1z_2)=\log(z_1)+\log(z_2) \tag1$$
when $(1)$ is interpreted as a set equivalence.
This means that any value of $\log(z_1z_2)$ can be expressed as the sum of some value of $\log(z_1)$ and some value of $\log(z_2)$.  And conversely, it means that the sum of any value of $\log(z_1)$ and any value of $\log(z_2)$ can be expressed as some value of $\log(z_1z_2)$.
Note that $(1)$ is true since $\log(|z_1z_2|)=\log(|z_1|)+\log(|z_2|)$ and $\arg(z_1z_2)=\arg(z_1)+\arg(z_2)$.
To see that $\arg(z_1z_2)=\arg(z_1)+\arg(z_2)$, we write $z_1 = |z_1| e^{i\phi_1}$ and $z_2=|z_2|e^{i\phi_2}$.  Clearly, $z_1z_2=|z_1||z_2|e^{i(\phi_1+\phi_2)}$.  So any argument of $z_1$ plus any argument of $z_2$ is an argument of $z_1z_2$.  On the other hand consider any argument of $z_1z_2$, which is of the form $\phi_1+\phi_2+2n\pi$ for some integer $n$.  We could simply take $\arg(z_1)=\phi_1$ and $\arg(z_2)=\phi_2+2n\pi$ and have the stated equality hold.

NOTE: It is important to understand that $(1)$ does not hold in general if $\log(z)$ is taken on the Principal branch of the complex logarithm (or any other designated branch since then we lose a degree of freedom).

As an example, take $z_1=i$ and $z_2=-i$.  Then, if we choose $\log(i)=i\pi/2$ and $\log(-i)=-i\pi/2$, then we must choose the branch of $\log(z)$ for which $\log(1)=0$.  If on the other hand we choose $\log(i)=-i3\pi/2$ and $\log(-i)=-i\pi/2$, then we must choose the branch of $\log(z)$ for which $\log(1)=-i2\pi$.
Conversely, if we choose the branch of $\log(z)$ for which $\log(1)=0$, then for $\log(i)=-i3\pi/2$, we must have $\log(-i)=-i\pi/2$.


text:
Q: How to emit an event on application close using socket.io I am trying emit an event while user closes the tab and for this I am emitting an event on unmount of a component ( which is nested inside a Main component) :
Emitting an event REMOVE_SOCKETS inside the cleanup function of useEffect unfortuantley doesn't trigger the event listener on the server side. I want to pass some paramertes like url, uid to know at which page/path the user closed the tab.
  useEffect(() => {
    return () => {
      debugger;
      if (socket) {
        socket.emit('REMOVE_SOCKETS', {
          url:  window.location.href,
        });
        socket.disconnect();
      }
    };
  }, []);

on express server side:
s.on('REMOVE_SOCKETS', () => {
   // doing some application logic
})

I kept debugger statement to check if the dev tools in Chrome browser pauses instead of the closing of tab while unmounting the component but that didn't happen.
I searched in various answers of the similar question that to emit an event inside the disconnect event listner on server side as soon as we detect disconnect event like the following :
s.on('disconnect', () => {
   s.emit('DISCONNECT_ACK_TO_CLIENT') // which is not needed in my case
} )

but in my case the client will no longer be available and also there is nothing I want to do by emitting event inside disconnect.
Also is there a way I can differetiate tab close and refresh, so that I can emit REMOVE_SOCEKTS only on tab close not on tab refresh ?

A: As far as I can tell, it is not possible to do much when the tab is being closed by the user. And this is on purpose. Otherwise, the user won't be able to close malicious tabs. Event if that was possible, it would still not be reliable - consider killing the browser using task manager for example.
One common solution would be to listen for the "close" event on the server side, and do whatever is needed. This should be complemented with ping/pong messages, in case the socket dies unexpectedly, to track the connection state.


text:
Q: Parsing and arranging text in python I'm having some trouble figuring out the best implementation
I have data in file in this format:
|serial #|machine_name|machine_owner|
If a machine_owner has multiple machines, I'd like the machines displayed in a comma separated list in the field.  so that.

|1234|Fred Flinstone|mach1|
|5678|Barney Rubble|mach2|
|1313|Barney Rubble|mach3|
|3838|Barney Rubble|mach4|
|1212|Betty Rubble|mach5|

Looks like this:

|Fred Flinstone|mach1|
|Barney Rubble|mach2,mach3,mach4|
|Betty Rubble|mach5|

Any hints on how to approach this would be appreciated.

A: You can use dict as temporary container to group by name and then print it in desired format:
import re

s = """|1234|Fred Flinstone|mach1|
|5678|Barney Rubble|mach2|
|1313|Barney Rubble||mach3|
|3838|Barney Rubble||mach4|
|1212|Betty Rubble|mach5|"""

results = {}
for line in s.splitlines():
    _, name, mach = re.split(r"\|+", line.strip("|"))
    if name in results:
        results[name].append(mach)
    else:
        results[name] = [mach]

for name, mach in results.items():
    print(f"|{name}|{','.join(mach)}|")

A: You need to store all the machines names in a list. And every time you want to append a machine name, you run a function to make sure that the name is not already in the list, so that it will not put it again in the list.
After storing them in an array called data. Iterate over the names. And use this function:
data[i] .append( [ ] )

To add a list after each machine name stored in the i'th place.
Once your done, iterate over the names and find them in in the file, then append the owner.
All of this can be done in 2 steps.


text:
Q: Sandcastle: Any way to show inherited members without showing base class? Given a derived class (using C#):
public class BaseClass {
   public void AMethod() {}
}
public class DerivedClass : BaseClass {
}

and running a Sandcastle documentation project in which BaseClass is hidden (Sandcastle Visibility's API filters),
Is there any way to document the DerivedClass members that are inherited from BaseClass as if they were declared explicitly?
I do not want to make wrappers:
public class BaseClass {
   public void AMethod() {}
}
public class DerivedClass : BaseClass {
   new public void AMethod() { base.AMethod(); }
}

^^^ I DON'T WANT TO DO THIS.
These Stack Overflow entries are similar but not what I seek:

*

*Hide methods inherited from Object from Sandcastle-generated documentation?
I want to show rather than hide.

*

*How should I document a inherited members?
The application eschews, explicitly, interfaces or contracts because of a legacy issue with Microsoft Visual Studio 2012.
Thanks!


text:
Q: Error Access to the path "/storage/emulated/0/abc.txt" is denied in Xamarin Android I am trying to run a Xamarin Android app on Android 8 API Level 26 emulator. Its giving exception when I am trying to write logs to file.
Exception:

System.UnauthorizedAccessException: Access to the path
  "/storage/emulated/0/abc.txt" is denied

Code:
string filename = "abc.txt";
var documentsPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = Path.Combine(documentsPath, filename);
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.WriteLine(text);
        }

I have given the READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions also.
Target Android Version: Android 8.0 API Level 26 Oreo
Exception Details:

{System.UnauthorizedAccessException: Access to the path
  "/storage/emulated/0/NECMobilePos_log21092018.txt" is denied. at
  System.IO.FileStream..ctor (System.String path, System.IO.FileMode
  mode, System.IO.FileAccess access, System.IO.FileShare share,
  System.Int32 bufferSize, System.Boolean anonymous,
  System.IO.FileOptions options) [0x001aa] in
  /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:239
  at System.IO.FileStream..ctor (System.String path, System.IO.FileMode
  mode, System.IO.FileAccess access, System.IO.FileShare share,
  System.Int32 bufferSize, System.Boolean isAsync, System.Boolean
  anonymous) [0x00000] in
  /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:149
  at System.IO.FileStream..ctor (System.String path, System.IO.FileMode
  mode, System.IO.FileAccess access) [0x00000] in
  /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:86
  at (wrapper remoting-invoke-with-check)
  System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess)
  at NECMobilePOS.Client.DroidLatest.FileLogger_Android.SaveText
  (System.String filenamePassed, System.String text) [0x000d1] in
  C:\ABC\XYZ\FileLogger_Android.cs:73 }

A: For Versions >= 23, you need to provide the Runtime Permissions. You can go through the document from the link below.
https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/
Or for testing now, you can go to app permissions and allow storage permission.


text:
Q: PyCharm crashing at startup Since a few days, PyCharm 2016.1.2 is crashing immediately at startup on my Mac (OS X.10.5).
I have tried to reinstall the IDE from scratch (i.e. deleting the app + everything concerning PyCharm in ~/Library) but it doesn't solve the problem.
I have also checked the IDE logs (in ~/Library/Logs/PyCharm) but there is no error here.
The only information available comes from the OS error box:
Crashed Thread:        0  AppKit Thread  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGABRT)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000303620

Note that I also use IntellijIdea on the same computer and I don't have any issues with it. Thanks for any information or advice.

A: I managed to "fix" the issue by upgrade to OS X El Capitan.

A: Under the package container of pycharm ,you will find file info.plist.
open the file and search for JVMVersion and remove 1.8+ from that and save it.
You JVMVersion should look like below-
**<key>JVMVersion</key>
      <string>1.8*</string>**

save and now open the pycharm.