kandi background
Explore Kits

epoxy | Android library for building complex screens | RecyclerView library

 by   airbnb Java Version: 5.0.0beta03 License: Apache-2.0

 by   airbnb Java Version: 5.0.0beta03 License: Apache-2.0

Download this library from

kandi X-RAY | epoxy Summary

epoxy is a Java library typically used in User Interface, RecyclerView applications. epoxy has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
Epoxy is an Android library for building complex screens in a RecyclerView. Models are automatically generated from custom views or databinding layouts via annotation processing. These models are then used in an EpoxyController to declare what items to show in the RecyclerView. This abstracts the boilerplate of view holders, diffing items and binding payload changes, item types, item ids, span counts, and more, in order to simplify building screens with multiple view types. Additionally, Epoxy adds support for saving view state and automatic diffing of item changes. We developed Epoxy at Airbnb to simplify the process of working with RecyclerViews, and to add the missing functionality we needed. We now use Epoxy for most of the main screens in our app and it has improved our developer experience greatly.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • epoxy has a highly active ecosystem.
  • It has 7822 star(s) with 676 fork(s). There are 162 watchers for this library.
  • There were 3 major release(s) in the last 12 months.
  • There are 254 open issues and 562 have been closed. On average issues are closed in 109 days. There are 11 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of epoxy is 5.0.0beta03
epoxy Support
Best in #RecyclerView
Average in #RecyclerView
epoxy Support
Best in #RecyclerView
Average in #RecyclerView

quality kandi Quality

  • epoxy has 0 bugs and 0 code smells.
epoxy Quality
Best in #RecyclerView
Average in #RecyclerView
epoxy Quality
Best in #RecyclerView
Average in #RecyclerView

securitySecurity

  • epoxy has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • epoxy code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
epoxy Security
Best in #RecyclerView
Average in #RecyclerView
epoxy Security
Best in #RecyclerView
Average in #RecyclerView

license License

  • epoxy is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
epoxy License
Best in #RecyclerView
Average in #RecyclerView
epoxy License
Best in #RecyclerView
Average in #RecyclerView

buildReuse

  • epoxy releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • epoxy saves you 50998 person hours of effort in developing the same functionality from scratch.
  • It has 95615 lines of code, 10484 functions and 861 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
epoxy Reuse
Best in #RecyclerView
Average in #RecyclerView
epoxy Reuse
Best in #RecyclerView
Average in #RecyclerView
Top functions reviewed by kandi - BETA

kandi has reviewed epoxy and discovered the below as its top functions. This is intended to give you an instant insight into epoxy implemented functionality, and help decide if they suit your requirements.

  • Initializes the touch helper .
  • Collects a list of moved items .
  • Validates that the class implements hashCode .
  • Submit new list .
  • Find and setter method for private field .
  • Calculates the offsets of a RecyclerView .
  • Adds a new controller to the controller .
  • Override the super implementation to draw the touch helper .
  • Removes duplicated models which have been added to the model .
  • Checks if two models are equals .

epoxy Key Features

Installation

Basic Usage

Documentation

Min SDK

Contributing

Sample App

Installation

copy iconCopydownload iconDownload
dependencies {
  implementation "com.airbnb.android:epoxy:$epoxyVersion"
  // Add the annotation processor if you are using Epoxy's annotations (recommended)
  annotationProcessor "com.airbnb.android:epoxy-processor:$epoxyVersion"
}

Library Projects

copy iconCopydownload iconDownload
buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.1.0'
  }
}

Creating Models

copy iconCopydownload iconDownload
@ModelView(autoLayout = Size.MATCH_WIDTH_WRAP_HEIGHT)
public class HeaderView extends LinearLayout {

  ... // Initialization omitted

  @TextProp
  public void setTitle(CharSequence text) {
    titleView.setText(text);
  }
}

Using your models in a controller

copy iconCopydownload iconDownload
public class PhotoController extends Typed2EpoxyController<List<Photo>, Boolean> {
    @AutoModel HeaderModel_ headerModel;
    @AutoModel LoaderModel_ loaderModel;

    @Override
    protected void buildModels(List<Photo> photos, Boolean loadingMore) {
      headerModel
          .title("My Photos")
          .description("My album description!")
          .addTo(this);

      for (Photo photo : photos) {
        new PhotoModel()
           .id(photo.id())
           .url(photo.url())
           .addTo(this);
      }

      loaderModel
          .addIf(loadingMore, this);
    }
  }

Integrating with RecyclerView

copy iconCopydownload iconDownload
MyController controller = new MyController();
recyclerView.setAdapter(controller.getAdapter());

// Request a model build whenever your data changes
controller.requestModelBuild();

// Or if you are using a TypedEpoxyController
controller.setData(myData);

License

copy iconCopydownload iconDownload
Copyright 2016 Airbnb, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

MediaController for VideoView inside BottomSheetDialog is hidden behind the BottomSheetDialog

copy iconCopydownload iconDownload
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content">

<VideoView
    android:id="@+id/videoView"
    android:layout_width="wrap_content"
    android:layout_height="210dp"
    android:layout_marginTop="16dp"
    android:clickable="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<FrameLayout
    android:id="@+id/frameView"
    android:layout_width="@id/videoView"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:layout_constraintStart_toStartOf="@id/videoView"
    app:layout_constraintEnd_toEndOf="@id/videoView"
    app:layout_constraintBottom_toBottomOf="@id/videoView"/>

</androidx.constraintlayout.widget.ConstraintLayout>
data class PageVideoEpoxyModel(
    val videoUrl: String,
):ViewBindingKotlinModel<ActivityPageVideoBinding>(R.layout.activity_page_video){

    override fun ActivityPageVideoBinding.bind() {
        videoView.setVideoURI(Uri.parse(videoUrl))
        videoView.setOnPreparedListener {

            val mediaController = MediaController(videoView.context)
            mediaController.requestFocus()

            val parent = mediaController.parent as ViewGroup
                parent.removeView(mediaController)

            frameView.addView(mediaController)

            mediaController.setMediaPlayer(videoView)
            mediaController.isEnabled = true

            videoView.setMediaController(mediaController)

            mediaController.setAnchorView(videoView)

            videoView.start()
            mediaController.show(0)
        }
    }
}
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content">

<VideoView
    android:id="@+id/videoView"
    android:layout_width="wrap_content"
    android:layout_height="210dp"
    android:layout_marginTop="16dp"
    android:clickable="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<FrameLayout
    android:id="@+id/frameView"
    android:layout_width="@id/videoView"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:layout_constraintStart_toStartOf="@id/videoView"
    app:layout_constraintEnd_toEndOf="@id/videoView"
    app:layout_constraintBottom_toBottomOf="@id/videoView"/>

