text:
Q: Graphviz and dot path Im trying to use schemaspy to generate a mssql db schema.
I have the following:
Schemaspy_5.0.0
Graphviz2-38
jtds-1.3.1 as mssql driver
SchemaspyGUI
after clic start the schema on schemaspy, this is the command schemaspGUI generates:
java -jar "C:\Esquema\schemaSpy_5.0.0.jar" -dp "C:\Esquema\jtds-1.3.1-dist\jtds-
1.3.1.jar" -t mssql-jtds -db database -all  -host LOCAL.LOCALHOST -port 1433 -u genaro
-connprops "C:\Esquema\properties\mssql-jtds.properties" -o "C:\Esquema\database" -hq

It displays this message:
Failed to query Graphviz version information
with: dot -V
java.io.IOException: Cannot run program "dot": CreateProcess error=2, El sistema no
puede encontrar el archivo especificado

In the graphviz download page says that you must add dot to your path, but after a long search i cant figure out how to add it.

A: Since my PATH is already polluted enough, I tried hacking the SchemaSpyGUI text boxes to inject the -gv parameter into the schemaspy command line.
On the Output Options tab, in the Output Directory textbox, end the output path with a " and a space, then -gv "C:\Path\To\Graphviz\NotTheBinFolder
and no closing ", because this is added by SchemaSpyGUI
Like so:

redpajama_set_name: RedPajamaStackExchange


text:
Q: What iOS capability / entitlement is "com.apple.OMC"? com.apple.OMC: what is it? Why is it enabled and how do I disable it?

A: Apple Pay. Found it in this project and it's the only thing enabled on the Capabilites page in Xcode: https://github.com/stripe/stripe-ios/blob/master/Example/Stripe%20iOS%20Example%20%28Simple%29.xcodeproj/project.pbxproj


text:
Q: Command Prompt/Batch - rename multiple files with sequential numbering of same number of digits I always have taken many photos that need to rename that with desired prefix and number, say I have the following photos

IMG_1933.JPG
  IMG_1934.JPG
  IMG_1935.JPG
  IMG_1936.JPG
  IMG_1937.JPG

Then I want to run a batch file to change them to:

Goodlooking 0098.jpg
  Goodlooking 0099.jpg
  Goodlooking 0100.jpg
  Goodlooking 0101.jpg
  Goodlooking 0102.jpg

I have read some answers here but cannot keep the leading zero while keeping the same number of digits when the number goes from 99 to 100, or 999 to 1000. Like the following:
@echo off
pushd %~dp0
setlocal EnableDelayedExpansion

set filename=Goodlooking 00
set Num=98
for /r %%i in (*.jpg) do (
    ren "%%i" "%filename%!Num!.jpg"
    set /a Num+=1
)

The above codes can do most of the works, but cannot keep the number of digits.
That means I need to setup two variables, 1) the prefix; 2) the starting number, then keep the same number of digits.
Thank you very much.

A: How about this:
@echo off
pushd %~dp0
setlocal EnableDelayedExpansion

set "filename=Goodlooking"

set Num=10098
for /r %%i in (*.jpg) do (
    ren "%%~i" "%filename% !Num:~1!%%~xi"
    set /a Num+=1
)

We need to consider octal values, therefore we add 1 to the num then simply get rid of it when renaming.
to understand the problem with octal values you can open cmd.exe and run this to see the result:
set /a num=0098


text:
Q: why is createServer() considered not a function? I installed express globally and npm installed my express app, yet neither the intellisence or the app is working ( I am using visual studio code on mac OS Yosemite).
here is a sample code:
/// <reference path="typings/node/node.d.ts" />
/// <reference path="typings/express/express.d.ts" />

var express = require('express');
var app = express.createServer();
app.get('/', function (req, res) {
    res.send('hi');
})

app.listen(8000);

and here are the errors I am getting:
Abeds-MacBook-Pro:myNode AZ$ node twitter.js
/Users/AZ/Desktop/myNode/twitter.js:5
var app = express.createServer();
                  ^

TypeError: express.createServer is not a function
    at Object.<anonymous> (/Users/AZ/Desktop/myNode/twitter.js:5:19)
    at Module._compile (module.js:397:26)
    at Object.Module._extensions..js (module.js:404:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:429:10)
    at startup (node.js:139:18)
    at node.js:999:3

I researched a bit and found that createServer() has been deprecated. I read that I need to change the version somewhere in my application.

Note: I did another application using purely Node.js, and createServer() did work without any error along with the intellisence.
EDIT:
in my other application I used require('net') instead.
I modified my code to the following:
var express = require('express')
  , http = require('http');

    var app = express();
    var server = http.createServer(app);
    console.log('Listening on port 8000')
    app.get('/', function (req, res) {
        res.send('hi');
    })

    app.listen(8000)

The problem I have now is that res.send('hi'); has not been reached, aka, I cannot send to the client.
EDIT 2:
I tried the following code provided in one of the answers:
const express = require('express');
const http = require('http');

const app = express();
const server = http.createServer(app).listen(8080, function(err) {
  if (err) {
    console.log(err);
  } else {
    const host = server.address().address;
    const port = server.address().port;
    console.log(`Server listening on ${host}:${port}`);
  }
});
app.get('/', function (req, res) {
    res.send('hi');
})

res.send('hi'); still does not work, neither does it provide an error.

A: createServer is a function of http so it should be:
const express = require('express');
const http = require('http');

const app = express();
app.get('/', function (req, res) {
  res.send('hi');
});

const server = http.createServer(app).listen(8080, function(err) {
  if (err) {
    console.log(err);
  } else {
    const host = server.address().address;
    const port = server.address().port;
    console.log(`Server listening on ${host}:${port}`);
  }
});

P.S. Installing express globally is a bad idea


text:
Q: Assign values to a list of lists I need to assign a predefined dimension to a list of lists. This is because the code within the for loop is using references to an 'existing' array of such dimension and it would throw an 'index out of range' error if the list is not preloaded before entering the loop.
The following slice of code intended to do such task does not produce the result I would expect.
a, b = 2, 3

matrix = [[[None]*2]*a]*b

for i in range(b):
    for j in range(a):
        print(i, j)
        matrix[i][j] = [i, j]
print(matrix)

I am expecting the elements of the two-dimension list of lists to be a two-elements list. Such as the print statement shows in the following output:
0 0
0 1
1 0
1 1
2 0
2 1
[[[2, 0], [2, 1]], [[2, 0], [2, 1]], [[2, 0], [2, 1]]]

The list of lists should contain the pairs printed.

A: The correct way to pre-dimension the list of lists is as follows:
a, b = 2, 3

matrix = [[[None for _ in range(2)]
                 for _ in range(a)]
                 for _ in range(b)]

for i in range(b):
    for j in range(a):
        print(i, j)
        matrix[i][j] = [i, j]
print(matrix)

So the output is as expected:
0 0
0 1
1 0
1 1
2 0
2 1
[[[0, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 0], [2, 1]]]


