unity – How can a object be prevented from falling?

I tried to make projectile for a Spaceship for 3D game. But whenever I instanitate an projectile and make it move, ıt falls . I assume because of rigidbody but couldn’t find how to fix. I want projectile to move forward and not fall.

Those are components of projectile

enter image description here

Those are codes I used to keep projectile from falling.

void Update()
    //transform.position += new Vector3(-1, 0, 0) * 0.1f;
    //GetComponent<Rigidbody>().velocity = -transform.right * 100 * Time.deltaTime;
    //GetComponent<Rigidbody>().AddForce(transform.up * 0.000001f);

unity – Why when using editor script with handles with DrawSolidArc it’s not drawing any arc over the object?

This is the editor script is in the Assets/Editor

using UnityEngine;
using UnityEditor;

public class DrawSolidArcEditor : Editor
    public float arrowSize = 1;

    void OnSceneGUI()
        DrawSolidArc t = target as DrawSolidArc;

        Handles.color = Color.blue;
        Handles.Label(t.transform.position + Vector3.up * 2,
                             t.transform.position.ToString() + "nShieldArea: " +

        GUILayout.BeginArea(new Rect(Screen.width - 100, Screen.height - 80, 90, 50));

        if (GUILayout.Button("Reset Area"))
            t.shieldArea = 5;


        Handles.color = new Color(1, 1, 1, 0.2f);
        Handles.DrawSolidArc(t.transform.position, t.transform.up, -t.transform.right,
                                180, t.shieldArea);

        Handles.color = Color.white;
        t.shieldArea = Handles.ScaleValueHandle(t.shieldArea,
                        t.transform.position + t.transform.forward * t.shieldArea,
                        t.transform.rotation, 1, Handles.ConeHandleCap, 1);

And the mono script for example this script is attached to a simple 3d cube :

using UnityEngine;

public class DrawSolidArc : MonoBehaviour
    public float shieldArea = 5;

but there is nothing around the cube. not also near it nothing.
it should draw arch in the editor.

Later I want to be able to use the mouse with a click down and drag to be able to change the arc size but for not it’s not drawing any arc.

I took the example from the unity official docs :


I noticed now also for example that I don’t see the gui button in the inspector of the object that the mono script is attached to :

if (GUILayout.Button("Reset Area"))

not sure what’s wrong with the editor script.

This is working. I still wonder why the unity docs example didn’t work but this is working and I don’t need the editor script. The problem with this script is that I must to turn on the Gizmos in the editor and I don’t want to make it turned on all the time. So it’s working but not as I wanted.

I want to draw the arc without the gizmos.

using UnityEngine;

public class DrawSolidArc : MonoBehaviour
    public Vector3 offset = Vector3.one;
    public float fieldOfViewAngle = 20;
    public float viewDistance = 4;
    public bool usePhysics2D = false;

    public void OnDrawGizmos()
        DrawLineOfSight(this.transform, offset, fieldOfViewAngle, viewDistance, usePhysics2D);
    public static void DrawLineOfSight(Transform transform, Vector3 positionOffset, float fieldOfViewAngle, float viewDistance, bool usePhysics2D)
        var oldColor = UnityEditor.Handles.color;
        var color = Color.yellow;
        color.a = 0.1f;
        UnityEditor.Handles.color = color;
        var halfFOV = fieldOfViewAngle * 0.5f;
        var beginDirection = Quaternion.AngleAxis(-halfFOV, (usePhysics2D ? Vector3.forward : Vector3.up)) * (usePhysics2D ? transform.up : transform.forward);
        UnityEditor.Handles.DrawSolidArc(transform.TransformPoint(positionOffset), (usePhysics2D ? transform.forward : transform.up), beginDirection, fieldOfViewAngle, viewDistance);
        UnityEditor.Handles.color = oldColor;

java – Instatiate a PGPPrivateKey object with an arbitrary private key block

Given a PGP public key block like below, how does one instantiate a BouncyCastle PGPPrivateKey object using the key?


I’ve found numerous examples of how to obtain a PGPPrivateKey from a PGPSecretKeyRing, but unfortunately I am starting from private keys in he format above. I haven’t been able to find a way to either instantiate a PGPPrivateKey using that data, or place the data into a PGPSecretKeyRing for easy extraction.

A means of going from the PRIVATE KEY BLOCK format to a Java representation don’t appear to be supported out of the box by BouncyCastle, but I also don’t know where to begin going about transforming them into a format that’s usable. I’ve tried many permutations of the below and similar versions using PGPObjectFactory, but haven’t been able to find a way to hand off the private key block in a format that the PGP library knows how to consume.

privateKeyInputStream = PGPUtil.getDecoderStream(new ByteArrayInputStream(privateKeyBytes));
    PGPSecretKeyRingCollection pgpSecretKeyRingCollection =
            new PGPSecretKeyRingCollection(privateKeyInputStream, new JcaKeyFingerprintCalculator() );
    Iterator keyRingIterator = pgpSecretKeyRingCollection.getKeyRings();
    while(keyRingIterator.hasNext()) {
        String className = keyRingIterator.next().getClass().getSimpleName();
        System.out.println("keyRingIterator object : " + className); // never called

How can a private key provided by a PGP PRIVATE KEY BLOCK be used to decrypt a file in Java code?

python 3.x – How to write a dictionnary of object instances describing geometrical shapes

My current position implies a lot of programming but I lack formal knowledge concerning how to properly code, and this is the object of my question. I believe the form of my code could be improved. As a result, here is a much simplified version of the program I am writting, that shares the same structure but is much simpler to read. I think I could realy use the opinion of people who knows python better than me.

Here, I define a class « geometric_shape », which can be used to calculate proporties of shapes, for exemple the area square or rectangles.

  • The main class has two arguments, “dimensions” and “model”, that is used to define the shape.
  • The different shapes are defined in the dictionnary “self.list_of_models”.
    • The key is the name of the different possible shapes.
    • Each value is a empty subclass instance, in which we define all the parameters of a given shape, here the number of parameters that describes the shape and the function used to calculate the area.
  • Finally, there is one method “area” that returns the area for the defined shape.

The advantage is, I can easily get the properties of a given shape by calling them using the string “self.model”. For example, here, I can call the number of parameters required to completely describe a shape using self.list_of_models( self.model ).noparameters

The problem is that I do not feel like it is an elegant way of doing things. For exemple, if I call the object instance, I see the variable is defined in a weird way.

Out(2): <__main__.geometric_shape.__init__.<locals>.model at 0x1dc810ea988>

So my question is : Would someone know a more elegant way to input a list of « shapes » than a dictionnary of object instances, or is this formulation fine the way it is ?

# -*- coding: utf-8 -*-

class geometric_shape:
    ''' Fonction utilitaires de spindiff, importé en tant que super classe dans spindiff'''
    # ==============================================================================================
    def __squared__(a):
        return a(0)**2
    def __product__(a):
        return a(0)*a(1)

    # ==============================================================================================
    def __init__(self):
        ''' Create list of available models'''

        self.dimensions = (1, 2 )
        self.model = 'square' # rectangle
        class model :
            ''' Définit une classe de modèle de système dans lequel la diffusion de spin est simulée.'''
            def __init__(self):
                self.noparameters = 1
                self.area_function = None
        self.list_of_models = {
                'square' : model() ,
                'rectangle' : model() ,     
        # model square
        self.list_of_models('square').noparameters = 1
        self.list_of_models('square').area_function = self.__squared__
        # model rectangle
        self.list_of_models('rectangle').noparameters = 2
        self.list_of_models('rectangle').area_function = self.__product__
    # ==============================================================================================    
    def area(self):
        ''' Return the area of the figure '''
        if len(self.dimensions) != self.list_of_models( self.model ).noparameters:
            raise ValueError('Nombre of parameters not compatible with this shape')
        return self.list_of_models( self.model ).area_function( self.dimensions )
# ==============================================================================================
if __name__ == '__main__':

    square = geometric_shape()
    self = square
    square.dimensions = ( 3. )
    square.model = 'square'
    print( square.area() )

object oriented – Python Back-end registration validation

I am working on a personal project (Flask CRUD app) and I am currently building the user service. I am trying to use as less as libraries as possible (that’s why I do not use WTF-forms for example, just for learning purposes). I am really not sure about a couple of things.

I am aware that form validation should be handled in both front and back-end (or at the very least on the back-end). In order to validate a new user, I am (currently) checking 3 things:

1) email does not already exist on the db (can only be verified on the back-end)

2) password is strong enough (can be done in both front and back end)

3) password and password_confirm matches (can be done in both front and back end)