</androidx.constraintlayout.widget.ConstraintLayout>
data class PageVideoEpoxyModel(
    val videoUrl: String,
):ViewBindingKotlinModel<ActivityPageVideoBinding>(R.layout.activity_page_video){

    override fun ActivityPageVideoBinding.bind() {
        videoView.setVideoURI(Uri.parse(videoUrl))
        videoView.setOnPreparedListener {

            val mediaController = MediaController(videoView.context)
            mediaController.requestFocus()

            val parent = mediaController.parent as ViewGroup
                parent.removeView(mediaController)

            frameView.addView(mediaController)

            mediaController.setMediaPlayer(videoView)
            mediaController.isEnabled = true

            videoView.setMediaController(mediaController)

            mediaController.setAnchorView(videoView)

            videoView.start()
            mediaController.show(0)
        }
    }
}

Can't pass params in URL to react component

copy iconCopydownload iconDownload
< Route path = { `/epoxy` } component = { SingleProjectPage } />  
< Route path = { `/project/epoxy` } component = { SingleProjectPage } />  
-----------------------
< Route path = { `/epoxy` } component = { SingleProjectPage } />  
< Route path = { `/project/epoxy` } component = { SingleProjectPage } />  

Why does my function run before componentDidMount

copy iconCopydownload iconDownload
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);
categoriesStyled.push(
    <SubMenu label={category.name}>
        {category.children.forEach(element => AddMenu(element)}
    </SubMenu>)
-----------------------
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);
categoriesStyled.push(
    <SubMenu label={category.name}>
        {category.children.forEach(element => AddMenu(element)}
    </SubMenu>)

In the code, the type of the lambda is mismatched, how does it work?

copy iconCopydownload iconDownload
fun curPos(Int): EpoxyRoutineModel_
fun listener((Int) -> Unit): EpoxyRoutineModel_
-----------------------
fun curPos(Int): EpoxyRoutineModel_
fun listener((Int) -> Unit): EpoxyRoutineModel_

Increment a cell value in a dataframe by the amount written in another dataframe cell

copy iconCopydownload iconDownload
# get values to increment from source DF
InventaireDF = pd.merge(InventaireDF, RecetteDF[['Codes interne', 'Quantite requise']], how='left', on='Codes interne')

# when source does not contain matching key, the increment value will be NaN; set it to zero instead
InventaireDF['Quantite requise'].fillna(0.0, inplace=True)

# convert relevant columns to dtype float
InventaireDF['Quantite requise'] = InventaireDF['Quantite requise'].astype(float)
InventaireDF['Quantite Reserver'] = InventaireDF['Quantite Reserver'].astype(float)

# perform the increment
InventaireDF['Quantite Reserver'] += InventaireDF['Quantite requise']

# drop the column with the increment because we don't need it anymore
InventaireDF.drop(columns=['Quantite requise'], inplace=True)

Inserting into table using values from another table involving a unique filed

copy iconCopydownload iconDownload
insert into tbl1 (itemNo, itemDescription)
    select itemNo & 'd', itemDescription
    from tbl2;

gl.h: No such file or directory, I can't seem to quell this error

copy iconCopydownload iconDownload
sudo apt-get install build-essential libgl1-mesa-dev

Simple TextView not showing in Airbnb Epoxy

copy iconCopydownload iconDownload
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="SIMPLE TITLE"
        app:layout_constraintBaseline_toBaselineOf="@+id/more_textview"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/more_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="More"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <com.airbnb.epoxy.EpoxyRecyclerView
        android:id="@+id/main_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rv = findViewById<EpoxyRecyclerView>(R.id.main_recyclerview)
        val controller  = MyController()
        controller.setData(listOf("test","test2", "test3"),true)
        rv.adapter = controller.adapter
    }
}
class MyController : Typed2EpoxyController<List<String>,Boolean>() {
    override fun buildModels(data1: List<String>, data2: Boolean) {
       data1.forEachIndexed { index, s ->
           MyTextViewModel_().id(index).titleText(s).addTo(this)
       }
    }
}
@EpoxyModelClass(layout = R.layout.textview_row)
abstract class MyTextViewModel(): EpoxyModelWithHolder<MyTextViewModel.VH>() {
    @EpoxyAttribute
    var titleText: String = "Default Title Text"

    override fun bind(holder: VH) {
        super.bind(holder)
        holder.titleTextView.text= titleText
    }

    class VH : EpoxyHolder() {
        lateinit var titleTextView: TextView
        override fun bindView(itemView: View) {
            titleTextView = itemView.findViewById(R.id.title_textview)
        }
    }
} 
-----------------------
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="SIMPLE TITLE"
        app:layout_constraintBaseline_toBaselineOf="@+id/more_textview"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/more_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="More"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <com.airbnb.epoxy.EpoxyRecyclerView
        android:id="@+id/main_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rv = findViewById<EpoxyRecyclerView>(R.id.main_recyclerview)
        val controller  = MyController()
        controller.setData(listOf("test","test2", "test3"),true)
        rv.adapter = controller.adapter
    }
}
class MyController : Typed2EpoxyController<List<String>,Boolean>() {
    override fun buildModels(data1: List<String>, data2: Boolean) {
       data1.forEachIndexed { index, s ->
           MyTextViewModel_().id(index).titleText(s).addTo(this)
       }
    }
}
@EpoxyModelClass(layout = R.layout.textview_row)
abstract class MyTextViewModel(): EpoxyModelWithHolder<MyTextViewModel.VH>() {
    @EpoxyAttribute
    var titleText: String = "Default Title Text"

    override fun bind(holder: VH) {
        super.bind(holder)
        holder.titleTextView.text= titleText
    }

    class VH : EpoxyHolder() {
        lateinit var titleTextView: TextView
        override fun bindView(itemView: View) {
            titleTextView = itemView.findViewById(R.id.title_textview)
        }
    }
} 
-----------------------
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="SIMPLE TITLE"
        app:layout_constraintBaseline_toBaselineOf="@+id/more_textview"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/more_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="More"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <com.airbnb.epoxy.EpoxyRecyclerView
        android:id="@+id/main_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rv = findViewById<EpoxyRecyclerView>(R.id.main_recyclerview)
        val controller  = MyController()
        controller.setData(listOf("test","test2", "test3"),true)
        rv.adapter = controller.adapter
    }
}
class MyController : Typed2EpoxyController<List<String>,Boolean>() {
    override fun buildModels(data1: List<String>, data2: Boolean) {
       data1.forEachIndexed { index, s ->
           MyTextViewModel_().id(index).titleText(s).addTo(this)
       }
    }
}
@EpoxyModelClass(layout = R.layout.textview_row)
abstract class MyTextViewModel(): EpoxyModelWithHolder<MyTextViewModel.VH>() {
    @EpoxyAttribute
    var titleText: String = "Default Title Text"

    override fun bind(holder: VH) {
        super.bind(holder)
        holder.titleTextView.text= titleText
    }

