text:
Q: User and Friends relationship model in prisma ORM I have been struggling to create User and Friends relationship in Prisma and facing some ambiguous errors
So I have a User entity with the following Model
model Users {
  id       String  @id @unique
  name     String
  email    String
  password String
}

Now I want to add a self-relationship with the many-to-many use case. where a user can have many Friends like following
model Users {
  id       String  @id @unique
  name     String
  email    String
  password String
  friends Users[]
}

but Prisma is complaining me about this and i am unable to understand why cant we self reference here

A: The correct way to manage self relationship with n to n case would be as follow.
model Users {
  id       String @id @default(uuid())
  name     String
  email    String
  password String

  friends  Users[] @relation("friends")
  friendOf Users[] @relation("friends")
}

reference https://www.prisma.io/docs/concepts/components/prisma-schema/relations/self-relations#many-to-many-self-relations


text:
Q: MySQL get rows, but for any matching get the latest version I'm developing a CMS, and implementing versioning by adding a new entry to the database with the current timestamp.
My table is set up as follows:
id | page | section | timestamp | content

"Page" is the page being accessed, which is either the path to the page ($page_name below), or '/' (to indicate 'global' fields).
"Section" is the section of the page being edited.
I want to be able to select all rows for a given page, but each section should only be selected once, the one with the latest timestamp being selected.
I've tried using the following CodeIgniter Active Record code:
$this->db->select('DISTINCT(section), content');
$this->db->where_in('page', array('/', $page_name));
$this->db->order_by('timestamp', 'desc');
$query = $this->db->get('cms_content');

Which is producing the following SQL:
SELECT DISTINCT(section), `content`
FROM (`cms_content`)
WHERE `page` IN ('/', 'index.html')
AND `enabled` = 1
ORDER BY `timestamp` desc

Which is returning both test rows (rows have all same fields except id, timestamp and content).
Any ideas as to where I'm going wrong?
Thanks!

A: Your mistake is thinking that DISTINCT applies only to section - an easy mistake to make as the parentheses are misleading here. In fact the DISTINCT applies to the entire row whether or not you have parentheses. It is therefore best to omit the parentheses to avoid confusion.
Your problem is a classic 'max per group' problem. There are many, many ways to write this query and it is probably one of the most popular SQL questions on this site so you can search Stack Overflow to find ways to solve it. One way to get you started is to only select rows which hold the maximum timestamp for that section:
SELECT section, content
FROM cms_content T1
WHERE page IN ('/', 'index.html')
AND enabled = 1
AND timestamp = (
    SELECT MAX(timestamp)
    FROM cms_content T2
    WHERE page IN ('/', 'index.html')
    AND enabled = 1
    AND T1.section = T2.section
)

I'm sorry but I do not know how to convert this SQL code into CodeIgniter Active Record. If another user more familiar with Active Record wishes to use this as a starting point for their own answer, they are welcome.

A: DISTINCT is for all columns selected, and because "content" differs you will get two different rows.
You only want to order by timestamp and limit 1 because you always want the latest.
But may I suggest that you keep a cross reference to the "active" page? That way, you are able to revert to a previous revision without dumping the new ones.
Meaning:
page
----
id
info
active_page_id

page_revisions
--------------
id
page_id
content
timestamp
...

Meaning, you have one-to-many between page <-> page_revisions, aswell as a one-to-one between page and page_revisions to keep track of the "current" revision. With this approach you are able to just join in the active revision.

A: This will do the job in Codeigniter, without temporary tables:
$this->db->query( "SELECT *
    FROM cms_content AS c1
    LEFT JOIN cms_content AS c2
        ON c1.page=c2.page
        AND c1.section=c2.section
        AND c1.timestamp < c2.timestamp
    WHERE c2.timestamp IS NULL AND page=?", $page );

redpajama_set_name: RedPajamaStackExchange


text:
Q: can't access constructor's context from $scope's event How can I access NavService (i.e. or the controller's context)?
module MyModule {
    export class MyClass {
        public static $inject = ['$scope', 'NavService'];
        constructor(private $scope: any, private NavService: MyWizard.NavService) {
            this.$scope.okCmd = this.okCmd;
        }
        okCmd() {
            this.NavService.next('details');
        }
}

Result: NavService is undefined because this. actually represents $scope.

A: That is a common problem in the JavaScript world, and that's why we will have function binding expressions in es7: this.$scope.okCmd = ::this.okCmd;
For now you can use a lambda that will store the constructor's this pointer in it's closure:
module MyModule {
  export class MyClass {
    public static $inject = ['$scope', 'NavService'];
    constructor(private $scope: any, private NavService: MyWizard.NavService) {
      this.$scope.okCmd = () => this.okCmd();
    }
    okCmd() {
      this.NavService.next('details');
    }
  }
}


text:
Q: Python Interpreter Behavior? I am using Python 2.7.
This is what happened:
>>> 2+++2
4

I am not sure as to how the python interpreter interprets this expression.
The only reason I can come up with is that successive "+" after the first "+" are considered as unary operators and the first "+" is considered as a binary operator, but what is actually the mechanism that is happening I am not sure of.
I would want someone to answer the question in terms of the grammar specifics of Python programming language and also report some other ambiguous expressions. I came up with some other expressions which are listed below (with their results):
>>> 2------------2
4
>>> 2+-2+-2+-2+-2+-2-------------------------2
-10

A: You're right; Python is interpreting this as 2 + (++2), as you might expect. You can see this by looking at the compiled bytecode for 2+2 and 2+++2, as follows:
>>> dis.dis(lambda: 2+2)
  1           0 LOAD_CONST               2 (4)
              3 RETURN_VALUE
>>> dis.dis(lambda: 2+++2)
  1           0 LOAD_CONST               1 (2)
              3 LOAD_CONST               1 (2)
              6 UNARY_POSITIVE
              7 UNARY_POSITIVE
              8 BINARY_ADD
              9 RETURN_VALUE

You might want to know why Python parses 2+++2 like this. First, the code gets split up into tokens:
>>> from cStringIO import StringIO
>>> import tokenize
>>> tokenize.generate_tokens(StringIO("2+++2").readline)
  9 <generator object generate_tokens at 0x0000000007BC7480>
>>> list(tokenize.generate_tokens(StringIO("2+++2").readline))
  10
[(2, '2', (1, 0), (1, 1), '2+++2'),
 (51, '+', (1, 1), (1, 2), '2+++2'),
 (51, '+', (1, 2), (1, 3), '2+++2'),
 (51, '+', (1, 3), (1, 4), '2+++2'),
 (2, '2', (1, 4), (1, 5), '2+++2'),
 (0, '', (2, 0), (2, 0), '')]

It's the parser that then associates the list of tokens into a syntax tree:
>>> st = ast.parse("2+++2")
>>> st
  36 <_ast.Module at 0x7d2acc0>
>>> ast.dump(st)
  37 'Module(body=[Expr(value=BinOp(left=Num(n=2), op=Add(), right=UnaryOp(op=UAdd(), operand=UnaryOp(op=UAdd(), operand=Num(n=2)))))])'

This follows standard disambiguation rules.

A: Take a look at the way Python defines unary and binary arithmetic operations. Especially unary expressions:
u_expr ::=  power | "-" u_expr | "+" u_expr | "~" u_expr

You can see the part "+" u_expr, which pretty much means that a number of + followed by a number is a valid unary expression (sort of recursive, huh?).
On the other hand you got these two:
m_expr ::=  u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr
        | m_expr "%" u_expr
a_expr ::=  m_expr | a_expr "+" m_expr | a_expr "-" m_expr

Which pretty much mean, when you have a binary expression, your read the first atom, then the sign, and read the next binary/unary expression. Which read code like:
2+-2+-2+-2+-2+---2+-2

essentially like:
2 + (-2) + (-2) + (-2) + (-2) + (-(-(-2))) + (-2)

A: It's perfectly plain in the grammar:
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power

So since any factor may be preceded by one of the unary operators, this will extend until the arithmetic expression consumes the binary operator. It's not ambiguous at all, since we have neither C's ++ operator nor Haskell's ability to define new ones.


text:
Q: Extract value inside a matching block using JQ in a nested array I have a JSON output like the one below and need to find the value of appId of the exact match of "name": "exampleAppName01" using JQ. I could narrow it down to the exact name, but I have no idea how to extract other values that matched with it.
The JSON output consists a lot of blocks like this. Simply I need to find the appId if the name matches what we provide.
{
  "apps": [
    {
      "appId": "exampleAppID01",
      "appArn": "arn:aws:amplify:eu-west-1:xxxxxxxxxxxxx:apps/exampleAppID01",
      "name": "exampleAppName01",
      "tags": {
        "pci_scope": "none",
        "project": "exampleRepoName01",
        "environment": "dev-default",
        "workspace": "default",
        "terraform": "true"
      },
      "description": "Amplify App for the exapmle project.",
      "platform": "WEB_DYNAMIC",
      "createTime": "2022-08-09T12:26:10.472000+05:30",
      "updateTime": "2022-08-16T13:18:31.658000+05:30",
      "iamServiceRoleArn": "arn:aws:iam::xxxxxxxxxxxxx:role/exampleAppName01-role",
      "environmentVariables": {
        "APP_DEBUG": "true",
        "_LIVE_UPDATES": "[{\"pkg\":\"@aws-amplify/cli\",\"type\":\"npm\",\"version\":\"latest\"},{\"pkg\":\"next-version\",\"type\":\"internal\",\"version\":\"latest\"},{\"pkg\":\"yarn\",\"type\":\"npm\",\"version\":\"latest\"},{\"pkg\":\"node\",\"type\":\"nvm\",\"version\":\"16.13.0\"}]"
      },
      "defaultDomain": "exampleAppID01.amplifyapp.com",
      "enableBranchAutoBuild": true,
      "enableBranchAutoDeletion": true,
      "enableBasicAuth": false,
      "customRules": [
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        },
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        },
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        }
      ],
      "buildSpec": "version: 1\nbackend:\n  phases:\n    build:\n      commands:\n        - '# Execute Amplify CLI with the helper script'\n        - amplifyPush --simple\nfrontend:\n  phases:\n    preBuild:\n      commands:\n        - yarn install\n    build:\n      commands:\n        - yarn run lint\n        - yarn run build\n  artifacts:\n    baseDirectory: .next\n    files:\n      - '**/*'\n  cache:\n    paths:\n      - node_modules/**/*\ntest:\n  artifacts:\n    baseDirectory: cypress\n    configFilePath: '**/mochawesome.json'\n    files:\n      - '**/*.png'\n      - '**/*.mp4'\n  phases:\n    preTest:\n      commands:\n        - echo \"test\"\n#test:\n#  artifacts:\n#    baseDirectory: cypress\n#    configFilePath: '**/mochawesome.json'\n#    files:\n#      - '**/*.png'\n#      - '**/*.mp4'\n#  phases:\n#    preTest:\n#      commands:\n#        - npm install\n#        - npm install start-server-and-test cypress mocha mochawesome mochawesome-merge mochawesome-report-generator --save-dev\n#    test:\n#      commands:\n#        # We need to set the NEXTAUTH_URL to localhost for the cypress tests but leave them as they were coming from the set environment variables for the deployed app\n#        - NEXTAUTH_URL=http://localhost:3000\n#        - npm run build\n#        - npx start-test 'yarn start' 3000 'npx cypress run --reporter mochawesome --reporter-options \"reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss\"'\n#    postTest:\n#      commands:\n#        - npx mochawesome-merge cypress/report/mochawesome-report/mochawesome*.json > cypress/report/mochawesome.json\n",
      "customHeaders": "",
      "enableAutoBranchCreation": true,
      "autoBranchCreationPatterns": [
        "example-*"
      ],
      "autoBranchCreationConfig": {
        "stage": "NONE",
        "enableAutoBuild": true,
        "environmentVariables": {},
        "enableBasicAuth": false,
        "enablePullRequestPreview": false
      },
      "repositoryCloneMethod": "SSH"
    },
    {
      "appId": "exampleAppID02",
      "appArn": "arn:aws:amplify:eu-west-1:xxxxxxxxxxxxx:apps/exampleAppID02",
      "name": "exampleAppName02",
      "tags": {
        "pci_scope": "none",
        "project": "exampleRepoName02",
        "environment": "dev-default",
        "workspace": "default",
        "terraform": "true"
      },
      "description": "Amplify App for the exapmle project.",
      "platform": "WEB_DYNAMIC",
      "createTime": "2022-08-09T12:26:10.472000+05:30",
      "updateTime": "2022-08-16T13:18:31.658000+05:30",
      "iamServiceRoleArn": "arn:aws:iam::xxxxxxxxxxxxx:role/exampleAppName02-role",
      "environmentVariables": {
        "APP_DEBUG": "true",
        "_LIVE_UPDATES": "[{\"pkg\":\"@aws-amplify/cli\",\"type\":\"npm\",\"version\":\"latest\"},{\"pkg\":\"next-version\",\"type\":\"internal\",\"version\":\"latest\"},{\"pkg\":\"yarn\",\"type\":\"npm\",\"version\":\"latest\"},{\"pkg\":\"node\",\"type\":\"nvm\",\"version\":\"16.13.0\"}]"
      },
      "defaultDomain": "exampleAppID02.amplifyapp.com",
      "enableBranchAutoBuild": true,
      "enableBranchAutoDeletion": true,
      "enableBasicAuth": false,
      "customRules": [
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        },
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        },
        {
          "source": "/<*>",
          "target": "https://xxxxxxxxxxxx.cloudfront.net/<*>",
          "status": "200"
        }
      ],
      "buildSpec": "version: 1\nbackend:\n  phases:\n    build:\n      commands:\n        - '# Execute Amplify CLI with the helper script'\n        - amplifyPush --simple\nfrontend:\n  phases:\n    preBuild:\n      commands:\n        - yarn install\n    build:\n      commands:\n        - yarn run lint\n        - yarn run build\n  artifacts:\n    baseDirectory: .next\n    files:\n      - '**/*'\n  cache:\n    paths:\n      - node_modules/**/*\ntest:\n  artifacts:\n    baseDirectory: cypress\n    configFilePath: '**/mochawesome.json'\n    files:\n      - '**/*.png'\n      - '**/*.mp4'\n  phases:\n    preTest:\n      commands:\n        - echo \"test\"\n#test:\n#  artifacts:\n#    baseDirectory: cypress\n#    configFilePath: '**/mochawesome.json'\n#    files:\n#      - '**/*.png'\n#      - '**/*.mp4'\n#  phases:\n#    preTest:\n#      commands:\n#        - npm install\n#        - npm install start-server-and-test cypress mocha mochawesome mochawesome-merge mochawesome-report-generator --save-dev\n#    test:\n#      commands:\n#        # We need to set the NEXTAUTH_URL to localhost for the cypress tests but leave them as they were coming from the set environment variables for the deployed app\n#        - NEXTAUTH_URL=http://localhost:3000\n#        - npm run build\n#        - npx start-test 'yarn start' 3000 'npx cypress run --reporter mochawesome --reporter-options \"reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss\"'\n#    postTest:\n#      commands:\n#        - npx mochawesome-merge cypress/report/mochawesome-report/mochawesome*.json > cypress/report/mochawesome.json\n",
      "customHeaders": "",
      "enableAutoBranchCreation": true,
      "autoBranchCreationPatterns": [
        "example-*"
      ],
      "autoBranchCreationConfig": {
        "stage": "NONE",
        "enableAutoBuild": true,
        "environmentVariables": {},
        "enableBasicAuth": false,
        "enablePullRequestPreview": false
      },
      "repositoryCloneMethod": "SSH"
    }
  ]
}