text:
Q: Conan - changing the recipe of existing packages and updating the package channel I would like to update the channel of some existing conan packages in my local conan/artifactory server without having to recompile/rebuild them.
Some background: we have some packages that were originally downloaded from a non-local server. These packages were uploaded to our local server, so we'll not be dependent to a connection to a 3rd party server. We set the remotes.json file to prefer the local server over the global server, however, for some reason - in some stations packages are referenced to the global server. This, and the fact that some packages were changed in the global server and creates new conflicts & issues, we decided to change the channel of our local packages. This will also help to make sure that no-one outside of our project changes the packages content (also happened few times when someone update the updated package from the server)
What we want is: To have the same conan packages but at a different channel: for example - instead of libjpeg/9c@bincrafters/stable we want the very same package but libjpeg/9c@local_channel/stable. We also need to change the package requirements file also to be dependent on our local channel and not on other channels. I have searched a method to do so and only found this: https://github.com/conan-io/conan/issues/3283. One of the answers suggested that it was impossible, as it was also require a change with the package version - changing the package version require a rebuild. I don't want to change the version of the package, only the channel. Is that possible to do so without having to rebuild the package?

A:
I would like to update the channel of some existing conan packages in my local conan/artifactory server without having to recompile/rebuild them.

Conan copy is what you are looking for:
conan copy libjpeg/9c@bincrafters/stable local_channel/stable --all
conan upload libjpeg/9c@local_channel/stable --all -r my_remote

Or, you can update directly in your Artifactory instance, by moving/copying Conan packages (artifacts). However, it will not update your dependencies and your local cache.

I have searched a method to do so and only found this: https://github.com/conan-io/conan/issues/3283.

That question is from 2018. Many new features were introduced since then, including copying artifact on Artifactory. Anyway, https://github.com/conan-io/conan/issues is the best place for asking anything, Conan team will answer there.

I don't want to change the version of the package, only the channel. Is that possible to do so without having to rebuild the package?

Conan copy command copies everything, including packages dependencies, so you don't need to rebuild. However, you have to update their dependencies too and it won't work. As your packages are cached, you will need to update their dependencies references too, not only updating a recipe and magically Conan solves it. There are few options:

*

*Rebuild all. It takes time, but at least you will have packages built with same environment.

*Use alias to lie about package reference. You should remove the original packages, and create an alias, from new names to old names:

    conan remove libjpeg/9c@bincrafters/stable -f
    conan alias libjpeg/9c@local_channel/stable libjpeg/9c@bincrafters/stable

So you don't need to update your packages and rebuild them, but as you can see it's an ugly workaround.


text:
Q: Macro for setting print area not working I would like to create a simple macro which will set a print area from selected area but i still get an error "Subscript out of range"
Here's the code
Worksheets("Zeszyt11").Activate ActiveSheet("Arkusz1").PageSetup.PrintArea = _ActiveCell.CurrentRegion.Address

EDIT
Ok,i've got one more question: I would like to make a print area only out of cells i've selected,now it takes every with any text..How to fix it ?

A: You can't say ActiveSheet("SheetName") try
Worksheets("Arkusz1").PageSetup.PrintArea = ActiveCell.CurrentRegion.Address


text:
Q: C++: Is there a difference between calling an operator and calling it's implementation I have a class in which I overloaded the == operator with memcmp() on a specific member. Due to a bad copy done in the code (memcpy called with bigger size than it should) I had a segfault when invoking the == operator.
I understand that UB is mysterious and obviously undefined, but still there is something I noticed that intrigues me.
While debugging, I swapped the == call with it's implementation (i.e. the a==b was swapped with memcmp(a.member_x, b.member_x, SIZE)) and no segfault!
So, is there a difference between using the operator itself and replacing it with the implementation or is this just the UB?
To clarify: Yes, this code includes UB. It's bad and it's results are undefined. What I want to know is: does something different happens when calling an operator or calling it's body? The UB just made me think that a difference might exist (and obviously was fixed)

A: Undefined Behavior means that "anything can happen". "Anything" includes "working just as intended". It can mean that you can get different behavior without changing anything, and it can mean that you get the same behavior even though you changed something.
In the past, warnings about relying on undefined behavior have often included the proverbial "launching of the nuclear missiles".
However, with modern aggressively optimizing compilers, the behavior can be much more subtle. In the past, undefined behavior would usually lead to "whatever happens happens". E.g. in your example, you would either read "junk" in memory if you are allowed to access it, or segfault if you aren't. But the operation (i.e. "compare these two chunks of memory") would still happen somehow.
This is no longer "guaranteed" (not that there ever were any guarantees when it comes to UB) with modern aggressively optimizing compilers. The compiler will no longer just do nonsense things.
With modern optimizing compilers, the compiler must often decide (or prove) that a certain optimization is safe, i.e. that it doesn't alter observable specified behavior. And since UB means "anything can happen" it means that the part of the optimizer that proves that certain optimizations are safe can "assume anything it wants". In essence, it can assume that all optimizations are safe, and then proceed however it wants to provide the most aggressive optimization possible.
As a result, UB is much less predictable and much less obvious than it once was. For example, UB in one place of the program can lead to the optimizer optimizing something in a way that it changes the behavior of something else in a different part of the program that is connected to this piece of code somehow (e.g. it calls it, or both manipulate the same state).
Let's say we have two threads manipulating shared mutable state. One of the two threads exhibits UB. Then, the optimizer can decide that that thread doesn't manipulate the state ("anything can happen", remember?) and since it can now prove that the state will only ever be accessed by one thread, it can optimize away all locks! [Note: I have no idea whether any compiler in reality does this, but it would be allowed to!]
Here's another example to demonstrate that "anything can happen" really, truly does mean "anything": let's assume there are two possible optimizations that could be applied in some code higher up the stack which calls your operator==. One optimization is only valid if the compiler can prove that operator== will always be true. The other optimization is only valid if the compiler can prove that it will always be false. This means, of course, that neither optimization can be applied since in general, your operator== could return either true or false.
But! We have UB. So, the compiler can decide to just assume that it will always be true and apply optimization #1. Or it could decide that it will always be false and apply optimization #2. Okay, fair enough. However, it can also decide to apply both optimizations! Remember: "anything can happen". Not just "anything that makes sense according to the logical framework of the C++ spec" but "anything" period. If the compiler needs something to be true and false at the same time, it is free to assume so in the presence of UB.
You can think of a modern optimizing compiler as trying to prove theorems about your code, and then applying optimizations based on those proofs. And UB allows it to prove any and all theorems.