    class VH : EpoxyHolder() {
        lateinit var titleTextView: TextView
        override fun bindView(itemView: View) {
            titleTextView = itemView.findViewById(R.id.title_textview)
        }
    }
} 
-----------------------
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="SIMPLE TITLE"
        app:layout_constraintBaseline_toBaselineOf="@+id/more_textview"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/more_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="More"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <com.airbnb.epoxy.EpoxyRecyclerView
        android:id="@+id/main_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rv = findViewById<EpoxyRecyclerView>(R.id.main_recyclerview)
        val controller  = MyController()
        controller.setData(listOf("test","test2", "test3"),true)
        rv.adapter = controller.adapter
    }
}
class MyController : Typed2EpoxyController<List<String>,Boolean>() {
    override fun buildModels(data1: List<String>, data2: Boolean) {
       data1.forEachIndexed { index, s ->
           MyTextViewModel_().id(index).titleText(s).addTo(this)
       }
    }
}
@EpoxyModelClass(layout = R.layout.textview_row)
abstract class MyTextViewModel(): EpoxyModelWithHolder<MyTextViewModel.VH>() {
    @EpoxyAttribute
    var titleText: String = "Default Title Text"

    override fun bind(holder: VH) {
        super.bind(holder)
        holder.titleTextView.text= titleText
    }

    class VH : EpoxyHolder() {
        lateinit var titleTextView: TextView
        override fun bindView(itemView: View) {
            titleTextView = itemView.findViewById(R.id.title_textview)
        }
    }
} 
-----------------------
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="SIMPLE TITLE"
        app:layout_constraintBaseline_toBaselineOf="@+id/more_textview"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/more_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="More"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    tools:context=".MainActivity">

    <com.airbnb.epoxy.EpoxyRecyclerView
        android:id="@+id/main_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val rv = findViewById<EpoxyRecyclerView>(R.id.main_recyclerview)
        val controller  = MyController()
        controller.setData(listOf("test","test2", "test3"),true)
        rv.adapter = controller.adapter
    }
}
class MyController : Typed2EpoxyController<List<String>,Boolean>() {
    override fun buildModels(data1: List<String>, data2: Boolean) {
       data1.forEachIndexed { index, s ->
           MyTextViewModel_().id(index).titleText(s).addTo(this)
       }
    }
}
@EpoxyModelClass(layout = R.layout.textview_row)
abstract class MyTextViewModel(): EpoxyModelWithHolder<MyTextViewModel.VH>() {
    @EpoxyAttribute
    var titleText: String = "Default Title Text"

    override fun bind(holder: VH) {
        super.bind(holder)
        holder.titleTextView.text= titleText
    }

    class VH : EpoxyHolder() {
        lateinit var titleTextView: TextView
        override fun bindView(itemView: View) {
            titleTextView = itemView.findViewById(R.id.title_textview)
        }
    }
} 

Why is my for loop not pulling the correct data from my array of objects?

copy iconCopydownload iconDownload
// on PORTFOLIO page, this code loops through ALL PICTURES WITHIN div's
    for (i=0;i<allPictures.length;i++) {

    $imgNum = allPictures[i].number;
    $imgTitle = allPictures[i].name;
    $imgDesc = allPictures[i].desc;

    $newDIV = $('<div>');
        $newDIV.addClass("image-holder");
        $newDIV.attr("onclick","toggleView()");      
        $newDIV.attr("data-imagePath",`images/portfolio/img\ (${$imgNum}).jpg`);
        $newDIV.attr("data-imageTitle",$imgTitle);

        $newDIV.attr("data-imgDesc",$imgDesc);


    // create newPICTURE
    $newPICTURE = $('<img>');
        //Change the src using jQuery's attr method + the allPics number
        $newPICTURE.attr("src", `images/portfolio/img\ (${$imgNum}).jpg`);

        // append PIC to DIV
        $newDIV.append($newPICTURE);

    // creating infoOverlay
    $newOVERLAY = $('<div>');
        $newOVERLAY.addClass("info-overlay");

        $newOVERLAY.text(allPictures[i].name);

        $newDIV.append($newOVERLAY);

        // THIS is the function I'd like to change all the relevant info for the toggled fullscreen overlay
}
    function toggleView() {
        console.log('toggle.js connected')
    
    // display OVERLAY
    var viewerOverlay = document.getElementById('viewerOverlay');
    
    if (viewerOverlay.style.display === 'none') {


   imageData=$(this).data('imagePath');
   imageTitleData=$(this).data('imageTitle');
   imageDescData=$(this).data('imgDesc');
   $('#centerpiece-img').attr('src',imageData)
   $('#centerpiece-title').text(imageTitleData);
    $('#centerpiece-desc').text(imageDescData);
        viewerOverlay.style.display = "block";
    } else {
        viewerOverlay.style.display = "none";
    }
   }
-----------------------
// on PORTFOLIO page, this code loops through ALL PICTURES WITHIN div's
    for (i=0;i<allPictures.length;i++) {

    $imgNum = allPictures[i].number;
    $imgTitle = allPictures[i].name;
    $imgDesc = allPictures[i].desc;

    $newDIV = $('<div>');
        $newDIV.addClass("image-holder");
        $newDIV.attr("onclick","toggleView()");      
        $newDIV.attr("data-imagePath",`images/portfolio/img\ (${$imgNum}).jpg`);
        $newDIV.attr("data-imageTitle",$imgTitle);

        $newDIV.attr("data-imgDesc",$imgDesc);


    // create newPICTURE
    $newPICTURE = $('<img>');
        //Change the src using jQuery's attr method + the allPics number
        $newPICTURE.attr("src", `images/portfolio/img\ (${$imgNum}).jpg`);

        // append PIC to DIV
        $newDIV.append($newPICTURE);

    // creating infoOverlay
    $newOVERLAY = $('<div>');
        $newOVERLAY.addClass("info-overlay");

        $newOVERLAY.text(allPictures[i].name);

        $newDIV.append($newOVERLAY);

        // THIS is the function I'd like to change all the relevant info for the toggled fullscreen overlay
}
    function toggleView() {
        console.log('toggle.js connected')
    
    // display OVERLAY
    var viewerOverlay = document.getElementById('viewerOverlay');
    
    if (viewerOverlay.style.display === 'none') {


   imageData=$(this).data('imagePath');
   imageTitleData=$(this).data('imageTitle');
   imageDescData=$(this).data('imgDesc');
   $('#centerpiece-img').attr('src',imageData)
   $('#centerpiece-title').text(imageTitleData);
    $('#centerpiece-desc').text(imageDescData);
        viewerOverlay.style.display = "block";
    } else {
        viewerOverlay.style.display = "none";
    }
   }
