Fabric js select object in group - fabricjs

Is it possible to select a single object from a group created like this?
var r = new fabric.Rect(...);
var l = new fabric.Line(...);
var roadGroup = new fabric.Group([r,l],{ ... });
So I want to have a group, but select objects l or r separately.

The simple answer is yes, but you should make sure you take into account the purpose of a group.
To get a handle on an object that is wrapped in a group you can do something like this:
var r = roadGroup._objects[0];
var l = roadGroup._objects[1];
To select a child of a group try something like this:
fabricCanvas.setActiveObject(roadGroup._objects[0]);
soapbox:
The purpose of creating a group is to treat several objects as if they were a single one. The purpose of selecting an object is to allow user interactions with an object. If you want your user to interact with a portion of a group, you might want to consider not grouping them in the first place, or else un-grouping them prior to selecting the child object.
/soapbox

I believe _objects is to be used internally only and may thus change in the future.
To me it group.item(indexOfItem) seems to be the way

So I had this scenario where I have multiple images in a box. Those all images move along with the box (as a group) but user should also be able to select an individual image and move it.
Basically I wanted to select individual objects (in my case images) of group, I did it like this:
groupImages.forEach(image => image.on('mousedown', function (e) {
var group = e.target;
if (group && group._objects) {
var thisImage = group._objects.indexOf(image);
var item = group._objects[thisImage];//.find(image);
canvas.setActiveObject(item);
}
}));
groupImages could be list of objects which you want to select individually.

Related

Is there an efficient way for getting the rarest role of a member discord.js

I have implemented a feature that shows people their rarest role (the role that the least people have). I did it by looping through each of their roles and checking how many people have the role. As it turns out, if you have over like 50 roles, it delays the bots response visibly, so I was wondering if there is a more efficient way of doing the same thing. My code is here:
const rolesOfMember = member._roles
for(const role in rolesOfMember) {
var membersHavingCurrentRole = message.guild.roles.cache.get(rolesOfMember[role]).members.size
if(membersHavingCurrentRole < membersHavingRarestRole) {
membersHavingRarestRole = membersHavingCurrentRole
rarestRoleID = rolesOfMember[role]
} else if(membersHavingCurrentRole == membersHavingRarestRole) {
var rarestRole = message.guild.roles.cache.get(rarestRoleID)
var currentRole = message.guild.roles.cache.get(rolesOfMember[role])
if(rarestRole.comparePositionTo(currentRole) < 0) {
membersHavingRarestRole = membersHavingCurrentRole
rarestRoleID = rolesOfMember[role]
}
}
}
Well, one way to simplify your code would be to not have to call message.guild.roles.cache.get() 3 or so times for every role that the member has, especially if they're going to have 50+ roles. In fact, we could eliminate the need for your member._roles object entirely, and therefore eliminate the need for the for/in loop. Here's an example (tested and works):
var rolesOfMember = message.member.roles.cache;
var rarestRole = rolesOfMember.sort((roleA, roleB) => roleA.members.size - roleB.members.size).first();
var rarestRoleID = rarestRole.id;
In this example, I first get the Collection of all of the roles that the member has. Then, I use the Collection.sort() method to sort the roles based on how many members have each role in the guild (from least to greatest, so in other words from rarest to most common). Since the first role in this sorted Collection will be the rarest role that the user has, I simply call Collection.first() on the sorted Collection in order to retrieve the first and rarest Role. From there, you can use rarestRole however you'd like, I simply retrieve the role's ID and store it in a variable in my example.
You can also alter the sorting function however you'd like in order to consider the case in which two roles have the same amount of people who have them.
Relevant resources:
https://discord.js.org/#/docs/main/stable/class/Role?scrollTo=members
https://discord.js.org/#/docs/collection/master/class/Collection?scrollTo=sort

Where is my error with my join in acumatica?