text:
Q: Stop 'extends WP_Widget' displaying the (backend) form, frontend? I am in the middle of transferring a website from one server to another.
It works as it should on the old server but on the new server is broken.
The widget is pretty basic, you fill in some options (text boxes and the like) via appearance -> widget and it displays the outcome frontend. Since the switch, it is showing the form (text boxes etc) underneath the frontend outcome, and has removed the textboxes etc from the backend completely. All I'm left with is a widget block with the message:
"There are no options for this widget."
Here's my code:
if ( ! class_exists( 'widget_block' ) ) {
class widget_block extends WP_Widget {

  public function __construct() {

    parent::__construct(
        'widget_block',
        __( 'Widget Block', 'dev.everythingdifferent.co.uk' ),
        array(
            'classname'   => 'widget_block',
            'description' => __( 'A basic widget block that allows for text only, text and image or text and video widget blocks.', 'everythingdifferent.co.uk' )
            )
    );

    load_plugin_textdomain( 'dev.everythingdifferent.co.uk', false, basename( dirname( __FILE__ ) ) . '/languages' );

}

/**
 * Front-end display of widget.
 *
 * @see WP_Widget::widget()
 *
 * @param array $args     Widget arguments.
 * @param array $instance Saved values from database.
 */
public function widget( $args, $instance ) {

    extract( $args );

    $title      = apply_filters( 'widget_title', $instance['title'] );
    $message    = $instance['message'];
    $thumbnail    = $instance['thumbnail'];
    $postid    = $instance['postid'];
    $videourl    = $instance['videourl'];
    $videoimage = $instance[ 'videoimage' ] ? 'true' : 'false';
    $autoplay = $instance[ 'autoplay' ] ? '1' : '0';

    echo $before_widget;

    ?>

        <?php if ( $title ) {echo $before_title . '' . $title . $after_title . ''; } ?>
        <?php
        $url = $videourl;
        // parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );

        // $videourl = $my_array_of_vars['v'];
        $videourl = parse_yturl($videourl);
        $videourl = 'https://www.youtube.com/embed/' . trim($videourl) . '?autoplay='.$autoplay;

        if (empty($url)) {
            $videourl = get_permalink( $postid );
            $classes ='';
        } else {
            $classes ='overlay-video homevid';
            // echo 'here'. $url;
        };
        ?>
            <a rel="homevid" class="<?php echo $classes; ?> playbutton clearfix media" title="<?php echo $title;?>" href="<?php echo $videourl; ?>" style="display:block;">

                <?php
                    if( $videoimage == 'true' ) {
                        // echo 'true';
                        // If the post has a feature image, show it
                        if( has_post_thumbnail( $postid ) ) {
                            echo get_the_post_thumbnail( $postid, 'video' );
                        // Else if the post has a mime type that starts with "image/" then show the image directly.
                        }
                    } else {
                        // echo 'false';
                    }
                ?>
                <?php if (empty($url)) {

                } else {
                    // echo 'here'. $url;
                    echo '';
                };
                ?>

<?php echo nl2br($message);?>

    <?
     echo $after_widget;
}

/**
  * Sanitize widget form values as they are saved.
  *
  * @see WP_Widget::update()
  *
  * @param array $new_instance Values just sent to be saved.
  * @param array $old_instance Previously saved values from database.
  *
  * @return array Updated safe values to be saved.
  */
public function update( $new_instance, $old_instance ) {

    $instance = $old_instance;

    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['message'] = strip_tags( $new_instance['message'] );
    $instance['thumbnail'] = strip_tags( $new_instance['thumbnail'] );
    $instance['postid'] = strip_tags( $new_instance['postid'] );
    $instance['videourl'] = strip_tags( $new_instance['videourl'] );
    $instance[ 'videoimage' ] = $new_instance[ 'videoimage' ];
    $instance[ 'autoplay' ] = $new_instance[ 'autoplay' ];

    return $instance;

}

/**
  * Back-end widget form.
  *
  * @see WP_Widget::form()
  *
  * @param array $instance Previously saved values from database.
  */
public function form( $instance ) {

    $title      = esc_attr( $instance['title'] );
    $message    = esc_attr( $instance['message'] );
    $thumbnail    = esc_attr( $instance['thumbnail'] );
    $postid    = esc_attr( $instance['postid'] );
    $videourl    = esc_attr( $instance['videourl'] );
    $videoimage    = esc_attr( $instance['videoimage'] );
    $autoplay    = esc_attr( $instance['autoplay'] );

    ?>

        <input class="checkbox" type="checkbox" <?php checked( $instance[ 'videoimage' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'videoimage' ); ?>" name="<?php echo $this->get_field_name( 'videoimage' ); ?>" />
        <label for="<?php echo $this->get_field_id( 'videoimage' ); ?>">Video and/or Image

        <label for="<?php echo $this->get_field_id('postid'); ?>"><?php _e('Post ID (How do I find this?):'); ?>
        <input class="widefat" id="<?php echo $this->get_field_id('postid'); ?>" name="<?php echo $this->get_field_name('postid'); ?>" type="text" value="<?php echo $postid; ?>" />

        <label for="<?php echo $this->get_field_id('postid'); ?>"><?php _e('YouTube url:'); ?>
        <input class="widefat" id="<?php echo $this->get_field_id('videourl'); ?>" name="<?php echo $this->get_field_name('videourl'); ?>" type="text" value="<?php echo $videourl; ?>" />

        <input class="checkbox" type="checkbox" <?php checked( $instance[ 'autoplay' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'autoplay' ); ?>" name="<?php echo $this->get_field_name( 'autoplay' ); ?>" />
        <label for="<?php echo $this->get_field_id( 'autoplay' ); ?>">Autoplay video

        <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?>
        <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />

        <label for="<?php echo $this->get_field_id('message'); ?>"><?php _e('Message'); ?>
        <textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('message'); ?>" name="<?php echo $this->get_field_name('message'); ?>"><?php echo $message; ?></textarea>

    <?php
    }

  }
}


text:
Q: Transforming Object Array to Object of Arrays with keys My Current Structure:
input:
[
   {A:A1, B:B1, C:C1, D:D1, E:E1, F:F1, G:G1, H:H1},
   {A:A2, B:B2, C:C2, D:D2, E:E2, F:F2, G:G2, H:H2},
   {A:A3, B:B3, C:C3, D:D3, E:E3, F:F3, G:G3, H:H3}
   ...
]

My Goal:
output
[
   {"A":[A1, A2, A3 ...]},
   {"B":[B1, B2, B3 ...]},
   {"C":[C1, C2, C3 ...]},
   {"D":[D1, D2, D3 ...]},
   {"E":[E1, E2, E3 ...]},
   {"F":[F1, F2, F3 ...]},
   {"G":[G1, G2, G3 ...]},
   {"H":[H1, H2, H3 ...]}
]

Where "A", "B", "C"... are the literal keys from the original objects, and they are now keys in an object to an array of all values of their type. This is usually simple except for the fact that I need to maintain the keys throughout
This is what I've tried so far but I'm not sure if my loop structure is correct.
def ArrayList invertReponse(ArrayList input){

    def output = new ArrayList()

    for(i=0;i<input[0].size();i++){

        def tempObj = {}
        def j=0
        input[0].each{ key, value ->
            tempObj[[input][0][i]][j] = value
            j++
        }
        output.push(tempObj)
    }
    return output
}

A: Depending on the assumptions you can make about the input, you might want to start with something like this:
def input = [[A:'A1', B:'B1', C:'C1'],
             [A:'A2', B:'B2', C:'C2'],
             [A:'A3', B:'B3', C:'C3']]

def result = input.inject([:]) { map1, map2 ->
    (map1.keySet() + map2.keySet())
        .inject([:]) {m, k -> m[k] = (map1[k] ?: []) + (map2[k] ?: []); m}
}

result will end up being [A:[A1, A2, A3], B:[B1, B2, B3], C:[C1, C2, C3]].
I hope that helps.
EDIT:
After re-reading the question I see now that what you really want as a result is a List that contains a bunch of Map that each have just 1 key in them.  This may be closer to what you want...
def input = [[A:'A1', B:'B1', C:'C1'],
             [A:'A2', B:'B2', C:'C2'],
             [A:'A3', B:'B3', C:'C3']]

def result = []
input.inject([:]) { map1, map2 ->
    (map1.keySet() + map2.keySet())
        .inject([:]) {m, k -> m[k] = (map1[k] ?: []) + (map2[k] ?: []); m}
}.each { k, v ->
    result << [(k):v]
}

With that, result will be [[A:[A1, A2, A3]], [B:[B1, B2, B3]], [C:[C1, C2, C3]]].

A: Another way would be to leverage the power of higher order functions as:
def list = [
   [A:'A1', B:'B1', C:'C1', D:'D1', E:'E1', F:'F1', G:'G1', H:'H1'],
   [A:'A2', B:'B2', C:'C2', D:'D2', E:'E2', F:'F2', G:'G2', H:'H2'],
   [A:'A3', B:'B3', C:'C3', D:'D3', E:'E3', F:'F3', G:'G3', H:'H3']
]

// Flexibility on merge condition by provding a Closure
Map mergeOn(Map one, Map two, Closure closure) {
  two.inject([:] << one) { acc, key, val ->
    key in acc.keySet() ? acc[key] = closure(acc[key], val) : acc << [(key): val]
    acc
  }
}

assert list.inject { acc, item ->
  mergeOn(acc, item) { a, b ->
    a instanceof List ? a << b : [a, b]
  }
}.collect { k, v -> [(k) : v] } == [
   [A: ['A1', 'A2', 'A3']],
   [B: ['B1', 'B2', 'B3']],
   [C: ['C1', 'C2', 'C3']],
   [D: ['D1', 'D2', 'D3']],
   [E: ['E1', 'E2', 'E3']],
   [F: ['F1', 'F2', 'F3']],
   [G: ['G1', 'G2', 'G3']],
   [H: ['H1', 'H2', 'H3']]
]


text:
Q: Quick way to convert image 3 channels depth to 1 channel in Python? I'm working on fer2013 dataset, as you can see in the code the output got 48, 48, 3) which is 3 channels dept, that can't be used in Conv2D layer. I want it's just 1 channel dept - ( 48, 48, 1). so is there anyway to convert the x_train and x_test to 1 channel depth (grayscale channel)?
the output should be :(28709, 48, 48, 1) (3589, 48, 48, 1)
instead of (28709, 48, 48, 3) (3589, 48, 48, 3)
Link to the dataset : https://drive.google.com/file/d/1HH8gqzFOBavHxHbKbwjozu2QzlPlo6RW/view?usp=sharing
Thank you.!
import os
import cv2

def prepare_Data(path="Facial_expression/fer2013",
             image_shape = (48, 48)):

TRAINING_DATA_PATH = os.path.join(path, 'Training')
TESTING_DATA_PATH = os.path.join(path, 'PrivateTest')

x_train = [] # is the training data set
y_train = [] # is the set of labels to all the data in x_train
x_test = []
y_test = []
label_id = 0

num_classes = len(os.listdir(TRAINING_DATA_PATH)) # get number of classes 7
for label in os.listdir(TRAINING_DATA_PATH): # get label in training path

    # Read training data
    for img_file in os.listdir(os.path.join(TRAINING_DATA_PATH, label)):
        img = cv2.imread(os.path.join(TRAINING_DATA_PATH, label, img_file)) # read all image in training path
        img = cv2.resize(img, image_shape) # resize all image with size = 48 x 48
        x_train.append(img) # append all training image in x_train

        y = np.zeros(num_classes) # create one hot vector with dimension of 7
        # print(y)
        y[label_id] = 1
        y_train.append(y)
    # Read testing data
    for img_file in os.listdir(os.path.join(TESTING_DATA_PATH, label)):
        img = cv2.imread(os.path.join(TESTING_DATA_PATH, label, img_file))
        img = cv2.resize(img, image_shape)

        x_test.append(img)
        y = np.zeros(num_classes)
        y[label_id] = 1
        y_test.append(y)
    label_id += 1

return np.array(x_train), np.array(y_train), np.array(x_test), np.array(y_test)

x_train, y_train,x_test, y_test = prepare_Data()

print("Number of images in Training set:", len(x_train))
print("Number of images in Test set:", len(x_test))
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
'Output'
Number of images in Training set: 28709
Number of images in Test set: 3589
(28709, 48, 48, 3)
(3589, 48, 48, 3)
(28709, 7)
(3589, 7)

A: After a day of researching I found that I need to reshape 28709 images into shape (48,48,1) but current shape of image is (48,48,3) which is 3 channels dept. First I need to convert all image in grayscale by  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) then use the numpy.reshape to reshape all image into 1 channel dept.

TRAINING_DATA_PATH = os.path.join(path, 'Training')
TESTING_DATA_PATH = os.path.join(path, 'PrivateTest')

x_train = []
y_train = []
x_test = []
y_test = []

label_id = 0

num_classes = len(os.listdir(TRAINING_DATA_PATH))
for label in os.listdir(TRAINING_DATA_PATH):

    # Read training data
    for img_file in os.listdir(os.path.join(TRAINING_DATA_PATH, label)):
        img = cv2.imread(os.path.join(TRAINING_DATA_PATH, label, img_file))
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # ADD THIS
        img = cv2.resize(gray, image_shape)

        x_train.append(img)
        y = np.zeros(num_classes)
        y[label_id] = 1
        y_train.append(y)
    # Read testing data
    for img_file in os.listdir(os.path.join(TESTING_DATA_PATH, label)):
        img = cv2.imread(os.path.join(TESTING_DATA_PATH, label, img_file))
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # ADD THIS
        img = cv2.resize(gray, image_shape)
        x_test.append(img)

        y = np.zeros(num_classes)
        y[label_id] = 1
        y_test.append(y)
    label_id += 1
x_train = np.array(x_train) # ADD THIS
x_train = x_train.reshape(x_train.shape[0],48,48, 1) # ADD THIS

x_test = np.array(x_test) # ADD THIS
x_test = x_test.reshape(x_test.shape[0], 48, 48,1) # ADD THIS

return np.array(x_train), np.array(y_train), np.array(x_test), np.array(y_test)

Number of images in Training set: 28709
Number of images in Test set: 3589
(28709, 48, 48, 1)
(3589, 48, 48, 1)
(28709, 7)
(3589, 7)


text:
Q: How to check if an hash is "completely" included in another hash? I am using Ruby on Rails 3.1.0 and I would like to check if an hash is "completely" included in another hash and return a boolean value.
Say I have those hashes:
hash1 = {
  :key1 => 'value1',
  :key2 => 'value2',
  :key3 => 'value3'
}

hash2 = {
  :key1 => 'value1',
  :key2 => 'value2',
  :key3 => 'value3',
  :key4 => 'value4',
  :key5 => 'value5',
  ...
}

I would like to check if the hash1 is included in the hash2 even if in the hash2 there are more values than hash1 (in the above case the response that I am looking for should be true)? Is it possible to do that by using "one only code line"\"a Ruby method"?

A: The easiest way I can think of would be:
hash2.values_at(*hash1.keys) == hash1.values

A: the more elegant way is to check the equality when one hash merge another.
e.g. rewrite Hash include? instance method for this.
class Hash
  def include?(other)
    self.merge(other) == self
  end
end

{:a => 1, :b => 2, :c => 3}.include? :a => 1, :b => 2 # => true

A: That will be enough
(hash1.to_a - hash2.to_a).empty?

A: There is a way:
hash_2 >= hash_1

Alternatively:
hash_1 <= hash_2

More info in this post: https://olivierlacan.com/posts/proposal-for-a-better-ruby-hash-include/

A: The most efficient and elegant solution I've found - with no intermediary arrays, or redundant loops.
class Hash
  alias_method :include_key?, :include?

  def include?(other)
    return include_key?(other) unless other.is_a?(Hash)
    other.all? do |key, value|
      self[key] == value
    end
  end
end

Since Ruby 2.3 you can use built-in Hash#<= method.

A: Since Ruby 2.3, you can do this:
hash1 <= hash2

A: I am not sure if I understand the inclusion idea in hash.
To see if it has the same keys(usual problem).
All keys in hash1 are included in hash2:
hash1.keys - hash2.keys == []
Then if you want to compare those values do as suggested in the previous post:
hash1.values - hash2.values_at(*hash1.keys) == []


text:
Q: How to detect mouse clicking in vb.net? I want this program for when user click on something either in application or outside of that, make a screen shot and save it as jpeg to a folder
This is the code that I want put those option in it:
Imports System.Net.Mail

Public Class Form1

Private Function TakeImage()
    Return TakeImage(0, 0, Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
End Function

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    PictureBox1.Image = CType(TakeImage(), Image)
End Sub
End Class

by the way I'm beginner in VB.NET

A: I guess it is a desktop application and that TakeImage(,,,) works.
In your form, add a button, double click it and just call TakeImage from there.
Then there is saving as jpeg - just google on how to convert the bitmap(?) format from TakeImage to jpeg and google how to save it. In VB.Net it should be rather easy to handle files.
But first set a return type on your TakeImage function. Probably like as Image. It doesn't change your program but is good practice and will aid you in your learning as the editor will continuously give you helping feedback.
Happy hacking!


text:
Q: Unable to run .netcore app as kubernetes cronjob I would like to create a kubernetes CronJob scheduler which can invoke .netcore console application every minute.
CronJob Spec [cronjob-poc.yml]:
kind: CronJob

metadata:

  name: cronjob-poc

spec:

  schedule: "*/1 * * * *" #Every Minute

  jobTemplate:

    spec:

      template:

        spec:

          containers:

          - name: cronjob-poc

            image: cronjobpoc:dev

            command: ["/usr/local/bin/dotnet", "/app/CronJobPoc.dll"]

          restartPolicy: OnFailure

Kind Commands:
kind create cluster --name=cronjob-poc

kind load docker-image cronjobpoc:dev --name=cronjob-poc

kubectl apply -f .\cronjob-poc.yml

.netcore is a very simple app which just prints hello
using System;

namespace CronJobPoc{

    class Program{

        static void Main(string[] args)
        {
            Console.WriteLine($"{DateTime.Now} - Hello World!");
        }
    }
}

Docker File:
FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["CronJobPoc/CronJobPoc.csproj", "CronJobPoc/"]
RUN dotnet restore "CronJobPoc/CronJobPoc.csproj"
COPY . .
WORKDIR "/src/CronJobPoc"
RUN dotnet build "CronJobPoc.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "CronJobPoc.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CronJobPoc.dll"]

When I do kubectl get pods I see below information.
NAME                           READY   STATUS             RESTARTS   AGE

cronjob-poc-1589463060-9dp8p   0/1     CrashLoopBackOff   4          2m51s

When I try to see logs using kubectl logs cronjob-poc-1589463060-9dp8p I do not see anything. The command returns empty.
Not sure how to see the logs. There is something wrong but not sure what?
I am expecting to see the output " - Hello World!" somewhere in the log. Not sure how to check what went wrong and where can the logs with proper error messages can be seen.
Any quick help on this would be highly appreciated.
I also tried using command argument as shown below in cronjob-poc.yml. I get CrashLoopBackOff status for the pod
command:
- /bin/sh
- -c
- echo Invoking CronJobPoc.dll ...; /usr/local/bin/dotnet CronJobPoc.dll

When I try to check the log using kubectl logs , I see /bin/sh: 1: /usr/local/bin/dotnet: not found

A: You could simplify the Dockerfile a bit. Here's an example I use in my cron job netcore apps:
# Copy csproj and restore as layer 1
FROM microsoft/dotnet:2.1-sdk-alpine AS build
ARG NUGET=https://api.nuget.org/v3/index.json
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore --source $NUGET

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/dotnet:2.1-runtime-alpine AS final
WORKDIR /app
COPY --from=build /app/out .
CMD ["dotnet", "Custom.MetricScraper.dll"]

It's 3 steps, slightly easier to read. You'll notice the difference is that instead of ENTRYPOINT I'm using CMD at the end. You can modify this to fit your project name and netcore 3.1.
Here's the corresponding YAML:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: metric-scraper-job
  labels:
    app: metric-scraper
spec: # Cron job wrapper around a job
  schedule: "* * * * *"
  jobTemplate:
    spec: # Job definition
      template:
        metadata:
          labels:
            app: metric-scraper
            is-cron: "true"
        spec: # Pod definition
          containers:
          - name: metric-scraper
            image: metricscraper:latest
            imagePullPolicy: IfNotPresent
            env:
              - name: ASPNETCORE_ENVIRONMENT
              value: Production
          restartPolicy: Never
      backoffLimit: 2

This YAML definition will run the image metricscraper:latest every minute.
One thing I noticed though about cron jobs in k8s is that the pods don't get cleaned up (at least on my 1.14 cluster). A workaround is setting a pod limit on a namespace via resourcequotas and sticking the cron jobs in there. Hope this helps!

A: The issue was, I was trying to docker this dotnetcore app using Visual Studio which was not installing sdk. When I dockered it manually using command 'docker build -t cronjobpoc .', it worked.
Also in the command I simply used 'dotnet CronJobPoc.dll' as dotnet was already there in the path
command:
- /bin/sh
- -c
- echo Invoking CronJobPoc.dll ...; dotnet CronJobPoc.dl


text:
Q: Remove Daemonset pod from a node I have a running DaemonSet which is running on all nodes. I want to remove it from a node in order to completely drain it, as kubectl drain doesn't get rid of them. Without deleting my DaemonSet, what's a good way to temporarily remove those pods from the node? I've tried draining it and deleting the DaemonSet pods, but the DaemonSet will still reschedule them, disregarding that the node is set as Unschedulable: true.

A: You need to use --ignore-daemonsets key when you drain kubernetes node:

--ignore-daemonsets=false: Ignore DaemonSet-managed pods.

So, in order to drain kubernetes node with DaemonSets in cluster, you need to execute:
kubectl drain <node_name> --ignore-daemonsets

If you need to Remove DaemonSet pod from a node completely, you can specify a .spec.template.spec.nodeSelector in DaemonSet (the DaemonSet controller will create Pods on nodes which match that node selector) and set that label to all nodes except the one you need to completely drain.


text:
Q: why aren't my html buttons aligning properly I cant get the 4 buttons to align in two rows. I've tried using flexbox yet I can only get them to align in two rows of three buttons at the top and one at the bottom. Ideally the buttons would be in the centre of the page, equally distant from each other.
HTML code

CSS code

Result

A: You can do it this way using flexbox note that you have to make two containers as a parent to hold your buttons.

.button_tense{
    width:300px;
    height: 300px;

}
.container{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
}

        <button class="button_tense">present</button>
    <button class="button_tense">past</button>

    <button class="button_tense">future</button>
    <button class="button_tense">imperfect</button>

And using grid with this

    .button_tense{
        width:300px;
        height: 300px;

    }
    .container{
    display: grid;
    grid-template-columns: 1fr 1fr;
    justify-items: center;
    }

        <button class="button_tense">present</button>
        <button class="button_tense">past</button>
        <button class="button_tense">future</button>
        <button class="button_tense">imperfect</button>

I would recommend for you to see this
Guide To Grid
and this
Guide To Flexbox
And welcome to stackoverflow :)

A: You have to add divs around each of the 2 buttons you want in the same row. Code is below.

button{
  margin:5px;
  }

         <button class="button_tense">present</button>
        <button class="button_tense">past</button>

        <button class="button_tense">future</button>
        <button class="button_tense">imperfect</button>


text:
Q: Cassandra data persistence with and without flushing the node Does Cassandra not persist the tables to disk if I don't do nodetool flush
I created the table and keyspace using CQL but I only saw the *-data.db file when I did a flush.
Without it, the data will be lost?

A: When data is written to a node it is first written to the commitlog on disk, and then it is written to a memtable in RAM.
Cassandra will flush the memtable from RAM and write it to an SSTable on disk when its data footprint exceeds the memtable_cleanup_threshold. Only when this happens will the commitlog be cleared. Nodetool flush converts all memtables to SSTables, even if the memtable_cleanup_threshold is not met.
So the answer is no, your data will not be lost. Eventually the memtable size will meet the threshold, and be written to an SSTable on the disk.


text:
Q: Best way to store a list of points I want to store (mass storage) a list of points; to be more precise it is a list that contains  a number not defined (but not exceeding 200) of groups of coordinates, where each group represents an area (a rectangle). This area could be for example a Rect structure.
What is the best way for me:
In order of importance:

*

*Occupied space in storage memory (obviously less is better).

*Ease with which the file is modified (would be better to be able to identify and change the single coordinate, instead of rewrite the entire file due to a change).

*Speed reading.

*Speed writing.

I already had some ideas on how to set up the work (for example simple text format managed by a custom class, serialization, access database (I can only use an access database), ...), but what is the best solution?

A: SQL Server has a native spatial type formats which can be used to store polygons
http://technet.microsoft.com/en-us/library/bb964711
http://technet.microsoft.com/en-us/library/bb895267.aspx
For manipulation, you can load the data into an object to read/modify/validate new points in each polygon.
EDIT: Jason Follas has a good exploration of spatial types here:
http://jasonfollas.com/blog/archive/2008/03/14/sql-server-2008-spatial-data-part-1.aspx
EDIT: I see the OP edited in that he can only use an access database, so my answer no longer applies... but I will leave it as-is in case somebody else finds this question without such a DB limitation.
As for the OP, using only an access database limits your abilities quite a bit.
I would consider two tables: Area and Points with a simple one-to-many relationship.

A: This is exactly the problem set addressed by most GIS storage formats.  There are many different formats available, all with various advantages and disadvantages.
The OGR project supports many formats for GIS style vector data, nearly all of which support storage of area features with most of the characteristics you're after.  One of the "newer" ones here would be ESRI's File Geodatabase format, which is supported in .NET via OGR's C# wrappers.
Alternatively, many database systems, such as SQL Server, PostgreSQL, Oracle, and others support storing spatial data directly in the database.  This may be a bit "heavyweight" depending on your needs, but will support very high performance and scalability.


text:
Q: Transposing Specifc Column to Row Headers and Count, then order by Division I really, really need your help with this,
I'd like to have an SQL query that I could run using MS Access/ADO Jet 4.0 that would take the data from the top table (which is a working example of what is the current data structure in the MDB file) and produce the resulting metrics table in the 2nd table depicted below thus Transposing the [Request Type] Column to Row Headers and Count, then order by Division.
This seems like advanced SQL algebra to me, and goes far beyond my level of SQL knowledge/programming.

A: You need query like this:
TRANSFORM Count(Table1.[Division]) AS CountOfDivision
SELECT Table1.[Branch], Table1.Division
FROM Table1
GROUP BY Table1.[Branch], Table1.Division
PIVOT Table1.[RequestType];


text:
Q: Displaying text on a swt button vertically I'm trying to display text on a button. Instead of displaying it as "Vertical", I'd like to display it as

V
e
r
t
i
c
a
l

Any assistance is much appreciated.

A: You have to make your own widget to achieve it in SWT.
Here is a complete example that you can try. Hope it helps.

A: SWT buttons do support wrapping (since 3.7).
Button button = new Button(parent, SWT.PUSH | SWT.WRAP);
button.setText("V\ne\nr\nt\ni\nc\na\nl");

But unfortunately the lines will be centered as a whole and not individually, so the result does not look particularly good.


text:
Q: Have Drop Down read from a list So I have a react render function that will render a pop-up menu. The user should be able to select from a dropdown menu inside the popup. Since the list of items to be selected are too long it is not possible to have them typed by hand (also maintaining an updated version will be a pain). I am thinking of having them read from a list, but it seems I am out of luck. Can anyone advise me on how to go about doing this?
render(){
//entities is obviously a long list
var entities=["a","b","c",...];
 return(

    <Input type="select" onChange={this.props.filterSelect}>
     {entities.map(e=><option>e</option>)}
    </Input>

 );

The problem is in the drop-down menu I do not get specific entities but only get the letter "e".I do think the problem is related to the scope of the arrow function and how the scope of each item (e) in the call back does not reach within the
<option></option>

tags, sadly I do not know how to take care of this issue. Any ideas?

A: This should fix it:
render(){
var entities=["a","b","c"];
 return(

    <Input type="select" onChange={this.props.filterSelect}>
     {entities.map(e=><option key={e}>{e}</option>)}
    </Input>

 );

A: I think your issue is simply you are missing {} around your variable so try {entities.map(e=><option>{e}</option>)}  instead.

A: render(){
    //entities is obviously a long list
    var entities = ["a", "b", "c", ...];
    return (

            <Input type="select" onChange = { this.props.filterSelect } >
                {
                    entities.map(e => <option>{ e } < /option>)
                }
            < /Input>

    )
}


text:
Q: Compare DateTime from client browser and remote server, C# Here's the scenario
I have a ASP.NET MVC website that has a form that allows client to enter an expiry date (using JQuery datepicker), after the client submits the form I need to check from my server if the submitted date is before the current date.
The problem is that the form or the DateTime object does not include any field that indicates what timezone the user is in, hence I am struggling to convert it to the same timezone the server is in, then compare.
What is a recommend approach to solving this?

A: Hide a form element that contains the offset
<input type="hidden" value="" name="timezone" id="timezone" />

And set its value on page load
$(function () {
    $("#timezone").value(new Date().getTimezoneOffset());
});


text:
Q: journald is not logging error messages I'm having an issue wherein journald is not logging any error messages, but syslog seems to capture them just fine. Here's an example:
journald output:
msg=Publish internal=true prefix="mqi (mqi)"
coral.service: main process exited, code=exited, status=2/INVALIDARGUMENT

syslog (/var/log/messages) output:
app: time="Nov 24 00:26:24.379" level=info msg=Publish internal=true prefix="mqi (mqi)"
systemd: coral.service: main process exited, code=exited, status=2/INVALIDARGUMENT
app: panic: process queue name is too long 'ENV_SGOBSIDTESTMANTLEIDENTITIIIO_I8CDDI8CDD_PROC'
app: goroutine 28 [running]:
app: lab.identitii.com/identitii/lib/ibis/ibiscon/mqi.partyToQueueName(0xc4253e45d0, 0x1369fe8, 0xc42004f180)
    <stack trace>

The unit file for the service looks like this.
    [Unit]
    Description=Frontend
    Wants=network-online.target
    After=network.target network-online.target

    [Service]
    User=user
    WorkingDirectory=/usr/local/identitii/coral
    Environment=LD_LIBRARY_PATH=/opt/oracle/instantclient_12_2
    Environment=I8_config_path=/usr/local/srv/config/common,/usr/local/srv/config/coral
    ExecStart=/usr/local/srv/coral/app
    Type=simple

    [Install]
    WantedBy=multi-user.target

I've tried redirecting stderr to stdout by appending 2>&1 to the ExecStart with no love. Any ideas?
I'm running RHEL 7.2.
Cheers


text:
Q: AWS Lambda SES send email with attachment PYTHON My Lambda function creates a text file in /tmp location within in lambda environment.
I am failing to send the file as an attachment using Lambda SES Python
I am following code from below AWS documentation to send RAW email with attachment using SES Python3.6
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-raw-using-sdk.html
def send_mail_with_attach_ses(sender, recipient, aws_region, subject, file_name):
    # The email body for recipients with non-HTML email clients.
    BODY_TEXT = "Hello,\r\nPlease find the attached file."

    # The HTML body of the email.
    BODY_HTML = """\

Hello!

Please find the attached file.

    """

    CHARSET = "utf-8"
    client = boto3.client('ses',region_name=aws_region)

    msg = MIMEMultipart('mixed')
    # Add subject, from and to lines.
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recipient

    msg_body = MIMEMultipart('alternative')
    textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
    htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)

    # Add the text and HTML parts to the child container.
    msg_body.attach(textpart)
    msg_body.attach(htmlpart)

    # Define the attachment part and encode it using MIMEApplication.
    att = MIMEApplication(open(file_name, 'rb').read())

    att.add_header('Content-Disposition','attachment',filename=os.path.basename(file_name))

    if os.path.exists(file_name):
        print("File exists")
    else:
        print("File does not exists")

    # Attach the multipart/alternative child container to the multipart/mixed
    # parent container.
    msg.attach(msg_body)

    # Add the attachment to the parent container.
    msg.attach(att)

    try:
        #Provide the contents of the email.
        response = client.send_raw_email(
            Source=msg['From'],
            Destinations=[
                msg['To']
            ],
            RawMessage={
                'Data':msg.as_string(),
            },
            ConfigurationSetName="ConfigSet"
        )
    # Display an error if something goes wrong.
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message ID:"),
        print(response['MessageId'])

    # Add a header to tell the email client to treat this part as an attachment,
    # and to give the attachment a name.
    att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))

    # Attach the multipart/alternative child container to the multipart/mixed
    # parent container.
    msg.attach(msg_body)

    # Add the attachment to the parent container.
    msg.attach(att)