-----------------------
for (i=0;i<allPictures.length;i++) {

    $imgNum = allPictures[i].number;
    $imgTitle = allPictures[i].name;
    $imgDesc = allPictures[i].desc;
//adding image description as data-attr

    $newDIV = $(`<div data-imgnumber='${$imgNum}' data-desc='${$imgDesc}'  data-title='${$imgTitle}'>`); // Adding current iteration number
        $newDIV.addClass("image-holder");
        $newDIV.attr("onclick","toggleView()");

    // create newPICTURE
    $newPICTURE = $('<img>');
        //Change the src using jQuery's attr method + the allPics number
        $newPICTURE.attr("src", `images/portfolio/img\ (${$imgNum}).jpg`);

        // append PIC to DIV
        $newDIV.append($newPICTURE);

    // creating infoOverlay
    $newOVERLAY = $('<div>');
        $newOVERLAY.addClass("info-overlay");

        $newOVERLAY.text(allPictures[i].name);

        $newDIV.append($newOVERLAY);

        // THIS is the function I'd like to change all the relevant info for the toggled fullscreen overlay

/*
As are showing selected image data in toggleView function so, REMOVE THIS CODE
        $newDIV.click(function(){
            $('#centerpiece-img').attr('src',`images/portfolio/img\ (${$imgNum}).jpg`)
            $('#centerpiece-title').text($imgTitle);
            $('#centerpiece-desc').text($imgDesc);
        });
*/
    // append DIV to container
    $('#art-display').append($newDIV);

}
function toggleView() {
    console.log('toggle.js connected')

    // display OVERLAY
    var viewerOverlay = document.getElementById('viewerOverlay');

    if (viewerOverlay.style.display === 'none') {

    // Here we are updating selected image data in bigger div
        $('#centerpiece-img').attr('src',`images/portfolio/img\ (${this.getAttribute("data-imgnumber")}).jpg`)
        $('#centerpiece-title').text(this.getAttribute("data-title"));
        $('#centerpiece-desc').text(this.getAttribute("data-desc"));


        viewerOverlay.style.display = "block";
    } else {
        viewerOverlay.style.display = "none";
    }
}
-----------------------
for (i=0;i<allPictures.length;i++) {

    $imgNum = allPictures[i].number;
    $imgTitle = allPictures[i].name;
    $imgDesc = allPictures[i].desc;
//adding image description as data-attr

    $newDIV = $(`<div data-imgnumber='${$imgNum}' data-desc='${$imgDesc}'  data-title='${$imgTitle}'>`); // Adding current iteration number
        $newDIV.addClass("image-holder");
        $newDIV.attr("onclick","toggleView()");

    // create newPICTURE
    $newPICTURE = $('<img>');
        //Change the src using jQuery's attr method + the allPics number
        $newPICTURE.attr("src", `images/portfolio/img\ (${$imgNum}).jpg`);

        // append PIC to DIV
        $newDIV.append($newPICTURE);

    // creating infoOverlay
    $newOVERLAY = $('<div>');
        $newOVERLAY.addClass("info-overlay");

        $newOVERLAY.text(allPictures[i].name);

        $newDIV.append($newOVERLAY);

        // THIS is the function I'd like to change all the relevant info for the toggled fullscreen overlay

/*
As are showing selected image data in toggleView function so, REMOVE THIS CODE
        $newDIV.click(function(){
            $('#centerpiece-img').attr('src',`images/portfolio/img\ (${$imgNum}).jpg`)
            $('#centerpiece-title').text($imgTitle);
            $('#centerpiece-desc').text($imgDesc);
        });
*/
    // append DIV to container
    $('#art-display').append($newDIV);

}
function toggleView() {
    console.log('toggle.js connected')

    // display OVERLAY
    var viewerOverlay = document.getElementById('viewerOverlay');

    if (viewerOverlay.style.display === 'none') {

    // Here we are updating selected image data in bigger div
        $('#centerpiece-img').attr('src',`images/portfolio/img\ (${this.getAttribute("data-imgnumber")}).jpg`)
        $('#centerpiece-title').text(this.getAttribute("data-title"));
        $('#centerpiece-desc').text(this.getAttribute("data-desc"));


        viewerOverlay.style.display = "block";
    } else {
        viewerOverlay.style.display = "none";
    }
}

How to get Item Position in EpoxyModelWithHolder?

copy iconCopydownload iconDownload
@EpoxyAttribute
Integer position;
public EpoxyModel<?> buildItemModel(int i, yourmodel) {

return model()_.id(i).position(i);

}
-----------------------
@EpoxyAttribute
Integer position;
public EpoxyModel<?> buildItemModel(int i, yourmodel) {

return model()_.id(i).position(i);

}

Community Discussions

Trending Discussions on epoxy
  • Python: Program Outputs Different Values Every Time It Runs
  • MediaController for VideoView inside BottomSheetDialog is hidden behind the BottomSheetDialog
  • Can't pass params in URL to react component
  • Why does my function run before componentDidMount
  • The problem that the data of RecyclerView changes randomly
  • How to fix java.lang.AbstractMethodError in android?
  • In the code, the type of the lambda is mismatched, how does it work?
  • Is the automatic comparison in the Epoxy library based on DiffUtil?
  • Navgraph direction build fail
  • Increment a cell value in a dataframe by the amount written in another dataframe cell
Trending Discussions on epoxy

QUESTION

Python: Program Outputs Different Values Every Time It Runs

Asked 2022-Apr-17 at 07:58

This problem has been occurring for a couple months now with any project that uses complicated sets of equations (such as for composite mechanics analysis or thrust/fluid flow analysis). Simple calculations, iterative methods, and Numpy matrices seem to work fine on their own though. And just to be sure, I have tried completely uninstalling and reinstalling Python and Pycharm, but the same problem persists.

For the past couple months, any code that incorporates more complex mathematics, such as those described above, will output different values despite all input values and calculations being constant. The different codes have no means of variation or randomness. I've noticed these incorrect outputs usually occur within arrays/matrices, and I can tell the output values are incorrect because the expected numbers are instead absurdly large.

For example, an element within a matrix is expected to be 5.197e+7, but instead, the code outputs 3.322e+257 for that same element. However, upon running the code a second time, the code produces an output of 2.822e+204 for the exact same element. Only upon the third run does the code output the correct value for that element, which is 5.197e+7. This process can take anywhere from 1 to 15 separate runs for the same, unchanging code in order to output the correct value.

Another interesting aspect is that the calculations I am coding usually require multiple iterations of said code. However, even though I am resetting the arrays that temporarily save all values (other than final values that no longer affect the calculations), whatever is causing these "errors is being carried through the code until the end of the iterations. To my understanding, this shouldn't be the case since, at the end of an iteration, the code is setting all values, other than the known initial values, to 0 and recalculating. This would mean that the code is continuously making the same error.

Below are some examples of the program's expected output vs actual outputs.

Expected Output for First Iteration

NM = [[ 2.57939977e+04]
 [ 3.03926820e+04]
 [-3.55271368e-13]
 [ 1.00000000e+00]
 [ 1.00000000e+00]
 [ 2.60208521e-16]]
[A] =
 [[1.50155575e+08 4.45004838e+07 0.00000000e+00]
 [4.44974703e+07 1.07288531e+08 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 5.19662175e+07]]
[D] =
 [[60.771  7.663  4.019]
 [ 7.659 12.322  4.019]
 [ 4.019  4.019  9.567]]

1st Attempt: Actual Output for First Iteration

NM = 
[[2.57939977e+004]
 [7.26576487e+225]
 [2.35904846e+253]
 [7.25895469e+242]
 [1.18107381e+291]
 [1.61312569e+291]]
[A] =
 [[1.50155575e+08 4.45004838e+07 0.00000000e+00]
 [4.44974703e+07 1.07288531e+08 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 5.19662175e+07]]
[D] =
 [[60.771  7.663  4.019]
 [ 7.659 12.322  4.019]
 [ 4.019  4.019  9.567]]

2nd Try: First Iteration