My goal is to display a small error message on the registration page if either at least one those errors appears. Currently, I am checking option 1, 2 and 3 and the back-end but only return True if the registration is valid otherwise, False.

Since case 1 and 2 can directly be handle also on the front-end, can I display the error message using JavaScript and not from the back-end? I am still confused on what would be the best return for validate_registration (currently a Boolean).

Also, I am not quite sure my code is over-engineered, I made a RegistrationForm class just to validate a registration form. I did that because I am able to pick validations methods from my validators.py which may be used in other Classes as well.

So this is what I did so for for the registration form:


@user.route('/new-user',methods = ('POST'))
def register_user():
    form_email = request.form.get('email')
    form_password = request.form.get('psw')
    form_password_repeat = request.form.get('psw-repeat')
    registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration()
    if registration_form:
        new_user = UserService().register_user(form_email, form_password)
        user_repository = UserRepository(conn, 'users')
        return "ok" #will probably change return statements later on
    return "not ok" #will probably change return statements later on


from prepsmarter.blueprints.user.validators import email_already_in_use, password_matching

class RegistrationForm():
    def __init__(self, email, pwd_1, pwd_2):
        self.email = email
        self.pwd_1 = pwd_1
        self.pwd_2 = pwd_2

    def validate_registration(self):
        is_valid = email_already_in_use(self.email) and is_strong_password(self.pwd_1) and password_matching(self.pwd_1, self.pwd_2)
        return is_valid