After trigger the lambda the function is reaching to response = client.send_raw_email and never returning until the lambda timesout. My lambda timeout is configured for 3 minutes.
{
  "errorMessage": "2019-07-30T10:14:45.180Z fc3ca995-58f9-4f89-8a35-114d941ee063 Task timed out after 180.06 seconds"
}

Can anyone help to send email with attachment using Lambda SES Python?

A: Your Lambda is timing out after 180 seconds. For what you're looking to achieve it shouldn't take this long.
Instead of increasing the timeout you should work out where the bottleneck is in your code and fix that.

A: you just have to extend the timeout value under basic settings of the function. It can go up to 15 mins.


text:
Q: Unity URP Can't override virtual function I'm trying to follow this article: https://bronsonzgeb.com/index.php/2021/03/20/pseudo-metaballs-with-scriptable-renderer-features-in-unitys-urp/
I've gotten to the end of it and tried to compile but got the following message:
RenderWater.cs(38,30): error CS0115: 'RenderWater.RenderObjectsPass.OnCameraSetup(CommandBuffer, ref RenderingData)': no suitable method found to override

The line in question is:
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)

I'm new to URP and so I have likely missed something, but I have not idea what

A: Edit: Just need to make sure you have "Universal RP" installed in the Package Manager.

Are you inheriting the right class? You need to make sure that you're doing the following instead of inheriting from MonoBehavior.
YourClass : TheClassWithThatMethodInIt