I want to get all the attributes from my "Actual Item Inventry" (From Stock Items Form) so i have:
PXResultset<CSAnswers> res = PXSelectJoin<CSAnswers,
InnerJoin<InventoryItem,
On<CSAnswers.refNoteID, Equal<Current<InventoryItem.noteID>>>
>
>.Select(new PXGraph());
But, this returns me 0 rows.
Where is my error?
UPDATED:
My loop is like this:
foreach (PXResult<CSAnswers> record in res)
{
CSAnswers answers = (CSAnswers)record;
string refnoteid = answers.RefNoteID.ToString();
string value = answers.Value;
}
... but i can not go inside foreach.
Sorry for the English.
You should use an initialized graph rather than just "new PXGraph()" for the select. This can be as simple as "this" or "Base" depending on where this code is located. There are times that it is ok to initialize a new graph instance, but also times that it is not ok. Not knowing the context of your code sample, let's assume that "this" and "Base" were insufficient, and you need to initialize a new graph. If you need to work within another graph instance, this is how your code would look.
InventoryItemMaint graph = PXGraph<InventoryItemMaint>.CreateInstance<InventoryItemMaint>();
PXResultset<CSAnswers> res = PXSelectJoin<CSAnswers,
InnerJoin<InventoryItem, On<CSAnswers.refNoteID, Equal<Current<InventoryItem.noteID>>>>>
.Select(graph);
foreach (PXResult<CSAnswers> record in res)
{
CSAnswers answers = (CSAnswers)record;
string refnoteid = answers.RefNoteID.ToString();
string value = answers.Value;
}
However, since you should be initializing graph within a graph or graph extension, you should be able to use:
.Select(this) // To use the current graph containing this logic
or
.Select(Base) // To use the base graph that is being extended if in a graph extension
Since you are referring to:
Current<InventoryItem.noteID>
...but are using "new PXGraph()" then there is no "InventoryItem" to be in the current data cache of the generic base object PXGraph. Hence the need to reference a fully defined graph.
Another syntax for specifying exactly what value you want to pass in is to use a parameter like this:
var myNoteIdVariable = ...
InventoryItemMaint graph = PXGraph<InventoryItemMaint>.CreateInstance<InventoryItemMaint>();
PXResultset<CSAnswers> res = PXSelectJoin<CSAnswers,
InnerJoin<InventoryItem, On<CSAnswers.refNoteID, Equal<Required<InventoryItem.noteID>>>>>
.Select(graph, myNoteIdVariable);
foreach (PXResult<CSAnswers> record in res)
{
CSAnswers answers = (CSAnswers)record;
string refnoteid = answers.RefNoteID.ToString();
string value = answers.Value;
}
Notice the "Required" and the extra value in the Select() section. A quick and easy way to check if you have a value for your parameter is to use PXTrace to write to the Trace that you can check after refreshing the screen and performing whatever action would execute your code:
PXTrace.WriteInformation(myNoteIdVariable.ToString());
...to see if there is a value in myNoteIdVariable to retrieve a result set. Place that outside of the foreach block or you will only get a value in the trace when you actually get records... which is not happening in your case.
If you want to get deep into what SQL statements are being generated and executed, look for Request Profiler in the menus and enable SQL logging while you run a test. Then come back to check the results. (Remember to disable the SQL logging when done or you can generate a lot of unnecessary data.)

NODE.JS: iterating over an array of objects, creating a new key if it does not exist