class LoginForm():
 # to do


import re 
from email_validator import validate_email, EmailNotValidError
from prepsmarter.extensions import conn

def is_strong_password(password):
    length_error = len(password) < 8
    digit_error = re.search(r"d", password) is None
    uppercase_error = re.search(r"(A-Z)", password) is None
    return length_error and digit_error and uppercase_error
def is_email_formated_correctly(email):
    is_correct = True
    except EmailNotValidError:
        is_correct = False
    return is_correct

def password_matching(pwd_1, pwd_2):
    return pwd_1 == pwd_2

def email_already_in_use(email):
    sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM users WHERE email = (%s)) THEN 1 ELSE 0 END;"
    cursor = conn.cursor()
    cursor.execute(sql, (email))
    res = cursor.fetchall()
    return res == 1 

java – Passing object or using the field

I would like to know what is a more appropriate way to code in Java. Is it generally better to pass entire objects in the method’s parameters or just using the fields from the class?

  1. Using the field:
public class Dictionary {
    ArrayList<Definition> list;

    public Dictionary() {
        this.list = new ArrayList<Definition>();

    public void newEntry(String key, String value) {
        this.list.add(new Definition(key, value)); 
public class SampleTests {
    public void Tests()
        Dictionary d = new Dictionary();

        d.newEntry("Apple", "A fruit");
  1. Passing an object:
public class Dictionary {

    public Dictionary() {
        //this.list = new ArrayList<Definition>();

    public void newEntry(String key, String value, ArrayList<Definition> list) {
        list.add(new Definition(key, value)); //I'm using field from this class!
public class SampleTests {
    public void Tests()
        Dictionary d = new Dictionary();
        ArrayList<Definition> list = new ArrayList<>();

        d.newEntry("Apple", "A fruit", list);

I’ve checked this related question, but the guys’ answers do not help me much

powershell – Poswershell MongoDb – Unable to cast object of type ‘System.Object[]’ to type MongoDB.Driver.ProjectionDefinition`1[MongoDB.Bson.BsonDocument]’

I am exporting MongoDB data from a collection into a file using Get-MdbcData. I am selecting fields from the collection using the parameter -Project with a string variable $FieldAttributes that lists either one or multiple fields to select and should have the format: @{_id=0; customer_id=1; account_status=1}

Get-MdbcData -Collection $MyColl -Project $FieldAttributes 

Below is the code with the function that outputs the expected format of $FieldAttributes above.

function Format-ColumnSelect {
        (string()) $Columns
    $results = @{}
    $Columns = "_id," + $Columns
    try {

        foreach($a in $Columns -split ",") {
                if ($a -eq "_id") {
                else {
        return  HashConvertTo-String($results)
    } catch {
        Write-Error -Message $_.Exception.GetBaseException().Message
    } finally {
$FieldAttribute = "customer_id,account_status"
$FieldAttributes = Format-ColumnSelect -Columns $FieldAttribute
Connect-Mdbc $Url $Database $CollectionName -CollectionVariable MyColl;
Get-MdbcData -Collection $MyColl -Project $FieldAttributes  | Export-MdbcData $Path -Append;

When executed, I get the error:
Unable to cast object of type ‘System.Object()’ to type MongoDB.Driver.ProjectionDefinition`1(MongoDB.Bson.BsonDocument)’.

If I hard code the projection expression, @{_id=0; customer_id=1; account_status=1}, it works as expected but errors out with the variable.
How do I cast $FieldAttributes to the expected type? Any help is appreciated.

physics – Does the work required to lift an object depend on the acceleration of the object?

I’m confused by an example in Stewart’s (8th edition, early transcendentals) Calculus textbook. Example 1, Section 6.4: “How much work is done in lifting a 1.2kg book off the floor to put it on a desk that is 0.7m high?”

I can understand the computation: (mass) times (acceleration due to gravity) times (distance). What I don’t understand is why the acceleration of the object as it gets lifted does not factor into the equation. I thought maybe we should just assume it’s constant velocity, but that really doesn’t make sense if the object is starting on the floor (where presumably the velocity is zero).

Is there a more precise way to phrase this question, like, “How much work is done against the force of gravity in lifting a 1.2kg book off the floor to put it on a desk that is 0.7m high?”

Is my confusion understandable? I’m not intentionally being pedantic. (I have a lot of respect for Stewart’s Calculus book.)

Overall I was trying to understand (vector) line integrals better, and kept backtracking until I came to this example. I’m posting this in the math forum instead of the physics forum because I’m used to thinking about math definitions. (I last took a physics class in 11th grade.)

Thank you!

unity – First object jumps on re-entry of second colliding object

The scenario is that I have two objects – Object A and Object B. The Object A is lying on the ground and when Object B enters the collider of Object A, the Object A moves (only X and Z axis) with Object B. The movement works well with the script shown below.

The issue is that most of the time, the Object A’s initially position shifts by few meters whenever Object B enters its collider. I feel it is related to offset position. What should happen is that, Object A should be the same position when Object B enters the collider and move along with Object B only when Object B moves.

So how do I fix this?

private Vector3 offsetPosition;

public Transform ObjectB;

public bool ObjectB_Collision = false;

void Start () {
        offsetPosition = ObjectB.transform.position - this.transform.position;

    void ObjectB_HasEntered() {
        offsetPosition = ObjectB.transform.position - this.transform.position;

    // Update is called once per frame
    void LateUpdate () {

        if (ObjectB_Collision == true) {
            this.transform.position = new Vector3 (ObjectB.transform.position.x, this.transform.position.y, ObjectB.transform.position.z) - new Vector3 (offsetPosition.x, 0, offsetPosition.z);


public void OnTriggerEnter (Collider col) {
        if (!enabled) return;

        if (col.gameObject.name == "Object_B") {
            ObjectB_Collision = true;

public void OnTriggerExit (Collider col) {
        if (!enabled) return;

       if (col.gameObject.name == "Object_B") {
            ObjectB_Collision = false;


Clean way to remove an identical nested object in javascript

can you give me some feedback about my approach to remove an idential element from following data structure?

const items = {
  'Sun Mar 07 2021': (
     { id: 2 },
     { id: 1 }
  'Sat Mar 06 2021': (
     { id: 1 } // remove me

const id = 1 // filter by id 1
const newDate = 'Sun Mar 07 2021' // filter by newDate

let oldDate = ''
// Find the duplicate date and 
// save it in oldDate to splice it afterwards
Object.keys(items).forEach(date => {
  items(date).forEach(item => {
    const match = item.id === id
    if (match && date !== newDate) {
      oldDate = date

// remove the old item from matched array
if (oldDate) items(oldDate).splice(item => item.id === id)

I think it can be simplified or solved differently. Unfortunately I can’t get any further, do you have any ideas?