Are you running into a namespace issue? Does VS flag it as missing the method to override as well?

A: Lots of missing functions are added to the 2020 version - you might want to update your unity to the newer one. You can check the unity change log here
OnCameraSetup is added in 2020


text:
Q: Click event not working when using font awesome inside A Tag I have A tag which have font awesome inside it. Sometimes it doesnt work when I use the font awesome icon, and need to try this until 3 or 4 times to make it works. What should I do?
$(".confirm-delete").click(function(e) {
  e.preventDefault();
  let id = e.target.dataset.id;
  Swal.fire({
    title: 'Perhatian!',
    text: "Apakah Anda yakin untuk menghapus pengisi jabatan ini?",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Ya, hapus',
    cancelButtonText: 'Tidak'
  }).then((result) => {
    if (result.isConfirmed) {
      $(`#delete${id}`).submit();
    }
  })
});

id }}" class="btn btn-danger btn-sm confirm-delete">
   <form action="{{ route('position.delete', ['congregationId' => $servant->id]) }}" method="post" class="d-inline" id="delete{{ $servant->id }}">
      @csrf
      @method('delete')
   </form>

A: You need to address your way to the container element
In jQuery use $(this)
but I do not like the form inside your link

$(".confirm-delete").on("click", function(e) {
  e.preventDefault();
  console.log($(this).data("id"));
})

  <form action="" method="post" class="d-inline" id="deleteX">
  </form>Something else
  X