text:
Q: Pandas deleting rows in order Given a particular df:
ID Text
1  abc
1  xyz
2  xyz
2  abc
3  xyz
3  abc
3  ijk
4  xyz

I want to apply condition where: Grouping by ID, if abc exists then delete row with xyz.  The outcome would be:
ID Text
1  abc
2  abc
3  abc
3  ijk
4  xyz

Usually I would group them by Id and apply np.where(...).  However, I don't think this approach would work for this case since it's based on rows.
Many thanks!

A: To the best of my knowledge, you can vectorize this with a groupby + transform:
df[~(df.Text.eq('abc').groupby(df.ID).transform('any') & df.Text.eq('xyz'))]

   ID Text
0   1  abc
3   2  abc
5   3  abc
6   3  ijk
7   4  xyz

A: I am using crosstab
s=pd.crosstab(df.ID,df.Text)
s.xyz=s.xyz.mask(s.abc.eq(1)&s.xyz.eq(1))
s
Out[162]:
Text  abc  ijk  xyz
ID
1       1    0  NaN
2       1    0  NaN
3       1    1  NaN
4       0    0  1.0
s.replace(0,np.nan).stack().reset_index().drop(0,1)
Out[167]:
   ID Text
0   1  abc
1   2  abc
2   3  abc
3   3  ijk
4   4  xyz


text:
Q: Quarantine status in Azure Active Directory sync In January I installed AAD Cloud Sync Agent and it worked till the end of July.
Checking Azure AD in the cloud the domain is in quarantine status and the installed agents list reports none. First question: was my agent, which worked for months, automatically removed from the list ?
Executing AAD Cloud Sync Agent Wizard again it reports the following error:

PowerShell: System.Net.WebException: Remote server error: (401) Unauthorized.
in System.Net.HttpWebRequest.GetResponse()
in Microsoft.ApplicationProxy.Connector.PSModule.OnpremisesPublishingOperations.ProcessRequestWithoutPayload(HttpWebRequest request)
in Microsoft.ApplicationProxy.Connector.PSModule.GetPublishedResourceCommand.ProcessRecord()
in System.Management.Automation.CommandProcessor.ProcessRecord()

The agent log is full of the following errors:

AADConnectProvisioningAgent.exe Error: 0 : Service bootstrap request failed with exception. Request Id: 'fa4d8a82-150a-4326-a556-ccf43b1a9f45', Error: 'System.ServiceModel.Security.MessageSecurityException: La richiesta HTTP non è autorizzata con lo schema di autenticazione client 'Anonymous'. Intestazione di autenticazione ricevuta dal server: ''. ---> System.Net.WebException: Errore del server remoto: (401) Non autorizzato.
in System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
in System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)

It is not a TLS 1.2 problem because it is not mandatory yet.
Admin AAD login has been verified.
The public ip of AAD agent on premise may have changed, is it possible the requests fail because the ip is filtered ?

A: "quarantine status" happens when usually there's a sync problem, which you need to manually address: https://docs.microsoft.com/en-us/azure/active-directory/cloud-sync/how-to-troubleshoot#provisioning-quarantined-problems
Not sure why the agent was removed from the list, it could be removed manually by someone else? check the tenant Audit Logs and hope you see something in the past 30 days.
Translating your error message to English:

'System.ServiceModel.Security.MessageSecurityException: The richest
HTTP is not authorized with the schema of the 'Anonymous' client
authentication. Intestazione di authenticazione ricevuta dal server:
''. ---> System.Net.WebException: Errore del remote server: (401) Non
autorizzato.

Looks like the account you're using is not working or you're passing a proxy, check the user sign-in logs in Azure AD for more details and fix accordingly if it's an auth problem. If you see no data in the logs then then double check if you a have a proxy and configure that in your sync agent settings: https://docs.microsoft.com/en-us/azure/active-directory/cloud-sync/how-to-troubleshoot#agent-times-out-or-certificate-is-invalid
The Azure AD Cloud Sync agent doesn't store any configs locally, so if issue persists, uninstall it completely, review the prerequisites, and then perform a new deployment accordingly: https://docs.microsoft.com/en-us/azure/active-directory/cloud-sync/how-to-prerequisites