NM = [[2.18479897e+158]
 [3.03926820e+004]
 [1.62552246e+034]
 [1.00000121e+000]
 [1.07935186e+000]
 [2.60208521e-016]]
[A] =
 [[1.50155575e+08 4.45004838e+07 0.00000000e+00]
 [4.44974703e+07 1.07288531e+08 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 5.19662175e+07]]
[D] =
 [[60.771  7.663  4.019]
 [ 7.659 12.322  4.019]
 [ 4.019  4.019  9.567]]

3rd Try: First Iteration

NM = [[ 2.57939977e+004]
 [ 3.03926820e+004]
 [-3.55271368e-013]
 [ 4.54183603e+225]
 [ 6.28847407e+094]
 [ 2.60208521e-016]]
[A] =
 [[1.50155575e+08 4.45004838e+07 0.00000000e+00]
 [4.44974703e+07 1.07288531e+08 0.00000000e+00]
 [0.00000000e+00 0.00000000e+00 5.19662175e+07]]
[D] =
 [[60.771  7.663  4.019]
 [ 7.659 12.322  4.019]
 [ 4.019  4.019  9.567]]

4th Try: First Iteration

NM = [[ 2.57939977e+04]
 [ 3.03926820e+04]
 [-3.55271368e-13]
 [ 1.00000000e+00]
 [ 1.00000000e+00]
 [ 2.60208521e-16]]
[A] =
 [[1.50155575e+008 4.45004838e+007 0.00000000e+000]
 [4.44974703e+007 1.07288531e+008 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 2.39203287e+198]]
[D] =
 [[60.771  7.663  4.019]
 [ 7.659 12.322  4.019]
 [ 4.019  4.019  9.567]]

As can be seen, the fourth iteration finally produced the correct NM matrix; however, the [A] matrix goes from having the correct values to an incorrect A[3][3] element. However, after a few more attempts at re-running the program, the program finally outputs all three correct matrices. As stated before, this can take anywhere between 1 and 15 attempts.

At this point, I'm lost with what could be causing these issues. I've given my code to others to run on their own computers and the program seems to have no issue. Any advice on how I can resolve this would be greatly appreciated. The full code and instructions for viewing the first iteration is below. If anything else is needed, please let me know.

To Re-create

  1. Run the code making sure C.stress_critical_loads() is commented out and C.tsai_wu() is not commented out in the main method.
  2. After running, scroll to the top of the output and then scroll down until the first instances of NM, [A], [B], and [D].
  3. If you see an error message in the middle of the output code, it's because the NM matrix is wrong. The error message goes away when the NM matrix is correct. The program also runs despite the error message.

Thanks again for any advice anyone can give.

import numpy as np
import math
from tabulate import *


def stress_transformation_matrix(x):
    # This function calculates the stress transformation
    # matrix given an input value for the ply angle
    return np.array([
        [math.cos(x)**2, math.sin(x)**2, 2*math.sin(x)*math.cos(x)],
        [math.sin(x)**2, math.cos(x)**2, -2*math.sin(x)*math.cos(x)],
        [-math.sin(x)*math.cos(x), math.sin(x)*math.cos(x), math.cos(x)**2 - math.sin(x)**2]
    ])


def strain_transformation_matrix(x):
    # This function calculates the strain transformation
    # matrix given an input value for the ply angle
    return np.array([
        [math.cos(x)**2, math.sin(x)**2, math.sin(x)*math.cos(x)],
        [math.sin(x)**2, math.cos(x)**2, -math.sin(x)*math.cos(x)],
        [-2*math.sin(x)*math.cos(x), 2*math.sin(x)*math.cos(x), math.cos(x)**2-math.sin(x)**2]
    ])


def local_stiffness_matrix(E11, E22, G12, v12, v21):
    # This function calculates the local stiffness
    # given the material properties at each ply
    return np.array([
        [E11 / (1 - v12 * v21), v21 * E11 / (1 - v12 * v21), 0],
        [v12 * E22 / (1 - v12 * v21), E22 / (1 - v12 * v21), 0],
        [0, 0, G12]
    ])