In plain JS use currentTarget to get the element the eventhandler is assigned to

$(".confirm-delete").on("click", function(e) {
  const tgt = e.target; // A or I depending. I if you click I
  const link = tgt.closest("a"); // Always A if clicking inside the link
  const curr = e.currentTarget; // The A since that is where we have the .on
  const id = e.currentTarget.dataset.id; // the ID from the link
  e.preventDefault();
  console.log(tgt.tagName, link.tagName, curr.tagName, id);
})

  <form action="" method="post" class="d-inline" id="deleteX">
  </form>Something else
  X

A: You can use currentTarget to get the element the event was bound to.
const id = e.currentTarget.dataset.id; // should be const because you don't reassign it.

A: I don't like the way you have a form inside your anchor - if you have inputs being rendered inside the form, then your html will be invalid and can cause some issues with how the browser renders it
Instead of having an anchor that you tie your event to, why not just use a button inside your form and if the result is not confirmed, prevent the default action:
Change html:
<form action="{{ route('position.delete', ['congregationId' => $servant->id]) }}" method="post" class="d-inline" id="delete{{ $servant->id }}">
  @csrf @method('delete')
  <button class="confirm-delete"></button>
</form>

And prevent the default action of the button if the result is not confirmed:
$(".confirm-delete").click(function(e) {
  Swal.fire({
    title: 'Perhatian!',
    text: "Apakah Anda yakin untuk menghapus pengisi jabatan ini?",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Ya, hapus',
    cancelButtonText: 'Tidak'
  }).then((result) => {
    if (!result.isConfirmed) {
      e.preventDefault();  // prevent default action if not confirmed
    }
  })
});