text:
Q: MessageDialog in separate thread In my current project I need to perform some calculations when a specific button is pressed, and while I perform these calculations, I want to show a Gtk::MessageDialog that simply states that calculations are being performed. So, I initialize the MessageDialog like this (for the moment just ignore that I actually don't need the pointer here):
Gtk::MessageDialog *waitdialog;
Gtk::MessageDialog dia("Processing", false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_NONE, true);
dia.set_title("Wait.");
dia.set_transient_for(*(Gtk::Window *)this);
waitdialog = &dia;

Next I want to start a separate thread with the dialog:
std::thread dialog_thread(wait_dialog,waitdialog);

The wait_dialog method is defined as follows:
void wait_dialog(Gtk::MessageDialog *dialog){
  dialog->run();
}

The problem now is, that even though the main window is darkened (because of set_transient_for), the message dialog is not visible. However, when I don't start a seperate thread, but just call waitdialog->run() instead, this will show the dialog properly (but will result in a loop).
So, the question is: why does the workaround with the separate thread not work? I can't make any sense of that :-(

A: GUI components are required to stay in the GUI loop.  Your long running calculations belong in the thread.  The calculation thread then signals back to the GUI thread to close the modal dialog.  Also, you should use glib threads instead of std::threads.  Here's how I would structure program:
// in header, member var dispatcher used to signal GUI thread
// and our member var thread
Glib::Dispatcher m_signalDone;
Glib::Thread* m_someThread;

...

// in constructor, hook up dispatcher event
m_signalDone.connect(sigc::mem_fun(this, &MyClass::OnDone));

...

// later when ready to kick off thread...
// show dialog or progess bar or something and kick off thread...
m_someThread = Glib::Thread::create(sigc::mem_fun(*this, &MyClass::CalcMethod), true);

...

void MyClass::CalcMethod()
{
   // do your long running stuff...

   // when done signal completion back to GUI
   m_signalDone.emit();
}

...

void MyClass::OnDone()
{
    // clean up dialog or progress bar or whatever

    // kill thread
    m_currentBackUpThread->join();
    m_currentBackUpThread = NULL;
}


text:
Q: How to navigate through elements in lxml? Say I have element tree returned by xquery
categories = tree.xpath(u"//ul[@class='tree-root']/li")

for cat in categories:
    catName = cat.find('span/span') # is there any shortcut for this?

As you can see I use find in order to access span elements. The question is there any shortcut to access child elements with known path or find is the only way?

A: You can use xpath() on elements the same way as on the tree:
span = cat.xpath('span/span')

Unfortunately, I couldn't find anything about more direct access to subelements in the docs. They can be iterated over or accessed as list elements, but that's not very handy. The Element class only provides access to the attributes of the current element.


text:
Q: prime-run: Segmentation fault When I run any graphical program with prime-run I get the following error:
[jomosoto@Jomosoto ~]$ prime-run glxinfo
name of display: :0
/usr/bin/prime-run: line 2:  7630 Segmentation fault      __NV_PRIME_RENDER_OFFLOAD=1 __VK_LAYER_NV_optimus=NVIDIA_only __GLX_VENDOR_LIBRARY_NAME=nvidia "$@"

The problem should be the __GLX_VENDOR_LIBRARY_NAME=nvidia:
[jomosoto@Jomosoto ~]$ __GLX_VENDOR_LIBRARY_NAME=nvidia glxinfo
name of display: :0
Segmentation fault

System Info:
OS: Artix Linux x86_64
Host: 82JQ Legion 5 Pro 16ACH6H
Kernel: 5.18.2-artix1-1

lspci -k | grep -A 3 VGA:
01:00.0 VGA compatible controller: NVIDIA Corporation GA104M [GeForce RTX 3070 Mobile / Max-Q] (rev a1)
        Subsystem: Lenovo Device 3a4f
        Kernel driver in use: nvidia
        Kernel modules: nouveau, nvidia_drm, nvidia
--
05:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Cezanne (rev c5)
        Subsystem: Lenovo Device 3a4f
        Kernel driver in use: amdgpu
        Kernel modules: amdgpu

My /etc/X11/xorg.conf.d/ and /etc/modprobe.d/ are empty and there's no /etc/X11/xorg.conf
Additional Information: nvidia-bug-report.sh

Any ideas?
Side note: I think I caused this problem when trying to configure my optimus (I tried optimus-manager, bumblebee, prime-select and more - all uninstalled now). It may be (not sure) some auto-generated config.
Side question: Does steam automatically use offloading? Steam games stopped launching shortly before I discoreverd my problem with prime-run.


text:
Q: stopping turtles in the imported drawing to fill the drawing Actually, I am using patch-ahead 1 condition for stopping my turtles in drawing imported by using "import-pcolors" command.
drawing or shape (such as star-fish) is aligned on the center of the world's patches and 4 turtles(seeds) are placed near the center of the origin within shape drawing remained stationary until the end, all other turtles are placed randomly and also moves randomly in the world with stationary? = false.
The goal is to completely fill the shape(drawing) without leaving any patch empty in the drawing, by moving the turtles randomly and stop when approaches to next stationary turtle and become stationary? = true, and reference for all other remaining non-stationary turtles.
here is what I have tried so far,
    to setup
      import-pcolors "starnew.png" ; image imported in the world on patches for turtles to interact

      create-robots num-of-robots
        [
          set seed? false
          set stationary? false
        set shape "circle 2"
        setxy random-pxcor random-pycor
      ]

      ask turtles
      [
        if who = 0 ; similarly for who = 1 (setxy = 0 1 ), who = 2 (setxy = 1 0 ), who = 3 (setxy = 0 -1 ),  having loaction near centre origin
        [
          setxy  0 0
          set seed? true
          set stationary? true
          set localized? true
          ]
      ]
    end
    to go
ask robots with [stationary? != true]
  [

    ifelse pcolor = white   ;; out-shape
      [
        wall
        fd 0.1
        rt random 30
        lt random 30
      ]
      [                     ;; In-shape
        set pos-inside? true
        ifelse ( not any? (robots-on patch-ahead 1 ) with [stationary? = true or seed? = true]   )
        [
          fd 0.1
          rt random 30
          lt random 30
        ]
        [
          set pos-inside? true
          set stationary? true
          set localized? true
          stop
        ]
      ]
  ]
  end

the desired behavior I want to achieve is shown in the picture below.


text:
Q: UIApplication.sharedApplication().delegate as! AppDelegate EXC_BREAKPOINT I am trying to use CoreData to save data and today when I tried to test the App I got the message: "fatal error: unexpectedly found nil while unwrapping an Optional value" and an EXC_BREAKPOINT message.
class ViewController: UIViewController {

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContext: NSManagedObjectContext = appDelegate.managedObjectContext <-- Here is the error

And if I use UIApplication.sharedApplication().delegate as! AppDelegate to call any other function from AppDelegate I get the same error.
Anybody knows a fix for that?

A: During initialization it is not guaranteed that AppDelegate is available.
Declare managedObjectContext as implicit unwrapped optional and assign the value in viewDidLoad
class ViewController: UIViewController {

    var managedObjectContext: NSManagedObjectContext!

    override func viewDidLoad()
    {
       super.viewDidLoad()
       let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
       managedObjectContext = appDelegate.managedObjectContext
    }

}

Or declare the variable as lazy initialized on the top level of the class.
lazy var managedObjectContext : NSManagedObjectContext = {
   let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
   return appDelegate.managedObjectContext
}()


text:
Q: design help on offline / reporting database We are considering to move away from having reports from a transactional database to an offline/ reporting database for our java web based project. Some ETL(like Kettle) to load the full/delta updates to offline database.
Reasons are obvious, to reduce load on transactional db & reporting performance.
Our outstanding questions are related to designing the offline database as i have no much knowledge on OLAP. Requirement is to have reports run by some report engine like Jasper/Pentaho, develop analytics and dashboards.
what is the best way to design offline/reporting
1) One big flat table? -  I am sure this very bad idea.
2) Multiple flat tables. I mean multiple denormalized tables. Idea is to de-normalize the related tables and link other de-normalized tables to get detailed reports.
And any idea how we can handle summaries?
3) Star schema, facts and dimensions.
One dumb question here: can we have all other detail columns in a fact table along with additive measures(summaries or aggregated data)
Is there a an tool to denormalize data from a set of normalised tables?
Thanks in advance.
Pradeep


text:
Q: UISlider - Add UILabel to min/max UIImageView? As shown below,
UISlider has a Minimum Image and Maximum Image.
These imageView elements can be set to any UIImage.
I have a custom UISlider scenario and I'm trying to simply make the left and right image a string (UILabel).
Any smart ideas about how I might inject a UILabel into these elements?
Or failing that, how I can extend my UISlider subclass so that it has a UILabel either side of it?
I guess I could encapsulate inside another UIView but I don't love that idea.
Thanks
WS

A: Here is smart & simple idea to achieve, that you want.
Look at this snapshot:

*

*Do not set min and max image for UISlider.

*Set UILabels on left and right of UISlider. UILabels allows to set string value.

*You can create custom view or IBDesignable with slider & two labels. This would be very easier than subclass UISlider and overriding of default properties.


text:
Q: Completeness of $\{x^m (1-x)^n\}$ over $L_2(0,1)$? The question can be obviously generalized, as we can easily come up with an arbitrary set of functions $\{f_n(x)\}$ over $(0,1)$.
Is there any theorem which can tell easily a set of basis functions are complete or not?