I am iterating over a collection of data, in my case, an array of objects. Here is a sample of 2 data points from it:
{
violation_id: '211315',
inspection_id: '268804',
violation_category: 'Garbage and Refuse',
violation_date: '2012-03-22 0:00',
violation_date_closed: '',
violation_type: 'Refuse Accumulation' },
{
violation_id: '214351',
inspection_id: '273183',
violation_category: 'Building Conditions',
violation_date: '2012-05-01 0:00',
violation_date_closed: '2012-04-17 0:00',
violation_type: 'Mold or Mildew' }
I need to create a new array of objects from this, one for each "violation_category" property. If Violation category already exists in the new array I am creating, i simply add the information to that existing category object (instead of having two "building conditions" objects for example, I would just add to an existing one).
However, I am having trouble assigning to the existing object if the current one exists (it's easy to check if it does not, but not the other way around). This is what am attempting to do currently:
if (violationCategory.uniqueCategoryName) {
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
} else {
category.violations = results[i].violation_id;
category.date = results[i].violation_date;
category.closed = results[i].violation_date_closed;
violationCategory.push(category);
}
In first condition, if this category (key) exists, I simply add to it, and in the second condition, this is where I am struggling. Any help appreciated. Thanks guys.
Just add an empty object to the key if there no object there :
violationCategory.uniqueCategoryName = violationCategory.uniqueCategoryName || {};
And only then, add the data you want to the object.
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
No condition needed.
Good luck!
Assuming that you have an input variable which is an array of objects, where the objects are looking like the objects of the question, you can generate your output like this:
var output = {};
for (var item of input) {
if (!output[item.violation_category]) output[item.violation_category] = [];
output[item.violation_category].push(item);
}
Of course you might customize it like you want.

create a filter not a group filter

I am creating a custom module in Orchard , I would like to create a query programmatically.
string queryName= "Product";
var item = _orchardServices.ContentManager.New("Query");
item.As<TitlePart>().Title =queryName;
_orchardServices.ContentManager.Create(item, VersionOptions.Draft);
if (!item.Has<IPublishingControlAspect>() && !item.TypeDefinition.Settings.GetModel<ContentTypeSettings>().Draftable)
_orchardServices.ContentManager.Publish(item);
var queryPart = item.As<QueryPart>();
queryPart.ContentItem.ContentType = queryName;
string desc =" filter for the query";
string contentType = "CommonPart.ChannelID.";
var filterGroupRecord = new FilterGroupRecord();
var filterRecord = new FilterRecord()
{
Category = "CommonPartContentFields",
Type = contentType,
Position = 0,
};
filterRecord.State = "<Form><Description>" + desc + "</Description><Operator>Equals</Operator><Value>ChannelId</Value></Form>";
filterGroupRecord.Filters.Add(filterRecord);
queryPart.FilterGroups.Insert(0, filterGroupRecord);
the problem is that:I want set a filters of the query,not a filters group.
could you tell me how to improve my code?
Database structure and class declarations make it impossible. Why do you need it?
Update:
I means that you must use FilterGroupRecord at least one.
But when Query published that Filter Group will be created automatically if query have not yet Filter Group (see at QueryPartHandler). You should add your filters to this group. And not needed to create new group.
var existingFilterGroup = queryPart.FilterGroups[0];
existingFilterGroup.Filters.Add(filterRecord);
Update 2:
To avoid problems with draftable query (and several other potential problems Orchard CMS: Adding default data to fields and then querying them) it is better to move the calling Publish method to the end of your code and other part of your code should be left unchanged. And in your case would be better if you will always publish your query without checking IPublishingControlAspect and Draftable.

Entity Framework 4.1 & existing database

Hi I have an existing database with a table with 30 fields, I want to split the table into many models so I could retrieve/save fields that I need and not every time retrieve/save the whole object from the db. using c#.
I think I should be using Code-First. Could someone provide an example or a tutorial link?
thanks,
You don't need to split table to be able to load a subset of field or persist subset of fields. Both operations are available with the whole table mapped to single entity as well.
For selection you simply have to use projection:
var data = from x in context.HugeEntities
select new { x.Id, x.Name };
You can use either anonymous type in projection or any non-mapped class.
For updates you can simply use:
var data = new HugeEntity { Id = existingId, Name = newName };
context.HugeEntities.Attach(data);
var dataEntry = context.Entry(data);
dataEntry.Property(d => d.Name).IsModified = true; // Only this property will be updated
context.SaveChanges();
Or:
var data = new HugeEntity { Id = existingId };
context.HugeEntities.Attach(data);
data.Name = newName;
context.SaveChanges(); // Now EF detected change of Name property and updated it
Mapping multiple entities to single table must follows very strict rules and it is possible only with table splitting were all entities must be related with one-to-one relation (and there are some problems with more than two entities per split table in code first) or with table-per-hierarchy inheritance. I don't think that you want to use any of them for this case.

Resources