By doing it this way it is more accessible too as your form will work (without the confirmation) even if javascript is disabled


text:
Q: Placing 3 identical bananas into 10 numbered distinct boxes I am a little bit confused on how to count the number of ways to distribute 3 identical bananas into 10 numbered boxes. Where we can have more than one banana in each box.
My teacher divided the problem into 4 cases.
case 1: 1 banana in each box
case 2: 2 bananas then 1 banana
case 3: 1 banana then 2 bananas
case 4: 3 bananas in each box.
Then each case could be solved by combination.
My first question is why are case 2 and case 3 different aren't we double counting ? isn't one of them already takes into consideration all possible ways to distribute 2 bananas and 1 banana.
I tried my own way to solve the problem, however I know that it is false since I am not getting an integer number. The way a proceeded is that we take the first banana, there are 10 different boxes to put them in so that's 10, then we take the second banana and also 10 possible boxes to place the banana then finally we have the third bananas which also have 10 possible boxes.
So by the rule of product we have 10*10*10. we have 3 identical bananas so we must divide by 3!
I know that my answer is wrong (since it is not an integer) but I don't see why it is wrong, for me the logic makes sense but I could be missing something.
I am struggling to understand the logic behind this problem.

A: Your answer is wrong because when two bananas go into the same box, it's not correct to divide those combinations by $6$.  If that's the approach you use, then it's essential to divide into cases along the lines of the solution presented by your teacher.
But for this sort of problem I prefer the approach often known as "stars and bars."  You have $9$ bars representing the dividers between the $10$ boxes.  You have $3$ stars representing the $3$ bananas.  There are $\binom{12}{3}=220$ ways to arrange the stars and bars in a line, and each different arrangement yields a unique division of the bananas into boxes.