class Properties:
    def __init__(self):
        # Material Properties
        self.M_E11 = np.array([181E9, 204E9, 138E9, 38.6E9, 76E9])
        self.M_E22 = np.array([10.3E9, 18.5E9, 9E9, 8.3E9, 5.5E9])
        self.M_G12 = np.array([7.17E9, 5.59E9, 7.1E9, 4.14E9, 2.3E9])
        self.M_v12 = np.array([0.280, 0.230, 0.300, 0.260, 0.340])
        self.M_v21 = np.array([0.016, 0.021, 0.019, 0.056, 0.33])
        self.E11 = np.array([])
        self.E22 = np.array([])
        self.G12 = np.array([])
        self.v12 = np.array([])
        self.v21 = np.array([])

        # Ultimate Failure Strengths
        self.P_SLT = np.array([1500E6, 1260E6, 1447E6, 1062E6, 1400E6])
        self.P_SLc = np.array([1500E6, 2499E6, 1447E6, 610E6, 235E6])
        self.P_STt = np.array([40E6, 61E6, 52E6, 31E6, 12E6])
        self.P_STc = np.array([246E6, 202E6, 206E6, 118E6, 53E6])
        self.P_SLTs = np.array([68E6, 67E6, 93E6, 72E6, 34E6])
        self.SLT = np.array([])
        self.SLc = np.array([])
        self.STt = np.array([])
        self.STc = np.array([])
        self.SLTs = np.array([])

        # Ultimate Failure Strains
        self.P_epsLtf = np.array([1.087E-2, 0, 1.380E-2, 2.807E-2, 0])
        self.P_epsLcf = np.array([0.652E-2, 0, 1.175E-2, 1.754E-2, 0])
        self.P_epsCtf = np.array([0.245E-2, 0, 0.436E-2, 0.456E-2, 0])
        self.P_epsCcf = np.array([1.818E-2, 0, 2E-2, 1.2E-2, 0])
        self.P_epsLTs = np.array([4E-2, 0, 2E-2, 4E-2, 0])
        self.epsLtf = np.array([])
        self.epsLcf = np.array([])
        self.epsCtf = np.array([])
        self.epsCcf = np.array([])
        self.epsLTs = np.array([])

        # Strength Ratios for stress and strain
        self.R11_s = np.array([])
        self.R22_s = np.array([])
        self.R12_s = np.array([])
        self.R11_e = np.array([])
        self.R22_e = np.array([])
        self.R12_e = np.array([])
        self.R_crit_s = np.array([])
        self.R_crit_e = np.array([])

        # Tsai-Wu Coefficients
        self.F11 = np.array([])
        self.F22 = np.array([])
        self.F12 = np.array([])
        self.F66 = np.array([])
        self.F1 = np.array([])
        self.F2 = np.array([])

        # Stiffness and Transformation Matrices
        self.Q = np.array([])
        self.Q_hat = np.array([])
        self.T = np.array([])
        self.T_hat = np.array([])

        # ABD Matrices
        self.A = np.empty(shape=(3, 3))
        self.B = np.empty(shape=(3, 3))
        self.D = np.empty(shape=(3, 3))
        self.ABD = np.empty(shape=(6, 6))

        # Laminate Loads
        self.Nxx = 200
        self.Nyy = 200
        self.Nxy = 0
        self.Mxx = 1
        self.Myy = 1
        self.Mxy = 0
        self.N_mech = np.array([])
        self.M_mech = np.array([])
        self.NT = np.empty(shape=(3, 1))
        self.MT = np.empty(shape=(3, 1))
        self.NM = np.array([])
        self.Nxx_cs = np.array([])
        self.Mxx_cs = np.array([])
        self.Nxx_ce = np.array([])
        self.Mxx_ce = np.array([])

        # Mid-plane Strains and Curvatures
        self.e0_k = np.array([])
        self.e0 = np.array([])
        self.k0 = np.array([])

        # Stresses and Strains
        self.sg = np.array([])      # global stress
        self.sl = np.array([])      # local stress
        self.eg = np.array([])      # global strain
        self.el = np.array([])      # local strain

        # Ply Orientations
        self.lam = None             # total laminate thickness
        self.z_lam = np.array([])   # laminate thickness from to pto bottom
        self.z_m = np.array([])     # mid-plane laminate thickness

        # Table and Material Properties
        self.mat = np.array([])
        self.mat_list = np.array([])

        # Total Ply Failure
        self.Beta = np.array([])

        # Angle at Each Ply (deg)
        self.angle = np.array([0, 0, 45, 45, -45, -45, 90, 90, -45, -45, 45, 45, 0, 0])
        self.a = np.array([])
        # Thickness at Each Ply (m)
        self.z = np.array([0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3,
                           0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3, 0.125E-3])
        # Number of Ply
        self.n = self.angle.size
        # Material at Each Ply
        self.m = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        # 0: T300/5208
        # 1: B(4) 5505
        # 2: AS4/3501
        # 3: Scotchply 1002
        # 4: Kevlar49/Epoxy

        # Thermal Properties
        self.a1 = -0.018E-6     # longitudinal thermal expansion, deg. C
        self.a2 = 24.3E-6       # transverse thermal expansion, deg. C
        self.a3 = 0             # shear thermal expansion, deg. C
        self.dT = 100           # change in temperature, deg. C

    def ply_angle(self):
        a = np.array([])
        for i in range(self.n):
            a = np.append(a, math.radians(self.angle[i]))
        self.a = a

    def ply(self):
        # set total laminate ply failure array
        self.Beta = np.full(self.n, 1)

        # Determine the thickness of each ply
        self.lam = sum(self.z)
        print('Total Thickness =', self.lam)
        for i in range(self.n):
            self.z_lam = np.append(self.z_lam, -self.lam / 2 + (i + 1) * self.z[i])
        print('Top-Bottom =', self.z_lam)
        for i in range(self.n):
            self.z_m = np.append(self.z_m, -self.lam / 2 - self.z[i] / 2 + (i + 1) * self.z[i])
        print('Mid-plane =', self.z_m)

    def material(self):
        for i in range(self.n):
            m = self.m[i]
            # Material Properties
            self.E11 = np.append(self.E11, self.M_E11[m])
            self.E22 = np.append(self.E22, self.M_E22[m])
            self.G12 = np.append(self.G12, self.M_G12[m])
            self.v12 = np.append(self.v12, self.M_v12[m])
            self.v21 = np.append(self.v21, self.M_v21[m])
            self.mat_list = np.append(self.mat_list, m)
            # Ultimate Failure Strengths
            self.SLT = np.append(self.SLT, self.P_SLT[m])
            self.SLc = np.append(self.STc, self.P_SLc[m])
            self.STt = np.append(self.STt, self.P_STt[m])
            self.STc = np.append(self.STc, self.P_STc[m])
            self.SLTs = np.append(self.SLTs, self.P_SLTs[m])
            # Ultimate Failure Strains
            self.epsLtf = np.append(self.epsLtf, self.P_epsLtf[m])
            self.epsLcf = np.append(self.epsLcf, self.P_epsLcf[m])
            self.epsCtf = np.append(self.epsCtf, self.P_epsCtf[m])
            self.epsCcf = np.append(self.epsCcf, self.P_epsCcf[m])
            self.epsLTs = np.append(self.epsLTs, self.P_epsLTs[m])
            # Tsai-Wu Coefficients
            self.F11 = np.append(self.F11, 1 / (self.P_SLT[m] * self.P_SLc[m]))
            self.F22 = np.append(self.F22, 1 / (self.P_STt[m] * self.P_STc[m]))
            self.F12 = np.append(self.F12, -math.sqrt(self.F11[i] * self.F22[i]) / 2)
            self.F66 = np.append(self.F66, 1 / self.P_SLTs[m] ** 2)
            self.F1 = np.append(self.F1, 1 / self.P_SLT[m] - 1 / self.P_SLc[m])
            self.F2 = np.append(self.F2, 1 / self.P_STt[m] - 1 / self.P_STc[m])

            if m == 0: self.mat = np.append(self.mat, 'T300/5208')
            elif m == 1: self.mat = np.append(self.mat, 'B(4)/5505')
            elif m == 2: self.mat = np.append(self.mat, 'AS4/3501')
            elif m == 3: self.mat = np.append(self.mat, 'Scotchply 1002')
            else: self.mat = np.append(self.mat, 'Kevlar49/Epoxy')
        print('F11 = ', self.F11)
        print('F22 =', self.F22)
        print('F12 =', self.F12)
        print('F66 =', self.F66)
        print('F1 =', self.F1)
        print('F2 =', self.F2)

    def mechanical_loads(self):
        self.N_mech = np.array([
            [self.Nxx],
            [self.Nyy],
            [self.Nxy]
        ])
        self.M_mech = np.array([
            [self.Mxx],
            [self.Myy],
            [self.Mxy]
        ])

    def local_thermal_coef(self):
        al = np.array([
            [self.a1],
            [self.a2],
            [self.a3]
        ])
        return al

    def material_properties(self):
        # Creates a table for the material properties of each different ply
        mat_list = list(map(int, set(self.mat_list)))
        for i in mat_list:
            data = np.array([[self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i]]])
            Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            print('\nMaterial =', self.mat[i], '(in SI units)')
            print(tabulate(data, headers=['E11', 'E22', 'G12', 'v12', 'v21']))
            print('\nMaterial =', self.mat[i], '(in Pa)')
            print('[Q] =\n', np.round(Q, 3))
            print('')

    def table(self):
        # Creates a table of ply number, thickness, orientation and material
        table = np.array([])
        for i in range(self.n):
            data = np.array([[i+1, self.mat[i], self.z[i], math.degrees(self.a[i])]])
            if i == 0:
                table = np.append(table, data)
            else:
                table = np.vstack([table, data])
        print(tabulate(table, headers=['Lamina', 'Material', 'Thickness', 'Orientation']))


