Class passar função

Preciso utilizar o mesmo botão em paginas diferentes e com funções diferentes

Como posso passar a função pro botão ?

class App extends Component {    render(){       return(         <View>            <Button title="Abrir conta" />         </View>       )    } }  const Button = (props) => (    <TouchableOpacity onPress={() => {}}>       <Text>{props.title}</Text>    </TouchableOpacity> ) 

TDD test class for ViewModel class, architecture, what do you think?

Currently I am writing my first TDD application. The project is in Xamarin.Forms and tested in xUnit.

I am wondering, that maybe more experienced developers will have any comments or suggestions regarding the code or architecture, before I will continue with next View Models, to avoid corrections.

I am using also Autofac and Moq.

Test class: https://github.com/przemyslawbak/Flashcards/blob/master/Flascards.UnitTests/ViewModels/MainPageViewModelTests.cs

public class MainPageViewModelTests     {         List<Phrase> phrases;         private MainPageViewModel _viewModel;         private Mock<IPhraseEditViewModel> _phraseEditViewModelMock;         private Mock<IMainDataProvider> _mainDataProviderMock;         public MainPageViewModelTests()         {             //instances             phrases = new List<Phrase>             {                 new Phrase { Category = "newCat1", Definition = "newDef1", Group = "newGr1", Learned = false, Name = "newName1", Priority = "newPrio1", Id = 7 }             };             _phraseEditViewModelMock = new Mock<IPhraseEditViewModel>();             _mainDataProviderMock = new Mock<IMainDataProvider>();              //setup             _mainDataProviderMock.Setup(dp => dp.GetGroups())                 .Returns(new List<string>                 {           "Group #1",           "Group #2",           "Group #3"              });             _mainDataProviderMock.Setup(dp => dp.PickUpFile())                 .ReturnsAsync("goodData.csv");             _mainDataProviderMock.Setup(dp => dp.GetStreamFromCSV("goodData.csv"))                  .Returns("Name|Definition|Category|Group|Priority\nname1 |def1|cat1|gr1|prio1\nname2 |def2|cat2|gr2|prio2");             _mainDataProviderMock.Setup(dp => dp.GetStreamFromCSV("emptyData.csv"))                 .Returns("");              //VM instance             _viewModel = new MainPageViewModel(_mainDataProviderMock.Object, CreatePhraseEditViewModel);         }          private IPhraseEditViewModel CreatePhraseEditViewModel() //method for creating PhraseEditVM         {             var phraseEditViewModelMock = new Mock<IPhraseEditViewModel>();             phraseEditViewModelMock.Setup(vm => vm.LoadPhrase(It.IsAny<int>()))               .Callback<int?>(phraseId =>               {                   phraseEditViewModelMock.Setup(vm => vm.Phrase)             .Returns(new Phrase());               });             _phraseEditViewModelMock = phraseEditViewModelMock; //field = var(!!)             return phraseEditViewModelMock.Object;         }          [Fact]         public void LoadGroups_ShouldLoadOnce_True()         {             _viewModel.LoadGroups(); //loads groups twice             _viewModel.LoadGroups();              Assert.Equal(3, _viewModel.Groups.Count); //counts how many groups are loaded         }         [Fact]         public void LoadGroups_ShouldLoad_True()         {             _viewModel.LoadGroups(); //loads collection of groups (from setup)             Assert.Equal(3, _viewModel.Groups.Count); //counts groups             var phrase = _viewModel.Groups[0];             Assert.NotNull(phrase);             Assert.Equal("Group #1", phrase); //compares group name         }         [Fact]         public void AddPhrase_ShouldBeExecuted_True()         {             _viewModel.PhraseEdit = false; //set up PhraseEdit prop             _viewModel.AddPhraseCommand.Execute(null); // executes command             Assert.True(_viewModel.PhraseEdit); //verifies PhraseEdit prop             _phraseEditViewModelMock.Verify(vm => vm.LoadPhrase(null), Times.Once); //counts loaded phrases         }         [Fact]         public void LoadFromFile_ShouldConvertReturnedCorrectFormatString_ReturnsPhraseList()         {             _viewModel.LoadFromFile("goodData.csv"); //loads phrases from the file             Assert.Equal(2, _viewModel.LoadedPhrases.Count); //counts loaded phrases from the file             var phrase = _viewModel.LoadedPhrases[0];             Assert.NotNull(phrase); //checks if phrase is not null, below compares props             Assert.Equal("name1", phrase.Name);             Assert.Equal("def1", phrase.Definition);             Assert.Equal("cat1", phrase.Category);             Assert.Equal("gr1", phrase.Group);             Assert.Equal("prio1", phrase.Priority);         }         [Fact]         public void PopulateDb_ShouldSeedDbWithPhrases_CallsDpSavePhrase()         {             _viewModel.LoadedPhrases = phrases; //populates collection             _viewModel.PopulateDb(_viewModel.LoadedPhrases); //populates Db with phase list - 1 item             _mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Once); //counts saved phrases         }         [Fact]         public void LoadFile_ShouldBeExecuted_CallsOnLoadFileExecute()         {             _viewModel.LoadFile.Execute(null); //execute command             Assert.Equal(2, _viewModel.LoadedPhrases.Count()); //counts loaded phrases from the file             Assert.Equal(3, _viewModel.Groups.Count); //counts loaded groups             _mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.AtLeast(2)); //counts saved phrases         }         [Fact]         public void PopulateDb_ShouldSeedDbOnce_True()         {             _viewModel.LoadedPhrases = phrases; //populates collection             _viewModel.PopulateDb(_viewModel.LoadedPhrases); //seeds Db twice             _viewModel.PopulateDb(_viewModel.LoadedPhrases);             _mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Once); //should seed only once         }         [Fact]         public void LoadFromFile_WithFilePathParameterIsNull_ReturnsEmptyCollection()         {             List<Phrase> expected = new List<Phrase>();             expected.Clear(); //expectations             List<Phrase> method = _viewModel.LoadFromFile("");//loads phrases from the file with empty path parameter             _viewModel.LoadFromFile(""); //loads phrases from the file with empty path string             Assert.Empty(_viewModel.LoadedPhrases); // check if LoadedPhrases is empty             Assert.Equal(expected, method); //compare expectations with method returns         }         [Fact]         public void PopulateDb_GetsEmptyCollectionParameter_DoesNothing()         {             _viewModel.LoadedPhrases.Clear(); //collection is empty             _viewModel.PopulateDb(_viewModel.LoadedPhrases); //PopulateDb with empty collection             _mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Never); //with empty collection SavePhrase runs never         }         [Fact]         public void LoadFromFile_GetsPathToEmptyFile_ReturnsEmptyCollection()         {             List<Phrase> expected = new List<Phrase>();             expected.Clear(); //expectations             List<Phrase> method = _viewModel.LoadFromFile("emptyData.csv"); //loads phrases from the file with empty content             Assert.Empty(_viewModel.LoadedPhrases); // check if LoadedPhrases is empty             Assert.Equal(expected, method); //compare expectations with method returns         }          //TODO:         //zły format pliku         //brak | w pliku     } 

Tested View Model class: https://github.com/przemyslawbak/Flashcards/blob/master/Flashcards/Flashcards/ViewModels/MainPageViewModel.cs

public interface IMainPageViewModel     {         void LoadGroups();     }     public class MainPageViewModel : ViewModelBase, IMainPageViewModel     {         List<Phrase> oldPhrases = new List<Phrase>(); //verification for PopulateDb method;         private Func<IPhraseEditViewModel> _phraseEditVmCreator;         private IMainDataProvider _dataProvider;         public string FileLocation { get; set; }         public ObservableCollection<string> Groups { get; set; }         public List<Phrase> LoadedPhrases { get; set; }         public bool PhraseEdit { get; set; }         public IPhraseEditViewModel SelectedPhraseEditViewModel { get; set; }         public MainPageViewModel(IMainDataProvider dataProvider,             Func<IPhraseEditViewModel> phraseditVmCreator) //ctor         {             _dataProvider = dataProvider;             _phraseEditVmCreator = phraseditVmCreator;             Groups = new ObservableCollection<string>();             LoadedPhrases = new List<Phrase>();             //commands tests             AddPhraseCommand = new DelegateCommand(OnNewPhraseExecute);             LoadFile = new DelegateCommand(OnLoadFileExecute);         }          public ICommand AddPhraseCommand { get; private set; }         public ICommand LoadFile { get; private set; }          private void OnNewPhraseExecute(object obj)         {             SelectedPhraseEditViewModel = CreateAndLoadPhraseEditViewModel(null);         }          private IPhraseEditViewModel CreateAndLoadPhraseEditViewModel(int? phraseId)         {             //Application.Current.MainPage.Navigation.PushAsync(new PhraseEditPage());             var phraseEditVm = _phraseEditVmCreator();             PhraseEdit = true;             phraseEditVm.LoadPhrase(phraseId);             return phraseEditVm;         }         private async void OnLoadFileExecute(object obj)         {             LoadedPhrases.Clear();             FileLocation = await _dataProvider.PickUpFile();             LoadedPhrases = LoadFromFile(FileLocation);             PopulateDb(LoadedPhrases);             LoadGroups();         }         public void LoadGroups() //loads group list from the DB         {             Groups.Clear();             foreach (var group in _dataProvider.GetGroups())             {                 Groups.Add(group);             }         }         public List<Phrase> LoadFromFile(string filePath)         {             if (filePath != "")             {                 string stream = "";                 LoadedPhrases.Clear();                 stream = _dataProvider.GetStreamFromCSV(filePath);                 Dictionary<string, int> myPhraseMap = new Dictionary<string, int>(); //exception for wrong format                 var sr = new StringReader(stream);                 using (var csv = new CsvReader(sr, true, '|'))                 {                     int fieldCount = csv.FieldCount;                     string[] headers = csv.GetFieldHeaders();                     for (int i = 0; i < fieldCount; i++)                     {                         myPhraseMap[headers[i]] = i;                     }                     while (csv.ReadNextRecord())                     {                         Phrase phrase = new Phrase                         {                             Name = csv[myPhraseMap["Name"]],                             Definition = csv[myPhraseMap["Definition"]],                             Category = csv[myPhraseMap["Category"]],                             Group = csv[myPhraseMap["Group"]],                             Priority = csv[myPhraseMap["Priority"]],                             Learned = false                         };                         LoadedPhrases.Add(phrase);                     }                 }             }             else             {                 LoadedPhrases.Clear();             }             return LoadedPhrases;         }         public void PopulateDb(List<Phrase> phrases)         {             if (oldPhrases != phrases) //populates only if collection is new             {                 foreach (var item in phrases)                 {                     _dataProvider.SavePhrase(item);                 }                 oldPhrases = phrases;             }         }     } 

GH repository of the project: https://github.com/przemyslawbak/Flashcards/tree/master/Flashcards/Flashcards

Unique Form Per User With Custom Form Class

Not sure if this is a related/duplicate of Generate unique form ID based on context

I am hoping I can render a unique form per user with the Form API using a custom form class.

What I’ve seen with \Drupal::formBuilder()->getForm(), you must provide your Form::class and this does not allow for something like:

public function getFormId() {    $  userID = \Drupal::currentUser()->id();   $  userFormID = 'form_settings' . $  userID;   return $  userFormID;  } 

and returns an invalid form with \Drupal::formBuilder()->getForm().

Ultimately trying to render a unique form via hook_preprocess_page() for the user to interact with.

Is it possible to provide a unique form/form_settings based on the user ID using the Form API?

Can provide more code if needed, but maybe this is just a no?

Using deftype to Create a Wrapper Class for Byte Arrays

I want to create a wrapper class for byte arrays so that I can use them as keys in fastutil‘s Object2LongAVLTreeMap. I have created a wrapper like this:

(deftype Bytes [^bytes ba]   Comparable   (compareTo     [this other]     (let [m (alength ^bytes (.ba this))           n (alength ^bytes (.ba other))           l (min m n)]       (loop [i 0]         (if (< i l)           (let [a (aget ^bytes (.ba ^Bytes this) i)                 b (aget ^bytes (.ba ^Bytes other) i)                 d (compare a b)]             (if (zero? d)               (recur (inc i))               d))           (compare m n)))))) 

The wrapper needs to implement Comparable for the insertions in the AVL Tree.

I am looking for feedback regarding my overall approach and my implementation of compareTo. I will be inserting lots of entries into the tree so I don’t want to be creating unnecessary objects, etc. during the comparison.

How to implement a data class that will be accessed/updated by multiple threads?

I am trying to implement a data class called GamePlayData that stores game play counts. It has two members one called lifetime, which stores the game play count since the machine was configured for the first time. The other member is called period, which stores play count for the configured period of time.

I have come up with the following class:

public class GamePlayData {     private KeyValueDatabase _database;     private long? _period;     private long? _lifetime;      private readonly string _lifetimeKey;     private readonly string _periodKey;      private readonly object _exclusion = new object();      public GamePlayData(KeyValueDatabase database)     {         _database = database;         _lifetimeKey = @"GamePlayDataLifetime"         _periodKey = @"GamePlayDataPeriod"                }      public long Period     {         get         {             lock (_exclusion)             {                 if (_period != null)                 {                     return (long)_period;                 }                  _database.GetValue(_periodKey, out long value);                 _period = value;                 return (long)_period;             }         }     }      public long Lifetime     {         get         {             lock (_exclusion)             {                 if (_lifetime != null)                 {                     return (long)_lifetime;                 }                  _database.GetValue(_lifetimeKey, out long value);                 _lifetime = value;                 return (long)_lifetime;             }         }     }      public void Increment(long amount)     {         lock (_exclusion)         {             if (_lifetime == null)             {                 _database.GetValue(_lifetimeKey, out long value);                 _lifetime = value;             }              if (_period == null)             {                 _database.GetValue(_periodKey, out long value);                 _period = value;             }              if (_lifetime + amount <= 0)             {                 _lifetime = 0;             }             else             {                 _lifetime = (_lifetime + amount);             }              if (_period + amount <= 0)             {                 _period = 0;             }             else             {                 _period = (_period + amount);             }              _database.SetValue(_lifetimeKey, _lifetime);             _database.SetValue(_periodKey, _period);          } // lock     }      public void Reset(long resetValue)     {         lock (_exclusion)         {             _lifetime = resetValue;             _period = resetValue;         }     } } 

The problem is that using locks here could potentially degrade the performance as contention locks are kinda slow.

I am wondering if there are some improvements I could do here or may be implement this class altogether in a different way to get more performance.

Any ideas ?

React-Native Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain

I’m trying do the get started react-native tutorial for Ubuntu, I already have installed nodejs, the react-native command line interface, a JDK, and the android studio. already set it up the environment variables, so when I try run react-native run-android, this error appears: info Starting JS server... info Building and installing the app on the device (cd android && ./gradlew app:installDebug)... Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain error Could not install the app on the device, read the error above for details. Make sure you have an Android emulator running or a device connected and have set up your Android development environment: https://facebook.github.io/react-native/docs/getting-started.html error Command failed: ./gradlew app:installDebug and I can’t find the solution for this.

C++ Array of pointers to an abstract class

I have this homework for my OOP class which I hope someone can check for me:

Make an abstract class ElementOnMap which contains a unique id (int), a type (char array) and a static var #ofElements. Than create a class Map with dimensions of the map and a matrix of pointers to objects of class Element. It should have the following functions:

a copy constructor!

Than make a sub class Island and a sub class Ship which inherit the class Element, which redefine the abstract method from Element, …

So this is Element.h

class Element { protected:     static int numEl;     int id;     char type[16];  public:     char * type()      {         char *p = type;         return p;            }     virtual void print() = 0; };  class Island :public Element {     char name[16];     int numPeople; public:     Island();     Island(char*, int);     void print(); }; 

This is my Element.cpp:

#include"Element.h" #include<string> #include<iostream> using namespace std;  int Element::numEl = 0;  Island::Island() {     id = numEl;     numEl++; }  Island::Island(char* naz, int a) :numPeople(a) {     strcpy_s(name, naz);      type[0] = 'I';     type[1] = 's';     type[2] = 'l';     type[3] = 'a';     type[4] = 'n';     type[5] = 'd';     type[6] = '';      id = numEl;     numEl++; }  void Island::print() {     cout << "ID elementa: " << id << "Tip elementa: " << type;      cout << "Ime ostrva: " << name << "Broj stanovnika: " << numPeople << endl; } 

and finally, Map.h:

class Mapa {     int m, n;     Element ***Matrix; public:     Mapa(int, int);     Mapa(const Mapa &M);     ~Mapa(); };  Mapa::Mapa(int a, int b):m(a), n(b) {     Matrix = new Element**[m];     for (int i = 0; i < m; i++)         Matrix[i] = new Element*[n]; }  Mapa::Mapa(const Mapa & M) {     this->m = M.m;     this->n = M.n;      Matrix = new Element**[m];     for (int i = 0; i < m; i++)         Matrix[i] = new Element*[n];      for (int i = 0; i < m; i++)         for (int j = 0; j < n; j++)         {             *Matrix[i][j] = *(M.Matrix[i][j]);         } }  Mapa::~Mapa() {     delete[] Matrix; } 

Am I declaring the pointer matrix correctly and is my copy constructor any good? I get that i need a deep copy cause i’m working with pointers, but this pointer inception is really making me feel dumb. Also, do i need a constructor for the abstract Element class, since it cant be instantiated?

What is a good storytelling way to change a characters class?

So let’s say i am playing a bard.

But now my bard is level 7 and i would like to change the class because i’m just not feeling it anymore. Now i want to play the same character. I still want the NPC’s to recognise my character. What are good way’s to do this, so i don’t just randomly become for example a sorcerer?

Did you ever change your class “mid-game”? How did you do it?

What is a good storytelling way to change a characters class?

Opportunity attack and class features during own turn. (via Dissonant Whispers)

Consider this scenario: a college of swords bard uses dissonant whispers on a creature within 5 feet of him while he is holding a melee weapon. The creature fails the save and has to immediately use its reaction to move away. In my understanding, this movement provokes opportunity attacks. So:

  1. Would the caster also be entitled to an opportunity attack?

  2. If so, would he be able to augment his opportunity attack with a blade flourish?