text:
Q: how the wordpress login works I have a WordPress-based site and also have other sites that don't use frameworks. I have a desire to use my WordPress account and password to log in to my other sites.
I know that WordPress uses phpass to encrypt and verify passwords. I have been able to use phpass on other sites to authenticate the login stored in the WordPress database.
I want to know, how can I log in with my WordPress account when I log in to other websites? In other words, how does WordPress implement remembering the login state?


text:
Q: Utilizing Foreach to generate a submenu I have two functions I'm working on that interact with each other and at this point I'm trying to fix the submenu portion of it.
My menu is generated using
public function CreateNavigation() {
            global $db;
            $query = <<<SQL
            SELECT id,name
            FROM pages
            WHERE enabled = :enabled
            AND main = :main
SQL;
            $resource = $db->sitedb->prepare( $query );
            $resource->execute( array (
            ':enabled'  =>  1,
            ':main'     =>  1,
            ));
                foreach($resource as $menu){
                    $this->parentid = $menu['id'];
                    echo "
".$menu['name']."
                    ".self::GetSublinks()."
";
                }

    }

And then the GetSublinks takes over to determine the dropdown of the menu
    public function GetSublinks() {
        global $db;
        $query = <<<SQL
        SELECT id,name
        FROM pages
        WHERE parentid = :parentid
        AND enabled = :enabled
SQL;
        $resource = $db->sitedb->prepare( $query );
        $resource->execute( array (
        ':parentid' => $this->parentid,
        ':enabled'  => 1,
        ));
        $row_count = $resource->rowCount();
        if($row_count >= 1) {
            return "
";
            foreach($resource as $row){
                return "
".$row['name']."
"
            }
            return "
";
        }
    }

Now the main menu itself works great, Even the sublinks work great to a degree. They check to make sure and modify the main link to show it has children if it does, but where I run into the issue is within the children it will only show the last of the links, so I can't have more than one dropdown because of this.
I have also tried changing my foreach within the sublinks to
while($row = $resource->fetch(PDO::FETCH_ASSOC))

To no avail. My menu works fine without having the dropdown, but the dropdown would be nice to add in.
var_dump($resource) Results:
object(PDOStatement)#7 (1) { ["queryString"]=> string(86) " SELECT id,name FROM pages WHERE parentid = :parentid AND enabled = :enabled" } object(PDOStatement)#7 (1) { ["queryString"]=> string(86) " SELECT id,name FROM pages WHERE parentid = :parentid AND enabled = :enabled" }

var_dump($row) Results:
array(2) { ["id"]=> string(1) "2" ["name"]=> string(10) "Create New" } array(2) { ["id"]=> string(1) "3" ["name"]=> string(14) "Delete Listing" }

A: I think your string concatenation and returning value is wrong. It should be like :
    if($row_count >= 1) {
        $subMenu = "";
        $subMenu .= "
";
        foreach($resource as $row){
            $subMenu .= "
".$row['name']."
"
        }
        $subMenu .= "
";
        return $subMenu;
    }

You should keep concatenating and at the end only return submenu.

A: When your code reaches to
return "
";

it will exit the function and return
 so it wont even come to foreach loop so you need to concatenate  string and than return it

return ¶ If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.

if($row_count >= 1) {
       $sub_menu = "
";
       foreach($resource as $row){
            $sub_menu .= "
".$row['name']."
"
        }
         return $sub_menu ."
";
  }


text:
Q: Ruby: POST data to a url In a rails app I want to be able to post some information to another website inside a method without visiting the website. I'm fairly new to the topic so act as if I'm 5 years old.
My idea so far:
def create_button
  button = {
    :name => 'test',
    :type => 'buy_now',
    :callback_url => 'http://www.example.com/my_custom_button_callback',
    :description => 'sample description',
    :include_email => true
  }
  "https://thesite.com/api/v1" + button.to_query
  # post logic here

end

A: Ruby ships with the Net::HTTP library for making HTTP requests. There are a lot of gems that wrap HTTP as well, my favorite is Faraday. Look into those libraries, it is pretty straightforward how to make a POST request with them.

A: There are a lots of gems that do this for free but if you only want to use the standard library, try something like this:
require "net/http"
require 'net/https'
require "uri"

uri = URI.parse("https://thesite.com/api/v1")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path)

# I'm unsure if symbols will work
button = {
  "name" => 'test',
  "type" => 'buy_now',
  "callback_url" => 'http://www.example.com/my_custom_button_callback',
  "description"  => 'sample description',
  "include_email" => true
}
req.set_form_data(button)
res = https.request(req)

A: Try: Net::HTTP
uri = URI.parse("https://thesite.com/api/v1")
button = {
 :name => 'test',
 :type => 'buy_now',
 :callback_url => 'http://www.example.com/my_custom_button_callback',
 :description => 'sample description',
 :include_email => true
}
res = Net::HTTP.post_form(uri,button)
res.code
res.body  # response from api


text:
Q: Ruby on Rails: What are Erubis' disadvantages and why isn't it packaged with Rails by default? How to set it up? I just discovered Erubis, a replacement for the default view renderer for Ruby on Rails. However, from what I can tell from reading about it, it's superior across the board.
It is much faster.
It has many more options.
It can prevent cross site scripting without having to use h.
Does this have any disadvantages versus the standard erb renderer? Why isn't this the standard renderer packaged with Rails?
Also, the docs for Erubis say to install it just by installing the gem, and then add the following to environment.rb:
require 'erubis/helpers/rails_helper'
#Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby

Reading the docs, FastEruby seems to be just a faster renderer than Eruby. Why wouldn't it be default and used by everyone?
I'm highly interested in using the engine erubis::EscapedEruby which automatically calls h to escape html on fields from the database. Are there any gotchas I should be aware of or does this pretty much solve  all cross site scripting?

A: The Rails team agrees. Erubis is the default in Rails 3 beta versions, and will be the default when Rails 3 is released. Yehuda Katz mentioned it in his blog, and Erubis is listed as a dependency for Action Pack in the current Rails 3 betas.

A: It's packaged by default as dependency gem in Rails4.
You can find more details here:
Ruby 2.1 with erubis Template Engine


text:
Q: cufftcomplex.h Programmers reference/Documentation I am working on an cufft implementation and can't find any reference to the cufftcomplex functions. I found cucomplex.h through google, though, but that doesn't help me. Specifically i want to know, how to read out the imaginary part and the real part of the cufftcomplex struct.

A: The types cufftComplex and cuComplex are actually same. It is documented in the cuFFT documentation. In cufft.h you will find the typedef:
typedef cuComplex cufftComplex;

In cuComplex.h you will find that cuComplex is indeed a float2, i.e. you can read out the real value with c.x and the imaginary value with c.y. Or better use the functions cuCrealf() and cuCimagf() which are provided in cuComplex.h.