As topic says. I can't access variable from class made in same script.
It's in same script, and variables(as you see) are public. Any ideas?
Tried googling "how to access script variable from another class" but didn't found anything.
Code:
public var Ludnosc = new Array();
var humanCount : int;
public class Human {
public var id : byte;
public var creatureType = "HUMAN";
public var gender : boolean; // false = k, true = m
//public var firstname : String; <- Opcja do wprowadzenia później
//public var lastname : String; <- Opcja do wprowadzenia później
public var age : byte;
public var pregnant : boolean = false;
function Breed(partner) {
if(this.age<16) {
Debug.Log("Woman with id " + this.id + " is too young to be pregnant. She must be 16 or older.");
}
else {
var success = Random.Range(0.0, makePregnantChance);
Debug.Log("Breed chance of partners with IDs [" + this.id + ", " + partner + "] was " + success*100 + "%.");
if(success>0.50) {
this.pregnant = true;
Debug.Log("Creature of type " + this.creatureType + ", with ID " + this.id + " is pregnant!");
Ludnosc.push(new Human()); //LINE 44 | tworzymy nowego czlowieczka
var tempHuman = Ludnosc[humanCount+1] as Human //LINE 45
tempHuman.id = humanCount+1; //LINE 46
tempHuman.age = 1;
var losujPlec = Random.Range(0.0, 1.0);
tempHuman.makePregnantChance = 18/tempHuman.age;
}
}
}
public var parents : byte[]; //Najpierw podajemy ID matki, potem ID ojca.
public var makePregnantChance : float;
}
Bugs:
Assets/TextPierwszy.js(44,33): BCE0005: Unknown identifier: 'Ludnosc'.
Assets/TextPierwszy.js(45,49): BCE0005: Unknown identifier: 'Ludnosc'.
Assets/TextPierwszy.js(45,57): BCE0005: Unknown identifier: 'humanCount'.
Assets/TextPierwszy.js(46,48): BCE0005: Unknown identifier: 'humanCount'.
Your code here:
public var Ludnosc = new Array();
var humanCount : int;
public class Human {...
Needs to actually be:
public class Human {
public var Ludnosc = new Array();
var humanCount : int;
That is of course, if they're related to the class, if not, then you'll be better off creating another class to hold anything else HumanExtras (or something similar),for example.
Related
My application is ASP.NET MVC 5 / SQL Server.
I am trying to select specific columns from a list based on an array:
First list has 200 columns: Age, Gender, .....
var list1 = _reportRepository.ShowMasteView().ToList();
Second list has 20 columns: Age, Gender, ......
From the view I select the items to be displayed:
string[] lits2 = showColumn.Where(c => c.Value == true).Select(c=> c.Key).ToArray();
I get
To get these two specific columns, I tried
var nList = list1.Select(t2 => lits2.Any(t1 => t2.Contains(t1)));
I get an error
Can not resolve symbol "Contains"
I was able to do it using the following
var keys = "Age,Gender";
var connection =
ConfigurationManager.ConnectionStrings["DALEntities"].ConnectionString;
using (var dataAdapter = new SqlDataAdapter("SELECT " + keys
+ " from dbo.vw_MasterView", connection))
{
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
return dataTable;
}
Is there a better way in linq?
From my understand it appears you are trying to extract/select a dynamic object that only has the desired properties/columns.
This can be achieved by building a dynamic expression/function to apply to the Select
The following builds an expression based on the model type and the provided properties
static class DynamicExtensions {
public static IQueryable<dynamic> SelectDynamic<TModel>(this IQueryable<TModel> query, ISet<string> propertyNames) {
var selector = query.BuildSelectorFor(propertyNames);
return query.Select(selector);
}
static Expression<Func<TModel, dynamic>> BuildSelectorFor<TModel>(this IQueryable<TModel> query, ISet<string> propertyNames) {
var modelType = typeof(TModel);
var properties = modelType.GetProperties().Where(p => propertyNames.Contains(p.Name));
// Manually build the expression tree for
// the lambda expression v => new { PropertyName = v.PropertyName, ... }
// (TModel v) =>
var parameter = Expression.Parameter(modelType, "v");
// v.PropertyName
var members = properties.Select(p => Expression.PropertyOrField(parameter, p.Name));
var addMethod = typeof(IDictionary<string, object>).GetMethod(
"Add", new Type[] { typeof(string), typeof(object) });
// { { "PropertyName", v.PropertyName}, ... }
var elementInits = members.Select(m =>
Expression.ElementInit(addMethod, Expression.Constant(m.Member.Name), Expression.Convert(m, typeof(object))));
// new ExpandoObject()
var newExpando = Expression.New(typeof(ExpandoObject));
// new ExpandoObject() { { "PropertyName", v.PropertyName}, ... }
var expando = Expression.ListInit(newExpando, elementInits);
// (TModel v) => new ExpandoObject() { { "PropertyName", v.PropertyName}, ... }
var lambdaExpression = Expression.Lambda<Func<TModel, dynamic>>(expando, parameter);
return lambdaExpression;
}
}
This takes advantage of ExpandoObject whose members can be dynamically added and removed at run time.
The following test was used as an example of how the above function is invoked.
[TestMethod]
public void DynamicList() {
var list1 = new List<Person>
{
new Person{ Gender = "Male", Age = 10, FirstName = "Nama1", SampleNumber = 12},
new Person{ Gender = "Male", Age = 12, FirstName = "Nama2", SampleNumber = 13},
new Person{ Gender = "Female", Age = 13, FirstName = "Nama3", SampleNumber = 14},
new Person{ Gender = "Male", Age = 14, FirstName = "Nama4", SampleNumber = 15},
};
var keys = new string[] { "Age", "Gender", };
var nList = list1.AsQueryable().SelectDynamic(new HashSet<string>(keys));
foreach (IDictionary<string, object> row in nList) {
var msg = $"{{ {keys[0]} = {row[keys[0]]}, {keys[1]} = {row[keys[1]]} }}";
Debug.WriteLine(msg);
}
}
and produces the following output
{ Age = 10, Gender = Male }
{ Age = 12, Gender = Male }
{ Age = 13, Gender = Female }
{ Age = 14, Gender = Male }
The dynamic objects can be used in the View and it is a simple matter of calling the desired members.
For example suppose you have a model as follows
public class MyViewModel {
public string MyProperty { get; set; }
public string[] Keys { get; set; }
public List<dynamic> MyDynamicProperty { get; set; }
}
that was populated with data and given to the view
var list1 = _reportRepository.ShowMasteView();
var keys = new string[] { "Age", "Gender", };
var nList = list1.AsQueryable().SelectDynamic(new HashSet<string>(keys));
var viewModel = new MyViewModel {
MyProperty = "Hello World",
MyDynamicProperty = nList.ToList(),
Keys = keys
};
return View(viewModel);
Then in the view you can use the model as desired, casting to get access to members in the expando object.
#model MyViewModel
...
<h2>#Model.MyProperty</h2>
<table>
<tr>
#foreach(string key in Model.Keys) {
<th>#key</th>
}
</tr>
#foreach (IDictionary<string, object> row in Model.MyDynamicProperty) {
<tr>
#foreach(string key in Model.Keys) {
<td>#row[#key]</td>
}
</tr>
}
</table>
I think you just need to use Contains on your list2.
var nList = list1.Where(t => lits2.Contains(t1));
Contains is a method for Lists. The code you had was trying to use it on a string.
If you have two list of a person's class
public class Person
{
public int id { get; set; }
public string name { get; set; }
}
If the lists are as below:
var list1 = new List<Person>
{
new Person{ id = 1, name = "Nama1"},
new Person{ id = 2, name = "Nama2"},
new Person{ id = 3, name = "Nama3"},
new Person{ id = 4, name = "Nama4"},
};
var list2 = new List<Person>
{
new Person{ id = 1, name = "Nama1"},
new Person{ id = 2, name = "Nama2"},
};
You can filter in the following ways
var keys = list2.Select(x => x.id).ToList();
var filter1= list1.Where(x => keys.Contains(x.id)).ToList();
var filter2= list1.Where(x => keys.Contains(x.id)).Select(x => new { x.name }).ToList();
var filter3= list1.Select(x => new
{
id = x.id,
name = x.name,
check = keys.Contains(x.id)
}).Where(x => x.check).ToList();
If you have array of string
you can use below code
array string same
var lis1 = new string[] {"name1", "name2","name3" };
var lis2 = new string[] { "name1" };
You can filter array of string in the following ways
var items1= lis1.Where(x=>lis2.Contains(x)).ToList();
var items= lis1.Select(x=> new { x, check= lis2.Contains(x) }).Where(x=>x.check == true).ToList();
I've just started learning TypeScript and I'm having a hard time wrapping my head around an interface behavior from the beginning tutorial on http://www.typescriptlang.org/Playground/#tut=ex5
As I understand it, the interface should enforce the type of the parameters, however this particular line throws me off
var user = new Student("Jane", "M.", "User");
It compiles correctly and all is well, but when I modify it to
var user = new Student(1, 2, 3);
it also compiles just fine.
Could anyone elaborate why it's working ?
I understand that this is a beginners question but I could not find any info on this searching online and I don't have any TypeScript experts around me.
Thanks in advance,
Eugene
The type of the Student constructor parameters is any because there is no type annotation:
class Student {
fullname : string;
constructor(public firstname, public middleinitial, public lastname) {
this.fullname = firstname + " " + middleinitial + " " + lastname;
}
}
If we change it to have some type annotations, we'll get an error:
class Student {
fullname : string;
constructor(public firstname: string, // <-- add ': string' here
public middleinitial: string, // and here
public lastname: string) { // and here
this.fullname = firstname + " " + middleinitial + " " + lastname;
}
}
var x = new Student(1, 2, 3); // Error
In a AIR Mobile application I have this code:
import character.*;
var player_1 = new characterObject("Player 1");
var player_2 = new characterObject("Player 2");
In the package class:
package character {
public class characterObject extends MovieClip {
public var characterName: Number;
public var playerCounter: Number = 0;
public function characterObject(myName: String) {
characterName = myName;
playerCounter++;
}
}
Can I access to player_1.playerCounter property inside player_2 object istance?
I need to increes the value of players only if total_player (a var that I want create as sum of player_1.playerCounter + player_2.playerCounter + player_n.playerCounter ...) is < of x.
Bad idea.
Yo can try next thing
package character {
public class CharactersModel extends Object{
private var _chars : Array = [];
public function addCharacter(char : characterObject) {
_chars.push(char);
}
public function getChars() : Array {
return _chars;
}
public function getCharByName(name : String ) : characterObject {
//select from array and return
//use it instead of null
return null;
}
}
}
and update characterObject like this
private var _model : CharactersModel;
public function characterObject(model : CharactersModel ,myName: String) {
_model = model;
characterName = myName;
playerCounter++;
model.addCharacter(this);
}
public function getOtherChar(name : String) {
return _model.getCharByName(name);
}
and finally
import character.*;
var model : CharactersModel = new CharactersModel();
var player_1 = new characterObject(model ,"Player 1");
var player_2 = new characterObject(model ,"Player 2");
I would create a vector to hold character instances outside of the characterObject class. Then you could refer to the length of the vector for the current amount.
var characters:Vector.<characterObject> = new Vector.<characterObject>();
characters.push( new characterObject("Player 1") );
characters.push( new characterObject("Player 2") );
trace( characters.length ); // 2
first time i'm using MongoDB.
I have read this example:
SELECT a,b FROM users WHERE age=33
db.users.find({age:33}, {a:1,b:1})
But I can't translate it into C#. Can anyone help me?
I have translated your query below using the new C# driver (2.2)
var mongoClient = new MongoClient(""mongodb://127.0.0.1:27017"");
var database = mongoClient.GetDatabase("databaseName");
IMongoCollection<Users> _collection = database.GetCollection<Users>("Users");
var condition = Builders<Users>.Filter.Eq(p => p.age, 33);
var fields = Builders<Users>.Projection.Include(p => p.a).Include(p => p.b);
var results= _collection.Find(condition).Project<Users>(fields).ToList().AsQueryable();
You can do it using SetFields method of MongoCursor class, below full example:
var server = MongoServer.Create(connectionString);
var db = _server.GetDatabase("dbName");
var users = db.GetCollection("users");
var cursor = users.FindAs<DocType>(Query.EQ("age", 33));
cursor.SetFields(Fields.Include("a", "b"));
var items = cursor.ToList();
you can use anonymous class
public class User
{
public int age;
public string a;
public string b;
}
var collection = db.GetCollection<User>("Users");
var results = collection.Find(Builders<User>.Filter.Eq(user => user.age, 33))
.Project(u => new { u.a, u.b }).ToList();
//create user class
//(not sure how your class looks like)
public class User
{
public int age;
public string a;
public string b;
}
//then you can use LINQ easily
var server = MongoServer.Create(connectionString);
var db = server.GetDatabase("dbName");
var usersCollection = db.GetCollection<User>("users");
var filteredCollection = usersCollection.AsQueryable().Where(x=> x.age < 33).Where(x=> x.a != null).Contains(x=> x.b != null);
Anyone know What is wrong with my syntax here? I am making dynamic eSQL Queries and running into an error when trying to make where condition for DateTime data type. This is the error:
The query syntax is not valid. Near term '2011', line 1, column 135.
If it matters the DateTime type in my entity is actually nullable DateTime?
However, I thought this is the correct syntax from everything I've read.
Here is the code:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>()
{
new EntityFilter<StudyFirstRead> { PropertyName = "username", OpType = ExpressionType.Equal, Value = "cwoodhouse" },
new EntityFilter<StudyFirstRead> { PropertyName = "FirstRead", OpType = ExpressionType.LessThan, Value = "DATETIME'2011-02-01 00:00'" }
};
Where EntityFilter is:
public class EntityFilter<T>
{
public string PropertyName { get; set; }
public ExpressionType OpType { get; set; }
public object Value { get; set; }
And I am building dynamic queries like so:
StringBuilder builder = new StringBuilder();
int counter = 0;
string baseStr = #"SELECT VALUE val FROM " + contextName + "." + tableName + " AS val WHERE val.";
builder.Append(baseStr);
foreach (EntityFilter<T> filter in filters)
{
//builder.Append(filter.PropertyName + " " + filter.OpTypeString() + " #p" + counter);
builder.Append(filter.PropertyName + " " + filter.OpTypeString() + "'" + filter.Value + "'");
counter++;
if (counter < filters.Count)
builder.Append(" AND val.");
else
{
break;
}
}
return builder.ToString();
It actually is the correct syntax for entity SQL (different than regular SQL or T-SQL).
Turns out the problem was too many single quotes, because I had them in both the EntityFilter object and the method that built the dynamic query.
according to you code the end of your SQL statement would produce something like
AND val.FirstRead = 'DATETIME'2011-02-01 00:00''
when executed you will get error
Error 102: Incorrect syntax near '2011'.
obviously that is not syntactically correct SQL, the quick fix whould be to have your filters collection as such:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>() {
new EntityFilter<StudyFirstRead> {
PropertyName = "username",
OpType = ExpressionType.Equal,
Value = "cwoodhouse"
}, new EntityFilter<StudyFirstRead> {
PropertyName = "FirstRead",
OpType = ExpressionType.LessThan,
Value = "2011-02-01 00:00"
}
};