A: Work in $[0,1]$ instead (which doesn't matter, as singletons are null), then Bernstein (or Stone-Weierstrass) tells you $\{x^m(1-x)^n\mid (m,n)\in\mathbb{Z}^2, m,n\geq 0\}$ spans a uniformly dense subset of $C[0,1]$.  Hence they are complete set in $L_2[0,1]$.


text:
Q: SocketIO does not work in components of other routes in REACT I have a component called NAV this component is static in the application, in that component I handle the socket.on listener to store the notification information, if there is a path that does not contain the socket it works normal, but when I put the socket in a component Inside of a route in react, the socket that was inside the NAV component stops working, I swear I must repeat the socket.on code of the NAV component so that the information can arrive again, this is a bad practice because the code should not be repeated so much This happens to me with 5 components in different routes, but I don't know how to prevent this from happening
I tried to make a component that covers all the components inside the routes and manages the sockets information there but it didn't work for me.
THIS IS THE CODE I HAVE IN THE SOCKET ON THE SERVER
socket.on("received event", async (id, productID) => {
  if (id || productID) {
    let product;

    if (productID !== undefined)
      product = await Product.findById(productID);

    const user = getUser(id ? id : product.owner);

    if (user.length > 0)
      user.map((user) => io.to(user.socketId).emit("received event"));
  }
});

THIS IS THE CODE THAT I HAVE IN THE NAV BUT I HAVE TO REPEAT IT IN EACH ROUTE THAT INTEGRATES THE SOCKET
useEffect(() => {
  socket.on("received event", async () => {
    await searchNotifications();
  });

  return () => socket.off();
});

THIS IS THE MAIN APP COMPONENT
function App() {
  return (
    <LoadingZone>
      <Nav /> // HERE IS THE "SOCKET" THE ABOVE CODE THAT IS REPEATED
      <Routes>
        <Route path="/" element={<Home />}/>
        <Route path="/report" element={<PrivateRoute><Report /></PrivateRoute>}/>
        <Route path="/messages" element={<PrivateRoute><Messages /></PrivateRoute>}/>
        <Route path="/notifications" element={<PrivateRoute><Notifications /></PrivateRoute>}/>
        <Route path="/help/*" element={<Help />} />
        <Route path="/post/information/*" element={<Post />} /> // THE SOCKET THAT IS IN THE NAV DOES NOT AFFECT IT
      </Routes>
      <Footer />
      <PopupWindow/>
    </LoadingZone>
  );
}

export default App;

It's supposed to keep taking the socket from the NAV since it doesn't depend on any route but it doesn't, I have the main socket in a separate file where I can access the different components. But this is my problem
This is the nav component
import { socket } from "../api";

function Nav() {
   const dispatch = useDispatch();

   const searchNotifications = useCallback(async () => {
    const briefNotifications = await getNotifications(cookies.get("id"));

    const currentNotification = [];
    let count = 0;

    for (let i = 0; i < 3; i++) {
      if (briefNotifications[i] !== undefined)
        currentNotification.push(briefNotifications[i]);
    }
    for (let i = 0; i < briefNotifications.length; i++) {
      if (!briefNotifications[i].view) count += 1;
    }

    dispatch(set(count));
    dispatch(changeNotifications(currentNotification));
  }, [dispatch]);

  useEffect(() => {
    socket.on("received event", async () => { // This works until I go to the Post route
      await searchNotifications();
    });

    return () => socket.off();
  });

   Return <Content/>
}

This is the Post component
function Post() {
   ... // Code that has nothing to do with the problem

   Return <Content/>
}

It's supposed to keep taking the socket from the NAV since it doesn't depend on any route but it doesn't

A: Not a lot of context provided for what exactly isn't working, but it appears the useEffect hook is missing a dependency array. Without it the component(s) are constantly opening/closing (subscribing/unsubscribing) the socket connection.
Since it doesn't appear there are any external dependencies try adding an empty dependency array so the effect is run once when the component mounts to connect the socket event, and unsubscribed from the event when the component unmounts.
Example:
useEffect(() => {
  socket.on("received event", async () => {
    await searchNotifications();
  });

  return () => socket.off();
}, []); // <-- add empty dependency array

A: You can create global hooks to handle repeated useEffect in many components. For example like this:
export const useSocket = () => {
  const [data, setData] = useState();

  useEffect(() => {
    socket.on("received event", async () => {
      const res = await searchNotifications();
      setData(res);
    });

    return () => socket.off();
  });

  return data;
}

And in any component that needs to use socket:
import { useSocket } from 'yourJsFile';

const AnyComponent = props => {
   const data = useSocket();
}


text:
Q: Await/Async or SocketAsyncEventArgs? So I've allready written a tcp-server with SocketAsyncEventArgs and socket.***Async methods. But I do love the await/async way of writing code using the Stream.ReadAsync and Stream.WriteAsync methods.
Is there any difference performance/memory wise, or do I simply make a difference in syntax?

A: The advantages of using the socketasynceventargs is to reduce strain on the garbage collector and to keep the buffers of the sockets grouped to prevent out of memory exception.
By using a pool of SocketAsyncEventArgs, you can eliminate the need to create and collect the IAsyncResult for every call to read and write.
Secondly, each SocketAsyncEventArgs can be assigned a portion of a large byte[] block. This prevents memory fragmentation which helps reduce the memory footprint. Although this can technically also be done with the Begin/End calls, it is easier to permenantly assign each SocketAsyncEventArgs with its own buffer instead of assigning a block every time that a read or write is called with the Begin/End methods.
One last difference that can be important is that according to the MSDN Library, the Begin/End Send method may block while the socket buffer is full. The SocketAsyncEventArgs will not block, instead, only a certain amount of bytes will be written depending on the amount of space in the sockets buffer, the callback will specify the amount of bytes written.
The advantages are really not noticeable unless it is an edge case. Unless you run into either of the problems specified, I suggest that you choose what is most comfortable and maintainable for you.


text:
Q: Unable to check checkbox via Perl LWP::UserAgent How should I check a checkbox like this:
<INPUT name="test2%40mydomain.com_notmetoo" type="CHECKBOX" value="off" >

with Perl's LWP::UserAgent module?
This code doesn't do it (the output is as if it was submitted without the checkbox being checked - i.e. the webpage gets refreshed and the checkbox cleared).
#!/usr/bin/perl
use LWP::UserAgent;

$ua = new LWP::UserAgent;
$ua->cookie_jar({ file => "$ENV{HOME}/.mailmanrc" });

$res = $ua->post('http://mydomain.com/mailman/admin/test1_mydomain.com/members/list',
    Content_Type => 'form-data',
    Content => [
        'test2%40mydomain.com_notmetoo' => 'on',
        setmemberopts_btn => 'Submit Your Changes'
    ]
);
if ($res->is_success) {
    print $res->decoded_content;
    print "Changed user setting...I hope!\n";
}
else {
    die $res->status_line;
}

I'm not sure why the "@" is represented by "%40" in the element name (any ideas?), but I've also tried:
'test2\%40mydomain.com_notmetoo' => 'on',
and
'test2@mydomain.com_notmetoo' => 'on',
without success.
There seems to be no JavaScript on the website (i.e. it works fine in my browser with JavaScript disabled).  I just can't get it to work in Perl.
Thanks.
Terry.

Update #1: Here's the POSTDATA value from Firefox's 'Tamper Data' extension when I submit after checking Test2's notmetoo box:
POSTDATA =-----------------------------2921376274802
Content-Disposition: form-data; name="findmember"

-----------------------------2921376274802
Content-Disposition: form-data; name="test1%40mydomain.com_realname"

Test1
-----------------------------2921376274802
Content-Disposition: form-data; name="user"

test1%40mydomain.com
-----------------------------2921376274802
Content-Disposition: form-data; name="test1%40mydomain.com_hide"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test1%40mydomain.com_notmetoo"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test1%40mydomain.com_plain"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test1%40mydomain.com_language"

en
-----------------------------2921376274802
Content-Disposition: form-data; name="test2%40mydomain.com_realname"

Test2
-----------------------------2921376274802
Content-Disposition: form-data; name="user"

test2%40mydomain.com
-----------------------------2921376274802
Content-Disposition: form-data; name="test2%40mydomain.com_hide"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test2%40mydomain.com_notmetoo"

off
-----------------------------2921376274802
Content-Disposition: form-data; name="test2%40mydomain.com_plain"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test2%40mydomain.com_language"

en
-----------------------------2921376274802
Content-Disposition: form-data; name="test3%40mydomain.com_realname"

Test3
-----------------------------2921376274802
Content-Disposition: form-data; name="user"

test3%40mydomain.com
-----------------------------2921376274802
Content-Disposition: form-data; name="test3%40mydomain.com_hide"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test3%40mydomain.com_plain"

on
-----------------------------2921376274802
Content-Disposition: form-data; name="test3%40mydomain.com_language"

en
-----------------------------2921376274802
Content-Disposition: form-data; name="setmemberopts_btn"

Submit Your Changes
-----------------------------2921376274802
Content-Disposition: form-data; name="allmodbit_val"

0
-----------------------------2921376274802--

Does that help anyone to help me?

A: My understanding of checkboxes is that the value= specifies the value which the variable will have when the checkbox is checked. So your confusing value="off" actually means thay you need
'test2%40mydomain.com_notmetoo' => 'off'

To indicate that the box is checked.

A: In your case the checkbox will have value "off" when checked. This would be less confusing if value is something like value="checkbox1". In this case the value of the checkbox would be checkbox1 when checked.
Also, consider using WWW::Mechanize for basic web operations like this (without javascript), its much easier and intuitive, also WWW::Mechanize is a subclass of LWP::UserAgent so you could still use LWP's methods.


text:
Q: InvalidArgumentException in UrlGenerator.php line 605: i could not fix it. can you help me? The command used to route to that

return redirect()->action('GuardianAuth\LoginController@login')->withInput();

in LoginController
in in AuthenticatesUsers


text:
Q: Style html,body from web component (Angular 2) I'm working on a LoginComponent in Angular 2 that should "restyle" the html and body tags, so I can put in a background image specific for the login page.
But just adding a style for the html, body in my login.css doesn't seem to work.
Is there a way to override the style on the html, body from a component? Or any element for that matter.
I've tried things like:
:host(.btn) { ... }
:host(.btn:host) { ... }
.btn:host { ... }

to style an element from outside the Login component. But nothing seems to work.

A: I'm not sure if this is exactly what you're looking for but this won't leave you with a permanently changed body background-image.
Here is how I did it for something similar. If tou want to impact the body background image for just this page this may work. (I've not tested this fully but it seems to work on windows browsers.)
Inside your component you can just work directly through the DOM when the component gets constructed. When it gets destroyed you can undo the change.
export class SpecialBackground  {
  constructor(){
    document.body.style.backgroundImage = "url('path/to/your/image.jpg')";
    document.body.style.backgroundPosition = "center center";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundAttachment = "fixed";
    document.body.style.backgroundSize = "cover";
  }
  ngOnDestroy(){
    document.body.style.backgroundImage = "none";
  }
}

For your purposes you can use a different function (rather than the constructor) when you button is clicked and you should good to go.

A: I had same issue with margin-top , the way I fixed is
constructor(
    private _renderer: Renderer2,
) {
    this._renderer.removeStyle(document.body, 'margin-top');
}

This worked perfectly for me.

A: I use this approach in my component, loaded in router-outlet:
      ngOnInit() {
        // Change <body> styling
        document.body.classList.add('align-content-between');
      }

      ngOnDestroy() {
        // Change <body> styling
        document.body.classList.remove('align-content-between');
      }

A: The way I used it is
constructor() {
    document.body.className = "bg-gradient";
  }

ngOnDestroy(){
    document.body.className="";
  }

This will dynamically add and remove style from the body for a particular component.

A: You could try
body {
  /* body styles here */
}

but styles in components are not supposed to be applied to elements outside themselves.
Another way is to use body as selector in your main component and use host-binding to set/remove a CSS class on body to make CSS you added to your index.html match.
@Component({
  selector: "body",
  host: {
    "[class.some-class]":"someClass"
  },
})
export class AppComponent {
  constructor(private loginService: LoginService) {
    loginService.isLoggedInChanged.subscribe((value) => {
      this.someClass = value;
    });
  }
  someClass: bool = false;
}

when you set someclass to true (usind some binding to a service, the class gets added to the body.
If you don't want to add CSS globally you can also bind to a style attribute directly
@Component({
  selector: "body",
  host: {
    "[style.background-image]":"bodyBackgroundImage()"
  },
})
export class AppComponent {
  bool isLoggedIn = false;
  constructor(private loginService: LoginService) {
    loginService.isLoggedInChanged.subscribe((value) => {
      this.isLoggedIn = value;
    });
  }
  function bodyBackgroundImage() {
    return this.isLoggedIn ? 'url("gradient_bg.png")': 'none';
  }
}

update
DomAdapter is gone. Renderer2 should provide similar functionality.

A way to style <body> directly from the login component is to use the DomAdapter (see also https://github.com/angular/angular/issues/4942)
System.import('angular2/src/platform/browser/browser_adapter').then(function(browser_adapter) {
  browser_adapter.BrowserDomAdapter.makeCurrent();
})
...
_dom: DomAdapter = new BrowserDomAdapter();
_dom.setStyle(_dom.query('body'), 'padding', '50px');

A: Very simple try this
//Add Style
document.body.style.overflow = 'hidden'

// Remove style
document.body.style.removeProperty('overflow')

//Remove style on destroy
ngOnDestroy(): void {
  document.body.style.removeProperty('overflow')
}

A: As an additional update, when using Angular: 9.1.12, adding styling to the body tag can be accomplished by using the src/styles.css file.This is assuming the src/angular.json's projects' architect object's styles array has been set to src/styles.css.
The angular.json file should look similar to below when configuring a global style sheet such as: src/styles.css. There are more details located within the angular documentation as well: https://angular.io/guide/workspace-config#style-script-config
{
    "projects": {
        "app": {
            "architect": {
                "styles": ["src/styles.css"]
            }
        }
    }
}

A: You need to change the way your component serves css using ViewEncapsulation. By default it's set to Emulated and angular will

add an attribute containing surrogate id and pre-process the style rules

To change this behavior import ViewEncapsulation from 'angular2/core' and use it in component's metadata:
@Component({
  ...
  encapsulation: ViewEncapsulation.None,
  ...
})

A: I just edited the styles.scss file and it worked for me.

A: Better to add css file at root level and configure it in angular-cli.json OR add it in index.html . so you can write your reset and global styles and no need to worry about shadow dom and other concepts.

A: Put your styles into a css class/ classes and do something like this in your component:
constructor() {
    document.body.classList.add("mainMapPageBody");
  }

ngOnDestroy(){
    document.body.classList.remove("mainMapPageBody");
}

This prevents you from having to write out lots of adding and removing of styling in the constructor/ destructor, making for easier debugging as in other answers.

A: ::ng-deep{
    html, body{
        //something here
    }
}


text:
Q: How exactly do Hair Tonics work on RDR2? I've been playing Red Dead Redemption 2 for a while now. If I would guess, I'm halfway through Chapter 3.
My beard and hair are both on size 7.
For hair, this is the longest size the game provides, now for facial hair, I still have sizes 8, 9 and 10 to go for.
When I reached level 6, a prompt was shown stating that from now on my beard would only grow if I start to drink Hair Tonics.
I've been drinking Hair Tonics from the moment I got access to them on the beginning of Chapter 2, but to be honest, after dozens of hours I'm not sure how they work as the in-game description is poorly detailed.
I noticed that I can drink more than one Hair Tonic per day, but I can't tell if this really makes a difference. A quick search on Google says that this effect stacks as you sip more Hair Tonics, but I'm looking for confirmation as I couldn't confirm for myself from playing (I didn't pay too much attention to this game mechanic).
I have questions like:

*

*How long does the effect of a single Hair Tonic last?

*If more than one is taken, does the effect last longer or is just the growth rate that speeds up?

*How much is the rate growth increased for each Hair Tonic that I drink?

*Does the Hair Tonic effect rely solely on screen transitions (like sleeping, missions that advance the time to the moment they should begin, chapter transition and so on) or does it work when the player is free roaming and the time is passing by? Does it work on both situation then?

I think these questions cover most of the details involving Hair Tonics on this game.

A: You can find the Hair Growth section from the guide below:

Sorry for the poor quality.
Taken from the official strategy guide for Red Dead Redemption 2 (available on the RDR2 app)


text:
Q: Password visibility icon using fontawesome I have this login form:
<form class="form-signin" action="${postUrl ?: '/login/authenticate'}" method="POST" id="loginForm" autocomplete="off">

      Username
      <input type="text" class="form-control" name="${usernameParameter ?: 'username'}" id="username" autocapitalize="none"/>

      Password
      <input type="password" class="form-control" name="${passwordParameter ?: 'password'}" id="password"/>
       &#128065

         <input type="checkbox" class="form-check-input" name="${rememberMeParameter ?: 'remember-me'}" id="remember_me"
         <g:if test='${hasCookie}'>checked="checked"</g:if>
         /> Remember me

   <button id="submit" class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button>
</form>

Currently it using an eye emoji like this:

But I want to change it to font awesome fa-eye also currently when I click on reveal password it showing cross sign and I also want to change that to eye lash icon as well.
Right now the eye and the cross sign icon I use unicode to display it.
Here is my javascript code:
 document.addEventListener("DOMContentLoaded", function(event) {
        document.forms['loginForm'].elements['username'].focus();
    });
    function passwordDisplayToggle() {
        var toggleEl = document.getElementById("passwordToggler");
        var eyeIcon = '\u{1F33D}';
        var xIcon = '\u{2715}';
        var passEl = document.getElementById("password");
        if (passEl.type === "password") {
            toggleEl.innerHTML = xIcon;
            passEl.type = "text";
        } else {
            toggleEl.innerHTML = eyeIcon;
            passEl.type = "password";
        }
    }

Any idea how I can switch it to font-awesome fa-eye?
Many thanks

A: I have to replace it with this jquery code to make it work :
    function passwordDisplayToggle() {

        var passEl = document.getElementById("password");
        var passToggler=$('#passwordToggler');

        if (passEl.type === "password") {
            passEl.type = "text";
            passToggler.removeClass('fa-eye');
            passToggler.addClass('fa-eye-slash');
        } else {
            passToggler.removeClass('fa-eye-slash');
            passToggler.addClass('fa-eye');
            // passToggler.addClass('d-none');
            passEl.type = "password";
        }
    }


text:
Q: Failed packages list I am planning to write a script to get the list of upgrades available on Ubuntu server and upgrade them. I can get the list of upgrades with "apt-get -s upgrade".
But how to get a report on list of packages that failed during the above command. Any specific command or technique? I can't find any option in apt-get or other command.


text:
Q: How to find a record based on a full match of associations I am making an application in which tasks can be completed by users. The tasks have an association Requirements. The User has an association Qualifications
The two are connected via a shared QualificationCategory
A Task has many requirements and a User has many Qualifications.
A Requirement is structured like this:
Requirement
- ID
- qualification_category_id
- task_type_id
- points_required

A Qualification is structured like this:
Qualification:
- ID
- qualification_category_id
- user_id
- points

The problem is this:
For a user I need to find all tasks he is allowed to complete. So i want to select all tasks from the database whose task_type.requirements match exactly inside the user.qualifications
So for each task check if the requirements match on any of the users qualifications based on qualification_category and for each requirement check if the corresponding user qualification points are higher or equal to the points required.
Models
class Requirement < ApplicationRecord
  belongs_to :qualification_category
  belongs_to :task_type, inverse_of: :requirements
end

class Task < ApplicationRecord
  belongs_to :task_type
  belongs_to :data_sourceable, polymorphic: true, optional: true
  belongs_to :user_id, optional: true
  belongs_to :solution, class_name: 'Hypothesis', optional: true
  belongs_to :payment_period, optional: true

  has_many :worker_groups, through: :task_type
  has_many :requirements, through: :task_type
end

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :timeoutable, :confirmable, :lastseenable,
         :recoverable, :rememberable, :trackable, :validatable, :registerable

  has_and_belongs_to_many :roles
  has_and_belongs_to_many :worker_groups
  has_many :payment_periods
  has_many :qualifications, inverse_of: :user
  has_many :qualification_categories, through: :qualifications
end

class Qualification < ApplicationRecord
  belongs_to :qualification_category
  belongs_to :user, inverse_of: :qualifications
end

How do i write my MySQL query or ARel statement to accomplish this. The application will hold millions of tasks so doing this in ruby is not desirable.
db fiddle: https://www.db-fiddle.com/f/2jBx1gQhzqn1hYS5xD82n/0

A: To return all task that a specific user is qualified for (based on matching a single qualification) a MySQL query something like this:
SELECT t.id
  FROM task t
  JOIN task_type tt
    ON tt.id = t.task_type_id
  JOIN requirement r
    ON r.task_type_id = tt.id
  JOIN qualification q
    ON q.qualification_category_id = r.qualification_category_id
   AND q.points                   >= r.points_required
  JOIN user u
    ON u.id = q.user_id
 WHERE u.id = ?

This might return "duplicates"; so we could either add a GROUP BY clause, or change the join operations into EXISTS predicates.

To match only tasks where all of the requirements are satisfied by user qualification, we'd need something a little different:
SELECT t.id
  FROM task t
  JOIN task_type tt
    ON tt.id = t.task_type_id
 WHERE EXISTS
       ( SELECT 1
           FROM requirement r
           JOIN qualification q
             ON q.qualification_category_id = r.qualification_category_id
            AND q.points                   >= r.points_required
          WHERE r.task_type_id = tt.id
            AND q.user_id = ?                                 -- specific user
       )
   AND NOT EXISTS
       ( SELECT 1
           FROM requirement r
           LEFT
           JOIN qualification q
             ON q.qualification_category_id = r.qualification_category_id
            AND q.user_id = ?                                 -- specific user
          WHERE r.task_type_id = tt.id
            AND ( q.user_id IS NULL OR q.points < r.points_required )
       )

The EXISTS bit checks that the user has at least one qualification that meets a requirement.
The NOT EXISTS bit checks if there are any requirement for a task category  where a user does not have a matching qualification.

Thinking about this a little more, I think the EXISTS part could be omitted, we only need to check NOT EXISTS... are there any requirement which is not statisfied by a qualification.
SELECT t.id
  FROM task t
  JOIN task_type tt
    ON tt.id = t.task_type_id
 WHERE NOT EXISTS
       ( SELECT 1
           FROM requirement r
           LEFT
           JOIN qualification q
             ON q.qualification_category_id = r.qualification_category_id
            AND q.user_id = ?                                 -- specific user
          WHERE r.task_type_id = tt.id
            AND ( q.user_id IS NULL OR q.points < r.points_required )
       )

(This assumes that qualification.points and requirement.points_required are non null, so the inequality comparison will evaluate to TRUE.  If we have the possibility of NULL values, we will need to handle those appropriately.)

A: To add on to spencers answer, for those looking to incorporate this into their rails project via a scope and ARel.
scope :qualified_for, ->(user) {
    task_types = TaskType.arel_table
    requirements = Requirement.arel_table
    qualifications = Qualification.arel_table
    requirements_conditions = requirements[:task_type_id].eq(task_types[:id])
                                  .and(
                                      qualifications[:user_id].eq(nil).or(qualifications[:points].lt(requirements[:points_required]))
                                  )

    requirement_query = Requirement.select(1).joins("LEFT
               JOIN qualifications
                 ON qualifications.qualification_category_id = requirements.qualification_category_id
                AND qualifications.user_id = #{user.id}").where(requirements_conditions).exists.not

    joins(:task_type).where(requirement_query)
  }


text:
Q: ROR: NoMethodError: undefined method `[]' for nil:NilClass I have not idea on which file is having this issue.
bundle exec rake db:create --trace
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:90: warning: already initialized constant FileUtils::VERSION
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:92: warning: previous definition of VERSION was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1188: warning: already initialized constant FileUtils::Entry_::S_IF_DOOR
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1267: warning: previous definition of S_IF_DOOR was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1446: warning: already initialized constant FileUtils::Entry_::DIRECTORY_TERM
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1541: warning: previous definition of DIRECTORY_TERM was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1448: warning: already initialized constant FileUtils::Entry_::SYSCASE
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1543: warning: previous definition of SYSCASE was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1501: warning: already initialized constant FileUtils::OPT_TABLE
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1596: warning: previous definition of OPT_TABLE was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1555: warning: already initialized constant FileUtils::LOW_METHODS
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1650: warning: previous definition of LOW_METHODS was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1562: warning: already initialized constant FileUtils::METHODS
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1657: warning: previous definition of METHODS was here
WARNING: Nokogiri was built against LibXML version 2.9.4, but has dynamically loaded 2.8.0
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
rake aborted!
NoMethodError: Cannot load `Rails.application.database_configuration`:
undefined method `[]' for nil:NilClass
(erb):26:in `<main>'
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/erb.rb:876:in `eval'
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/erb.rb:876:in `result'
/usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/application/configuration.rb:172:in `database_configuration'
/usr/local/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0/lib/active_record/railtie.rb:39:in `block (3 levels) in <class:Railtie>'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `block in execute'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `each'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `execute'
/usr/local/lib/ruby/gems/2.5.0/gems/bugsnag-6.7.3/lib/bugsnag/integrations/rake.rb:18:in `execute_with_bugsnag'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:213:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:193:in `invoke_with_call_chain'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:237:in `block in invoke_prerequisites'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:235:in `each'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:235:in `invoke_prerequisites'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:212:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:193:in `invoke_with_call_chain'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:182:in `invoke'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:160:in `invoke_task'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `block (2 levels) in top_level'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `each'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `block in top_level'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:125:in `run_with_threads'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:110:in `top_level'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:83:in `block in run'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:186:in `standard_exception_handling'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:80:in `run'
/usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<top (required)>'
/usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:74:in `load'
/usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:74:in `kernel_load'
/usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:28:in `run'
/usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:424:in `exec'

    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
        /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor.rb:387:in `dispatch'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:27:in `dispatch'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/base.rb:466:in `start'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:18:in `start'
    /usr/local/bin/bundle:30:in `block in <main>'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/friendly_errors.rb:124:in `with_friendly_errors'
    /usr/local/bin/bundle:22:in `<main>'

    Caused by:
NoMethodError: undefined method `[]' for nil:NilClass
(erb):26:in `<main>'
    /usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/erb.rb:876:in `eval'
    /usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/erb.rb:876:in `result'
    /usr/local/lib/ruby/gems/2.5.0/gems/railties-5.2.0/lib/rails/application/configuration.rb:172:in `database_configuration'
    /usr/local/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0/lib/active_record/railtie.rb:39:in `block (3 levels) in <class:Railtie>'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `block in execute'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `each'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:271:in `execute'
    /usr/local/lib/ruby/gems/2.5.0/gems/bugsnag-6.7.3/lib/bugsnag/integrations/rake.rb:18:in `execute_with_bugsnag'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:213:in `block in invoke_with_call_chain'
    /usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:193:in `invoke_with_call_chain'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:237:in `block in invoke_prerequisites'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:235:in `each'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:235:in `invoke_prerequisites'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:212:in `block in invoke_with_call_chain'
    /usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:193:in `invoke_with_call_chain'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/task.rb:182:in `invoke'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:160:in `invoke_task'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `block (2 levels) in top_level'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `each'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:116:in `block in top_level'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:125:in `run_with_threads'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:110:in `top_level'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:83:in `block in run'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:186:in `standard_exception_handling'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/lib/rake/application.rb:80:in `run'
    /usr/local/lib/ruby/gems/2.5.0/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
    /usr/local/bin/rake:23:in `load'
    /usr/local/bin/rake:23:in `<top (required)>'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:74:in `load'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:74:in `kernel_load'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli/exec.rb:28:in `run'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:424:in `exec'
        /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor.rb:387:in `dispatch'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:27:in `dispatch'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/vendor/thor/lib/thor/base.rb:466:in `start'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/cli.rb:18:in `start'
    /usr/local/bin/bundle:30:in `block in <main>'
    /usr/local/lib/ruby/site_ruby/2.5.0/bundler/friendly_errors.rb:124:in `with_friendly_errors'
    /usr/local/bin/bundle:22:in `<main>'
    Tasks: TOP => db:create => db:load_config

Database.yml
PostgreSQL. Versions 7.4 and 8.x are supported.
#
# Install the pg driver:
#   gem install pg
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
development:
  adapter: postgresql
  encoding: unicode
  database: pcms_development
  host: localhost
  pool: 5
  username: root
  password:
  port: 3306

test:
  adapter: postgresql
  encoding: unicode
  database: pcms_test
  host: localhost
  pool: 5
  username: root
  password: # <%= Rails.application.secrets[:database][:password] %>

A: If your database.yml file looks like the same as you pasted, then please remove this
# <%= Rails.application.secrets[:database][:password] %>

from the test Env, keep the password blank as same as development,
Also comment the first line in the file
#PostgreSQL. Versions 7.4 and 8.x are supported.

Try this
development:
  adapter: postgresql
  encoding: unicode
  database: pcms_development
  host: localhost
  pool: 5
  username: root
  password:

test:
  adapter: postgresql
  encoding: unicode
  database: pcms_test
  host: localhost
  pool: 5
  username: root
  password:


text:
Q: d3.js force layout drag stops working after deleting a node I've seen this answer and this too, but they don't work.
My code is on Fiddle.
Two questions:
1. On clicking a node and pressing the delete button on the keyboard the node and corresponding links get deleted, but why am I not able to drag the remaining nodes afterward?
2. I tried attaching an image (using the path in the nodes array), but the image doesn't appear. The circles just disappear and no image appears (the path to the image is correct. In the same program I tried displaying the image at a corner of the screen and it worked).
The code:
<!DOCTYPE html>
<meta charset="utf-8">

A: There is one problem in the redraw function in your code.
linkLayer = linkLayer.data(links, function(d) {return d.id; })
           .exit()
           .remove();

Above line has no use in your code since you are assigning the same variable with links having the old data again.
linkLayer = theLayer.selectAll(".link").data(links, function(d) { return d.id; })
           .enter()
           .append("line")
           .attr("class", "link");

Same happens for nodes. Change your code as shown below.
//Creating links
linkLayer = theLayer.selectAll(".link").data(links, function(d) {
     return d.id;
});
linkLayer.enter().append("line").attr("class", "link");
linkLayer.exit().remove();

//Creating Nodes with image icons
var gNodes = nodeLayer.enter().append("g")
   .attr("class", "node")
   .on("dblclick", dblclick).style("fill", function(d, i) {
        return d3.rgb(i * 15, i * 15, i * 15);
   })
   .on("mouseup", mouseup)
   .on("mousemove", mousemove)
   .on("mousedown", mousedown)
   .call(dragElement)
   .classed("fixed", function(d) {
      d.fixed = true;
   });

gNodes.append("circle")
   .attr("r", 12);

gNodes.append("svg:image")
   .attr("class", "circle")
   .attr("xlink:href",function(d){ return d.icon })
   .attr("x", "-8px")
   .attr("y", "-8px")
   .attr("width", "16px")
   .attr("height", "16px");

nodeLayer.exit().remove();

For updating position of circles and images easily, I have grouped them using g elements. So you will need to update the position of g element using transform attribute instead of updating cx and cy attributes of circle. Now, tick function will look like this. Updated fiddle
function tick() {
  linkLayer.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

  nodeLayer.attr("transform", function(d) {return "translate("+d.x+","+d.y+")"; });
}


text:
Q: How to send strings to a WinForms application from another application using methods I have an EXE that I've created called logger which is a simple WinForms application. It has a richtextbox and that's pretty much it.
I then also have a suite of other applications. What I want to be able to do with these apps is to be able to get them to write output to the logger.exe I have full control over the code of all applications.
I understand I could do a process.start and specify arguments but I want these apps to be able to write to the richtextbox at will based on the methods being called within them.
I was hoping I could create an api in the logger.exe that would expose a method for appending the richtextbox.
Does anyone have any tips on how I might achieve this?
EDIT: This is what I have so far:
namespace ScreenLog
{
  [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]
  public partial class Logger : Form, IFromClientToServerMessages
  {
      public Logger()
      {
          InitializeComponent();
      }

      public void DisplayTextOnServerAsFromThisClient(string text)
      {
          LogConsole.AppendText(Environment.NewLine + text);
      }
  }
  [ServiceContract(SessionMode = SessionMode.Allowed)]
  public interface IFromClientToServerMessages
  {
      [OperationContract(IsOneWay = false)]
      void DisplayTextOnServerAsFromThisClient(string message);
  }
}

A: As you might have already guessed you would need any of IPC(Inter Process Communication) mechanism to send messages between different processes(Applications). WCF is one of the option, You could implement a simple WCF service module which uses net.pipe binding. This service can be hosted in managed application. In your case this service can be hosted in your logger application.
Note: If you want to host a WCF application in a managed application, Particular managed application(Logger) should have admin privilege.
Implementation of Logger Form
partial class declaration
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]
public partial class Logger: Form, IFromClientToServerMessages

Introduce Interface for communication
This interface should be added to a assembly which is accessible by both Logger application and any other application which sends message to logger.
[ServiceContract(SessionMode = SessionMode.Allowed)]
   public interface IFromClientToServerMessages
   {
       [OperationContract(IsOneWay = false)]
       void DisplayTextOnServerAsFromThisClient(string message);
   }

Implementing Interface
Add the following method implementation to your Logger form
public void DisplayTextOnServerAsFromThisClient(string text)
{
  //Add proper logic to set value to rich text box control.
  richtextbox = text;
}

Hosting the WCF service in logger application
Invoke HostTheNetPipeService() within the constructor of Logger Form
private void HostTheNetPipeService()
{
  serverHost = new ServiceHost(this);
  serverHost.AddServiceEndpoint((typeof(IFromClientToServerMessages)), new NetNamedPipeBinding(), "net.pipe://127.0.0.1/Server");
  serverHost.Open();
}

Call the service from other applications to send message/text
private void SendMessageToLogger()
{
    using (ChannelFactory<IFromClientToServerMessages> factory = new ChannelFactory<IFromClientToServerMessages>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/Server")))
    {
       IFromClientToServerMessages clientToServerChannel = factory.CreateChannel();
                try
                {
                    clientToServerChannel.DisplayTextOnServerAsFromThisClient("Message to be displayed");
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    CloseChannel((ICommunicationObject)clientToServerChannel);
                }
            }
        }

Closing the communication channel
private void CloseChannel(ICommunicationObject channel)
{
  try
  {
     channel.Close();
  }
  catch (Exception ex)
  {

  }
  finally
  {
     channel.Abort();
  }
}


text:
Q: Displaying only one record from json object , using jquery each Below is my code to display some notifications from json object.
$.each(valid_result, function(key, element){
      jQuery("#notifications_list").html(''+element.notification+'';
      console.log(key+' : '+element.notification);
     });

The above list will display here

But it is displaying only one record even though I have more records. Please suggest me where I am doing wrong. Any help would be greatly appreciated.

A: You are overwriting results. Please use append() method instead of html().
jQuery.each(valid_result, function(key, element){
  jQuery("#notifications_list").append(''+element.notification+'');
  console.log(key+' : '+element.notification);
});

If there are many elements in Your JSON object, then better approach is to append only once like so:
var list = '';

jQuery.each(valid_result, function(key, element){
   list += ''+element.notification+'';
});

jQuery("#notifications_list").html(list);

A: You are removing the old entry, you should append your code to it...
$.each(valid_result, function(key, element){
    $("#notifications_list").append(''+element.notification+'');
});


text:
Q: How to get VM series in azure? I have a VM (windows) in my azure.I tried seeing the tables in storage account but didn't get any help. I want to know the series of VM like A series,etc. Can i get this data from REST API also?

A: Yes, it is possible. You could use the following API.
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{vm}?api-version=2017-03-30

This is my test result in my lab.


text:
Q: Print undeclared in this scope whenever I compile my file, the compiler would tell me that my print is not declared in this scope. The problem is I can't touch my main file since it belongs to my school. Does anyone know what to do? Thanks!
Compiler error message:
main.cpp: In function 'void TestPush()':
main.cpp:10:5: error: 'Print' was not declared in this scope
 Print(a);
 ^~~~~

In my .h file:
template <typename T>
class vector
 {

private:
    T* v;
    int count;
    int capacity;
public:

vector(int capacity)
: v(new T[capacity]), count(0) {}

void Print(vector<T> s) {
    for(int i = 0; i < count; i++)
    {
    std::cout<<v[i]<<" ";
    }
    std::cout<< "(size=" << size << "," << "capacity=" << capacity << ")";

}
}

In my main file:
#include <iostream>
#include <cstdlib>              // atoi
#include "cs150_vector.h"

void TestPush(void)
{
std::cout << "\n********** TestPush **********\n";
cs150::vector<float> a;
std::cout << "Empty array:\n";
Print(a);

std::cout << "push_back 5 floats:\n";
for (float i = 0; i < 5; i++) {
    a.push_back(i);
    Print(a);
}

std::cout << "pop_back until empty:\n";
while (!a.empty()) {
    a.pop_back();
    Print(a);
}

}


text:
Q: how to enhance the image size of the screenshot captured for extent report? I am capturing the screenshot of the screen at failure and extent report displays it. When I click on the captured screenshot in the extent report, it's not the full screen. Its short by approximately 1 cm on all sides.
How to enhance it to make it full screen?

A: You can change the css style configuration in extent-config.xml.
Example below, changed the width of image.
<!-- custom styles -->
<styles>
    <![CDATA[
        .featherlight-image {   border: 1px solid #f6f7fa;   cursor: zoom-in;    width: 75px; }
    ]]>
</styles>

Check the css variables in your report and adjust the image how you want.

A: For Extent Report v4 you can use htmlReporter
public ExtentHtmlReporter htmlReporter;

@BeforeTest
public void setExtentReport() {
    String reportUrl = System.getProperty("user.dir") + "/test-output/ExtentReportVersion4.html";
    htmlReporter = new ExtentHtmlReporter(reportUrl);
    String css = ".r-img {width: 100%;}";
    htmlReporter.config().setCSS(css);
}


text:
Q: How do I set Chocolatey to install applications onto another drive? I've installed Chocolatey, but I would like it to install programs to another drive instead of C. C is only a small SSD, but I have other drives where I usually install programs to.
Any ideas?

A: It looks like Chocolatey has now created a ubiquitous switch:
Ubiquitous Install Directory Option (Licensed Editions Only)
I've not had chance to use this personally, but it looks like this would do the trick. If a little manual per application.

A: Adding to @antonio's answer I wanted to put my findings on other cases for setting the installation directory.
For fileType = 'exe' there seem to be two types of installers which you can tell apart with the given silentArgs (also in the chocolateyInstall.ps1).
So far I found /S as silentArgs and some longer stuff starting with /VERYSILENT /NORESTART (which seems to be an InnoSetup installer).

*

*/S: After testing I found this to be working (7zip as example):
choco install 7zip.install -y --ia "/D\=D:\Destination\" (Note: This also triggers debugging output. If you have a solution that doesn't, please tell me!)

*/VERYSILENT /NORESTART ...: According to the InnoSetup Installer CLI docs the switch should be /DIR=<path> and it seems to work like this: choco install pdftk --ia="/DIR=D:\\Tool\\PDFTk".

A lot of installers also don't use any of the above. VirtualBox for example expects certain installation arguments, the jdk8 package has params to set a directory that way etc. If you cannot match the silentArgs and fileType with the above you will have to do a little research.
For VirtualBox I ran the installer with /? and got a popup explaining the parameters that could be added.
For Mozilla Firefox I found a community post that explained what flags and switches were allowed for the installer. Unfortunately you have to resupply the ini file for updates every time making it a bit tedious.
Now if you primarily use chocolatey to easily update your applications automatically and install them without manually looking for download links and cluttering your download folder with .msi, .exe and .zip files, you can simply add the chocolatey flag --notsilent (or --not-silent) to have the installer run normally with all the options you could normally provide to the UI as well. In most cases they are then also used for updates.

A: The accepted answer hints at this option already, so I'm only posting for the sake of completeness:
Change the default Program Files directory with regedit
While SSDs have gotten bigger and cheaper in recent years, there are still some niche use cases where you want to keep a Windows install on a separate, smaller partition and software on a different, bigger partition.

*

*Press win + R and type regedit

*Locate this key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

*Change ProgramFilesDir and ProgramFilesDir (x64) from C:\ProgramFiles to [your drive]:\Program Files
Citing my sources: this answer but longer.
Important notes
Chocolatey will, in general, respect this — but there's a few caveats with that method that need to be mentioned:

*

*Some programs/installers don't respect ProgramFilesDir registry keys. For example, Audacity still installed to C: (despite — in my case, at least — ProgramFilesDir is F:\Program Files, but chocolatey made an assumption that it's installed to F: when making the shortcuts and start menu entries).

*This breaks NVIDIA GeForce Experience. There may also be other side effects, but I haven't found them yet.

*You need to change ProgramFilesDir registry keys before installing anything with chocolatey, otherwise some scripts, packages, or programs might be broken (for example, I had to reinstall the chocolateygui package)

Side note: this answer operates under assumption that "how do I set chocolatey to install applications onto another drive" means "how do I set chocolatey to install application to the same drive where I've installed most of my other software."

A: Chocolatey FOSS
For each application, you would need to know its command line switch used during installation to change its installation directory and pass it using --installArgs. See Install Command (choco install) and Overriding default install directory or other advanced install concepts.
Another way to ensure a different drive is to relocate your Program Files to a different drive. You may want to look that up; it is possible to do.
Chocolatey Licensed Versions
We've added the ubiquitous install switch! If you need to override the install directory and you don't want to do all of the work to determine what that switch is, you have the option to use one switch with Chocolatey - Ubiquitous Install Directory Option (Licensed Editions Only).
NOTE: We need to ensure the longevity of the Chocolatey community somehow, and that is to have a FOSSium (freemium) model. The Pro version is $8/month (annually $96), costs you less than eating out once a month, gets you some awesome features, and ensures that the community infrastructure continues to provide a great service and improve. While you are using a free service (the community repository, aka https://chocolatey.org/packages), it is not free to provide that service. So we select certain premium features to go into those versions to provide enough value to be worth the price.

A: I've found another simple trick - install choco as usual, and right after installation move the c:\programdata\chocolatey directory anywhere you like, and then update ChocolateyInstall environment variable and also update PATH environment variable so choco's \bin subfolder is found after moving it.
Of course, I don't know if it fine with any other packages, but I just installed 7zip and docker-machine with no problems, so seems to work.

A: Summarized and corrected solution (incl. convenience script)
For the free version you have to pass the directory as an addtional input argument:
choco install theapp -y --ia "folder switch"

The challenge is that the switch differs from installer to installer.

Proceeding to determine the installer

*

*Go to the chocolatey package repo and search for your app

*Scroll down to "List Files" and open tools\chocolateyInstall.ps1. If there is no such file go back to search and use the ".installer" version.

*Search for fileType = exe. Most of my tested apps had this extension. If it's the case search for silentArgs. If there is a:

*

*/S: use --ia "/D=C:\new\path.  Note: single backslashes, double backslashes didn't work for me. Also no backslash before the = sign, as suggested in other comments.

*/VERYSILENT: use --ia /DIR=C:\new\path. The verysilent switch belongs to the InnoSetup Installer.

*something else: search "app silent install" on google, determine the path switch and enter it accordingly: --ia "..."

*fileType = msi: use --ia INSTALLDIR="C:\new\path" (I did not test this)

Fallback solution
Do a non-silent installment and specify the path in the ui: choco install theapp --notsilent
Convenience script
I created a Powershell script which allows to install common apps (vlc, VS Code, python, git, Chrome...) with custom parameters, incl. folders:
https://github.com/vii33/ChocoVanillaPackage

Remarks to other comments
(I cannot comment directly because of my score, sorry)

*

*@geisterfurz007 Thank you for the manual.

*@quetzalcoatl This did not work for me since applications are not installed inside the chocolatey folder. Your solution moves the chocolatey binaries, the package installation is still done in the default folder.

A: You could move the Chocolatey directory to another location then create a hard symbolic link from the default location - see The Complete Guide to Creating Symbolic Links (AKA Symlinks) on Windows.
I.e. mklink /J C:/ProgramData/chocolatey D:/my/new/location
But be sure to create the usual backups, restore points, etc. before doing anything.

A: Use the ChocolateyToolsLocation environment variable.
The program itself stays where it's supposed to be, but all installations with choco are installed at D:\tools.
Or another env-var:
ChocolateyInstall:D:\ProgramData\chocolatey

Source:

*

*https://github.com/chocolatey/choco/blob/master/src/chocolatey.resources/helpers/functions/Get-ToolsLocation.ps1#L37

A: For an MSI package (which is most often the case in Windows) use:
choco install package-name  --% -ia INSTALLDIR="c:\intall\path"

To see whether the package is an MSI one, on the Chocolatey package page, under Files, look for chocolateyInstall.ps1 and then look for:
fileType = 'msi'

It was tested with Strawberry Perl.
Of course, you can always use the paid chocolate and benefit from the ubiquitous install switch.


text:
Q: I have one batch class which updates Account Name to true. But Not getting updated data in Test class inside System.assertEquals() public class CustomIterator
  implements Iterator<Account>{

  private List<Account> accs;
  private List<Contact> conts;
  private Integer currentIndex;

  public CustomIterator(List<Account> accs){
      this.accs = accs;
      this.currentIndex = 0;
  }

  public boolean hasNext(){
      return currentIndex < accs.size() - 1;
  }

  public Account next(){
      if(hasNext()) {
          currentIndex++;
          return accs[currentIndex];
      } else {
          throw new NoSuchElementException();
      }
  }
}

public class CustomIterable implements Iterable<Account> {
   public Iterator<Account> iterator(){
      List<Account> accs =
      [SELECT Id, Name, Rating
       FROM Account
       LIMIT 10 ];
      return new CustomIterator(accs);
   }
  }

global class BatchClass implements Database.Batchable<Account>{

   global Iterable<Account> start(Database.BatchableContext info){
       return new CustomIterable();
   }
   global void execute(Database.BatchableContext info, List<Account> scope){
       List<Account> accsToUpdate = new List<Account>();
       for(Account acc : scope){
           acc.Name = 'true';
           accsToUpdate.add(acc);
       }
       update accsToUpdate;
   }
   global void finish(Database.BatchableContext info){
       System.debug('Batch Done');
   }
}

@isTest
public class BatchClassTest {

    @testSetup
    public static void makeData(){
            Account acc=new Account(Name='Test Account');
            insert acc;
    }

    @isTest
    public static void batchTest(){
        BatchClass obj=new BatchClass();
        Test.startTest();
        Id jobId=Database.executeBatch(obj);
        Test.stopTest();
        Account accAfterUpdate=[Select id, Name From Account];
       System.assertEquals('true', accAfterUpdate.Name);

    }
}

Getting Below Error While Executing Test class.
//System.AssertException: Assertion Failed: Expected: true, Actual: Test Account

A: Your unit test found a bug. By writing more granular unit tests to evaluate each piece of functionality in your code, you might have been able to get more direct guidance to the source of the problem:
  public boolean hasNext(){
      return currentIndex < accs.size() - 1;
  }

The logic here is incorrect. Assume accs.size() is 1 (as it is in your test context). Your iterator will never return true to hasNext() and will therefore stop immediately.


text:
Q: How to Make Progress Bar In The Front Webview With Transparant Background? I want to make transparant background and showing in center layout. But i'm very confused when i'm used relative layout my apps crash after showing progress bar and didn't transparant background.
I'm using android studio to make a webview apps.
This is my code MainActivity
public class MainActivity extends AppCompatActivity {

    ProgressBar superProgressBar;
    WebView superWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        superProgressBar = findViewById(R.id.myProgressBar);
        superWebView = findViewById(R.id.mywebView);

        superProgressBar.setMax(100);

        superWebView.loadUrl("https://www.google.com");
        superWebView.getSettings().setJavaScriptEnabled(true);
        superWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                superProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                superProgressBar.setVisibility(View.GONE);
            }
        });
        superWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                superProgressBar.setProgress(newProgress);
            }
      }
}

This is my code layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.cokein.webviewtest.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal">

        <ProgressBar
            android:id="@+id/myProgressBar"
            style="?android:attr/progressBarStyle"
            android:layout_width="71dp"
            android:layout_height="70dp"
            android:layout_centerInParent="true"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:indeterminateDrawable="@drawable/pbc"
            android:progress="25"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>

    <WebView
        android:id="@+id/myWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


text:
Q: ticker of title news list suddenly disappears when i use foreach loop in asp.net mvc when i use ticker by foreache loop to list my title of news the ticker disappear
when i use only  li tag static title the ticker works Normally
the error

when i use  static li

Edit
partial View _breakingnews contains  the foreach

                @foreach (var item in Model.Take(3))
                {

@item.Title

                }

Home controller
public PartialViewResult _breakingnews()
    {
        var cat = db.breakingNews.ToList();
        return PartialView(cat);

    }

i call partial view in layout
        @Html.Action("_breakingnews", "Home")


text:
Q: How to optimize date transformation in Oracle SQL I have a date column CUR_DATE in NUMBER(10) (20210821) data type in DB and when I starting some executions with transforming I have a very tough issues with operation time.
for ex. I need to get data for the last 2 months from the current day, so I use transformation like this in my WHERE clause:
and trunc(to_date(CUR_DATE,'yyyymmdd'),'mm') >= add_months(trunc(sysdate,'mm'),-1)

and if I don't change date type of course it runs faster
and CUR_DATE >= 20220201

So maybe there will be solution which allows me execute data for last two months?

A: Do the opposite:
and cur_date >= to_number(to_char(add_months(trunc(sysdate, 'mm'), -1), 'yyyymmdd'))

if you must. Why? Because - I presume - there's an index on cur_date column. When you mess with it (apply various functions), index is no longer used. You could create a function-based index, though.
SQL> select to_number(to_char(add_months(trunc(sysdate, 'mm'), -1), 'yyyymmdd')) val from dual;

       VAL
----------
  20220201

SQL>

What you really should do is to store dates into DATE, not NUMBER datatype columns.