class Calculations(Properties):
    def __init__(self):
        super().__init__()
        self.NM = np.array([])          # Loads and Moments
        self.e0_k = np.array([])        # Mid-plane strains and curvatures
        self.fail_order = np.array([])  # Ply order of failure

    def a_matrix(self):
        for i in range(self.n):
            T = stress_transformation_matrix(self.a[i])
            T_hat = strain_transformation_matrix(self.a[i])
            if self.Beta[i] == 1:
                Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            else:
                Q = np.array([
                    [0, 0, 0],
                    [0, 0, 0],
                    [0, 0, 0]
                ])

            Q_hat = np.matmul(np.linalg.inv(T), Q)
            Q_hat = np.matmul(Q_hat, T_hat)
            A = Q_hat * (self.z_lam[i] - (self.z_lam[i] - self.z[i]))
            self.A = np.add(self.A, A)
            # print('\nLamina', i, '\t\u03B8 =', math.degrees(self.a[i]), 't =', self.z[i], 'Material =', self.mat[i-1])
            # print('[Q\u0302] =\n', np.round(Q_hat, 3))
        print('\nLaminate Stiffness Matrices\n[A] =\n', np.round(self.A, 3))

    def b_matrix(self):
        for i in range(self.n):
            T = stress_transformation_matrix(self.a[i])
            T_hat = strain_transformation_matrix(self.a[i])
            if self.Beta[i] == 1:
                Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            else:
                Q = np.array([
                    [0, 0, 0],
                    [0, 0, 0],
                    [0, 0, 0]
                ])

            Q_hat = np.matmul(np.linalg.inv(T), Q)
            Q_hat = np.matmul(Q_hat, T_hat)
            B = Q_hat * (self.z_lam[i] ** 2 - (self.z_lam[i] - self.z[i]) ** 2)
            self.B = np.add(self.B, B)
        self.B /= 2
        print('\n[B] =\n', np.round(self.B, 3))

    def d_matrix(self):
        for i in range(self.n):
            T = stress_transformation_matrix(self.a[i])
            T_hat = strain_transformation_matrix(self.a[i])
            if self.Beta[i] == 1:
                Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            else:
                Q = np.array([
                    [0, 0, 0],
                    [0, 0, 0],
                    [0, 0, 0]
                ])

            Q_hat = np.matmul(np.linalg.inv(T), Q)
            Q_hat = np.matmul(Q_hat, T_hat)
            D = Q_hat * (self.z_lam[i] ** 3 - (self.z_lam[i] - self.z[i]) ** 3)
            self.D = np.add(self.D, D)
        self.D /= 3
        print('\n[D] =\n', np.round(self.D, 3))

    def matrices_combined(self):
        self.a_matrix()     # call A matrix method
        self.b_matrix()     # call B matrix method
        self.d_matrix()     # call D matrix method

        self.ABD = np.array([
            [np.array(self.A[0][0]), np.array(self.A[0][1]), np.array(self.A[0][2]), np.array(self.B[0][0]), np.array(self.B[0][1]), np.array(self.B[0][2])],
            [np.array(self.A[1][0]), np.array(self.A[1][1]), np.array(self.A[1][2]), np.array(self.B[1][0]), np.array(self.B[1][1]), np.array(self.B[1][2])],
            [np.array(self.A[2][0]), np.array(self.A[2][1]), np.array(self.A[2][2]), np.array(self.B[2][0]), np.array(self.B[2][1]), np.array(self.B[2][2])],
            [np.array(self.B[0][0]), np.array(self.B[0][1]), np.array(self.B[0][2]), np.array(self.D[0][0]), np.array(self.D[0][1]), np.array(self.D[0][2])],
            [np.array(self.B[1][0]), np.array(self.B[1][1]), np.array(self.B[1][2]), np.array(self.D[1][0]), np.array(self.D[1][1]), np.array(self.D[1][2])],
            [np.array(self.B[2][0]), np.array(self.B[2][1]), np.array(self.B[2][2]), np.array(self.D[2][0]), np.array(self.D[2][1]), np.array(self.D[2][2])],
        ])

    def calculated_loads(self):
        self.NM = np.matmul(self.ABD, self.e0_k)
        print('\nResulting Loads and Moments\n', np.round(self.NM, 3))

    def thermal_loads(self):
        al = self.local_thermal_coef()
        for i in range(self.n):
            T = stress_transformation_matrix(self.a[i])
            T_hat = strain_transformation_matrix(self.a[i])
            if self.Beta[i] == 1:
                Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            else:
                Q = np.array([
                    [0, 0, 0],
                    [0, 0, 0],
                    [0, 0, 0]
                ])
            Q_hat = np.matmul(np.linalg.inv(T), Q)
            Q_hat = np.matmul(Q_hat, T_hat)
            ag = np.matmul(np.linalg.inv(T_hat), al)

            NT = np.matmul(Q_hat, ag) * (self.z_lam[i] - (self.z_lam[i] - self.z[i]))
            self.NT = np.add(self.NT, NT)
            MT = np.matmul(Q_hat, ag) * (self.z_lam[i] ** 2 - (self.z_lam[i] - self.z[i]) ** 2)
            self.MT = np.add(self.MT, MT)
        self.NT *= self.dT
        self.MT *= (self.dT / 2)

    def combined_loads(self):
        # Combine the mechanical and thermal loads
        self.mechanical_loads()
        self.thermal_loads()
        N = self.N_mech + self.NT
        M = self.M_mech + self.MT
        self.NM = np.vstack((N, M))
        print('\nNM =', self.NM)

    def calculated_midplane_strains_curvatures(self):
        self.matrices_combined()    # call ABD matrix method
        # self.loads()
        self.e0_k = np.matmul(np.linalg.inv(self.ABD), self.NM)
        # print('\nResulting Mid-Plane Strains and Curvatures\n', self.e0_k)
        self.e0 = np.array([
            self.e0_k[0],
            self.e0_k[1],
            self.e0_k[2]
        ])
        self.k0 = np.array([
            self.e0_k[3],
            self.e0_k[4],
            self.e0_k[5]
        ])

    def calculated_stresses_and_strains(self):
        self.combined_loads()  # call calculated loads method
        self.calculated_midplane_strains_curvatures()   # call mid-plane strains and curvature method
        for i in range(self.n):
            eg = np.array([self.e0 + self.z_m[i] * self.k0])
            if i == 0:
                self.eg = np.array(eg)
            else:
                self.eg = np.append(self.eg, eg, axis=0)
        for i in range(self.n):
            T_hat = strain_transformation_matrix(self.a[i])
            el = np.matrix(np.matmul(T_hat, self.eg[i]))
            if i == 0:
                self.el = np.array(el)
            else:
                self.el = np.append(self.el, el, axis=1)
        # All values of local strains are 1x3 arrays, so
        # each time the strain is needed, the specific
        # array must be selected and then transposed
        self.el = np.transpose(self.el)
        # print('[Local Strain] =', self.el)
        for i in range(self.n):
            Q = local_stiffness_matrix(self.E11[i], self.E22[i], self.G12[i], self.v12[i], self.v21[i])
            sl = np.matrix(np.matmul(Q, np.transpose(np.matrix(self.el[i]))))
            if i == 0:
                self.sl = np.array(sl)
            else:
                self.sl = np.append(self.sl, sl, axis=1)
        # All values of local stress are 1x3 arrays, so
        # each time the stress is needed, the specific
        # array must be selected and then transposed
        self.sl = np.transpose(self.sl)
        print('\n[Local Stress] =\n', self.sl)

    def stress_strength_ratio_11(self):
        for i in range(self.n):
            sl = np.transpose(self.sl[i])
            if float(sl[0]) >= 0:
                self.R11_s = np.append(self.R11_s, self.SLT[i] / float(sl[0]))
            else:
                self.R11_s = np.append(self.R11_s, self.SLc[i] / abs(float(sl[0])))

    def stress_strength_ratio_22(self):
        for i in range(self.n):
            sl = np.transpose(self.sl[i])
            if float(sl[1]) >= 0:
                self.R22_s = np.append(self.R22_s, self.STt[i] / float(sl[1]))
            else:
                self.R22_s = np.append(self.R22_s, self.STc[i] / abs(float(sl[1])))

    def stress_strength_ratio_12(self):
        for i in range(self.n):
            sl = np.transpose(self.sl[i])
            self.R12_s = np.append(self.R12_s, self.SLTs[i] / abs(float(sl[2])))

    def stress_critical_loads(self):
        self.calculated_stresses_and_strains()
        self.stress_strength_ratio_11()     # call R11 method
        self.stress_strength_ratio_22()     # call R22 method
        self.stress_strength_ratio_12()     # call R12 method
        for i in range(self.n):
            R = np.array([
                [self.R11_s[i], self.R22_s[i], self.R12_s[i]]
            ])
            if self.Beta[i] == 1:
                R_crit = np.min(R)
            else:
                R_crit = 9999
            self.R_crit_s = np.append(self.R_crit_s, R_crit)
            self.Nxx_cs = np.append(self.Nxx_cs, R_crit * self.Nxx)
            self.Mxx_cs = np.append(self.Mxx_cs, R_crit * self.Mxx)
        Nxx_c = np.min(self.Nxx_cs)
        N_pos = np.where(self.Nxx_cs == Nxx_c)[0]
        Mxx_c = np.min(self.Mxx_cs)
        self.fail_order = np.append(self.fail_order, N_pos + 1)
        print('\nPly Failure in ply', N_pos + 1)
        print('R_crit =', np.min(self.R_crit_s))
        print('Critical in-plane loading at ply', N_pos + 1, '=', Nxx_c, '')
        print('Critical bending loading at ply', N_pos + 1, '=', Mxx_c, '')
        print('Stress: Nxx_c =', Nxx_c)
        print('Stress: Mxx_c =', Mxx_c)

        Beta = np.full(self.n, 0)
        if not np.array_equal(self.Beta, Beta):
            self.Beta[N_pos] = 0
            print(self.Beta)
            # Reset all values
            self.A = np.zeros(shape=(3, 3))
            self.B = np.zeros(shape=(3, 3))
            self.D = np.zeros(shape=(3, 3))
            self.ABD = np.zeros(shape=(6, 6))
            self.eg = np.zeros([])
            self.el = np.zeros([])
            self.sl = np.zeros([])
            self.NT = np.zeros(shape=(3, 1))
            self.MT = np.zeros(shape=(3, 1))
            self.NM = np.zeros(shape=(6, 1))
            self.R11_s = np.zeros([])
            self.R22_s = np.zeros([])
            self.R12_s = np.zeros([])
            self.R_crit_s = np.zeros([])
            self.Nxx_cs = np.zeros([])
            self.Mxx_cs = np.zeros([])
            # re-run calculations
            if not np.array_equal(self.Beta, Beta):
                self.stress_critical_loads()
            else:
                print('Ply Fail Order =', self.fail_order)

    def tsai_wu(self):
        self.calculated_stresses_and_strains()
        a = np.array([])
        b = np.array([])
        c = np.array([])
        R1 = np.array([])
        R2 = np.array([])
        for i in range(self.n):
            sl = np.transpose(self.sl[i])
            a = np.append(a, self.F11[i] * sl[0] ** 2 + 2 * self.F12[i] * sl[0] * sl[1]
                          + self.F22[i] * sl[1] ** 2 + self.F66[i] * sl[2] ** 2)
            b = np.append(b, self.F1[i] * sl[0] + self.F2[i] * sl[1])
            c = np.append(c, -1)
        for i in range(self.n):
            if self.Beta[i] == 1:
                R1 = np.append(R1, (-b[i] + math.sqrt(b[i]**2 - 4 * a[i] * c[i])) / (2 * a[i]))
                R2 = np.append(R2, (-b[i] - math.sqrt(b[i]**2 - 4 * a[i] * c[i])) / (2 * a[i]))
            else:
                R1 = np.append(R1, 9999)
                R2 = np.append(R2, -9999)
        R_crit = np.min(R1)
        R_crit_pos = np.where(R1 == R_crit)[0]
        # print('R1 =', R1)
        # print('R2 =', R2)
        print('\nR_cr at ply', R_crit_pos + 1, '=', R_crit, '')
        self.fail_order = np.append(self.fail_order, R_crit_pos + 1)

        NTW_xxc = R_crit * self.Nxx
        MTW_xxc = R_crit * self.Mxx
        print('N_xx,cr for ply', R_crit_pos + 1, '=', NTW_xxc)
        print('M_xx,cr for ply', R_crit_pos + 1, '=', MTW_xxc)

        Beta = np.full(self.n, 0)
        if not np.array_equal(self.Beta, Beta):
            self.Beta[R_crit_pos] = 0
            print('\nFailure Progression =', self.Beta)
            # Reset all values
            self.A = np.zeros(shape=(3, 3))
            self.B = np.zeros(shape=(3, 3))
            self.D = np.zeros(shape=(3, 3))
            self.ABD = np.zeros(shape=(6, 6))
            self.eg = np.zeros([])
            self.el = np.zeros([])
            self.sl = np.zeros([])
            self.NT = np.zeros(shape=(3, 1))
            self.MT = np.zeros(shape=(3, 1))
            self.NM = np.zeros(shape=(6, 1))
            # re-run all values
            if not np.array_equal(self.Beta, Beta):
                self.tsai_wu()
            else:
                print('Ply Fail Order =', self.fail_order)


def main():

    C = Calculations()
    C.ply_angle()
    C.ply()
    C.material()
    C.material_properties()
    C.table()
    # Comment out for Tsai-Wu failure calculations
    # print('\nCritical Stress Criterion')
    # C.stress_critical_loads()
    # Comment out for Maximum Stress failure calculations
    print('\nTsai-Wu Criterion\n')
    C.tsai_wu()


if __name__ == '__main__':
    main()

ANSWER

Answered 2022-Apr-16 at 01:55

I don't know if it's the cause of your problem, but your code has six calls to np.empty. I don't see any later initialization of these arrays.

np.empty causes the array to not be initialized, and the memory will contain random garbage. Try replace those with np.zeros and see if you get better results.

Source https://stackoverflow.com/questions/71890376

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install epoxy

Gradle is the only supported build configuration, so just add the dependency to your project build.gradle file:.

Support

See examples and browse complete documentation at the Epoxy Wiki. If you still have questions, feel free to create a new issue.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.