Deep copy of arrays in Ruby - ruby-on-rails

I wanted to get an object on production and do an exact replica( copy over its contents) to another object of same type. I tried doing this in 3 ways from ruby console which none of them worked:
Let's say you have the tt as the first object you want to copy over and tt2 as the replica object. The first approach I tried is cloning the array
tt2.patients = tt.urls.patients
tt2.doctors = tt.segments.doctors
tt2.hospitals = tt.pixels.hospitals
Second approach I tried is duplicating the array which is actually the same as cloning the array:
tt2.patients = tt.patients.dup
tt2.doctors = tt.doctors.dup
tt2.hospitals = tt.hospitals.dup
Third approach I tried is marhsalling.
tt2.patients = Marshal.load(Marshal.dump(tt.patients))
tt2.doctors = Marshal.load(Marshal.dump(tt.doctors))
tt2.hospitals = Marshal.load(Marshal.dump(tt.hospitals))
None of the above works for deep copying from one array to another. After trying out each approach individually above, all the contents of the first object (tt) are nullified (patients, doctors and hospitals are gone). Do you have any other ideas on copying the contents of one object to another? Thanks.

Easy!
#new_tt = tt2.clone
#new_tt.patients = tt2.patients.dup
#new_tt.doctors = tt2.doctors.dup
#new_tt.hospitals = tt2.hospitals.dup
#new_tt.save

This is what ActiveRecord::Base#clone method is for:
#bar = #foo.clone
#bar.save

Ruby Facets is a set of useful extensions to Ruby and has a deep_clone method that might work for you.

Related

Using Insert with a large multi-layered table using Lua

So I am working on a script for GTA5 and I need to transfer data over to a js script. However so I don't need to send multiple arrays to js I require a table, the template for the table should appear as below.
The issue I'm having at the moment is in the second section where I receive all vehicles and loop through each to add it to said 'vehicleTable'. I haven't been able to find the "table.insert" method used in a multilayered table
So far I've tried the following
table.insert(vehicleTable,vehicleTable[class][i][vehicleName])
This seems to store an 'object'(table)? so it does not show up when called in the latter for loop
Next,
vehicleTable = vehicleTable + vehicleTable[class][i][vehicleName]
This seemed like it was going nowhere as I either got a error or nothing happened.
Next,
table.insert(vehicleTable,class)
table.insert(vehicleTable[class],i)
table.insert(vehicleTable[class][i],vehicleName)
This one failed on the second line, I'm unsure why however it didn't even reach the next problem I saw later which would be the fact that line 3 had no way to specify the "Name" field.
Lastly the current one,
local test = {[class] = {[i]={["Name"]=vehicleName}}}
table.insert(vehicleTable,test)
It works without errors but ultimately it doesn't file it in the table instead it seems to create its own branch so object within the object.
And after about 3 hours of zero progress on this topic I turn to the stack overflow for assistance.
local vehicleTable = {
["Sports"] = {
[1] = {["Name"] = "ASS", ["Hash"] = "Asshole2"},
[2] = {["Name"] = "ASS2", ["Hash"] = "Asshole1"}
},
["Muscle"] = {
[1] = {["Name"] = "Sedi", ["Hash"] = "Sedina5"}
},
["Compacts"] = {
[1] = {["Name"] = "MuscleCar", ["Hash"] = "MCar2"}
},
["Sedan"] = {
[1] = {["Name"] = "Blowthing", ["Hash"] = "Blowthing887"}
}
}
local vehicles = GetAllVehicleModels();
for i=1, #vehicles do
local class = vehicleClasses[GetVehicleClassFromName(vehicles[i])]
local vehicleName = GetLabelText(GetDisplayNameFromVehicleModel(vehicles[i]))
print(vehicles[i].. " " .. class .. " " .. vehicleName)
local test = {[class] = {[i]={["Name"]=vehicleName}}}
table.insert(vehicleTable,test)
end
for k in pairs(vehicleTable) do
print(k)
-- for v in pairs(vehicleTable[k]) do
-- print(v .. " " .. #vehicleTable[k])
-- end
end
If there is not way to add to a library / table how would I go about sorting all this without needing to send a million (hash, name, etc...) requests to js?
Any recommendations or support would be much appreciated.
Aside the fact that you do not provide the definition of multiple functions and tables used in your code that would be necessary to provide a complete answere without making assumptions there are many misconceptions regarding very basic topics in Lua.
The most prominent is that you don't know how to use table.insert and what it can do. It will insert (append by default) a numeric field to a table. Given that you have non-numeric keys in your vehicleTable this doesn't make too much sense.
You also don't know how to use the + operator and that it does not make any sense to add a table and a string.
Most of your code seems to be the result of guess work and trial and error.
Instead of referring to the Lua manual so you know how to use table.insert and how to index tables properly you spend 3 hours trying all kinds of variations of your incorrect code.
Assuming a vehicle model is a table like {["Name"] = "MyCar", ["Hash"] = "MyCarHash"} you can add it to a vehicle class like so:
table.insert(vehicleTable["Sedan"], {["Name"] = "MyCar", ["Hash"] = "MyCarHash"})
This makes sense because vehicleTable.Sedan has numeric indices. And after that line it would contain 2 cars.
Read the manual. Then revisit your code and fix your errors.

Lua - table won't insert from function

I have a Lua function where I build a table of value and attempt to add it to a global table with a named key.
The key name is pulled from the function arguments. Basically, it's a filename, and I'm pairing it up with data about the file.
Unfortunately, the global table always comes back nil. Here's my code: (let me know if you need to see more)
(Commented parts are other attempts, although many attempts have been deleted already)
Animator = Class{}
function Animator:init(atlasfile, stringatlasfriendlyname, totalanimationstates, numberofframesperstate, booleanstatictilesize)
-- Define the Animator's operation mode. Either static tile size or variable.
if booleanstatictilesize ~= false then
self.isTileSizeStatic = true
else
self.isTileSizeStatic = false
end
-- Define the total animation states (walking left, walking right, up down, etc.)
-- And then the total frames per state.
self.numAnimationStates = totalanimationstates or 1
self.numAnimationFrames = numberofframesperstate or 2
-- Assign the actual atlas file and give it a programmer-friendly name.
self.atlasname = stringatlasfriendlyname or removeFileExtension(atlasfile, 'animation')
generateAnimationQuads(atlasfile, self.atlasname, self.numAnimationStates, self.numAnimationFrames)
end
function generateAnimationQuads(atlasfile, atlasfriendlyname, states, frames)
spriteWidthDivider = atlasfile:getWidth() / frames
spriteHeightDivider = atlasfile:getHeight() / states
animationQuadArray = generateQuads(atlasfile, spriteWidthDivider, spriteHeightDivider)
animationSetValues = {atlasarray = animationQuadArray, width = spriteWidthDivider, height = spriteHeightDivider}
--gAnimationSets[#gAnimationSets+1] = atlasfriendlyname
gAnimationSets[atlasfriendlyname] = animationSetValues
--table.insert(gAnimationSets, atlasfriendlyname)
end
Note: when using print(atlasfriendlyname) and print(animationSetValues), neither are empty or nil. They both contain values.
For some reason, the line(s) that assign the key pair to gAnimationSets does not work.
gAnimationSets is defined a single time at the top of the program in main.lua, using
gAnimationSets = {}
Animator class is called during the init() function of a character class called Bug. And the Bug class is initialized in the init() function of StartState, which extends from BaseState, which simply defines dummy init(), enter(), update() etc. functions.
StartState is invoked in main.lua using the StateMachine class, where it is passed into StateMachine as a value of a global table declared in main.lua.
gAnimationSets is declared after the table of states and before invoking the state.
This is using the Love2D engine.
Sorry that I came here for help, I've been picking away at this for hours.
Edit: more testing.
Trying to print the animationQuadArray at the index gTextures['buganimation'] always returns nil. Huh?
Here's gTextures in Main.lua
gTextures = {
['background'] = love.graphics.newImage('graphics/background.png'),
['main'] = love.graphics.newImage('graphics/breakout.png'),
['arrows'] = love.graphics.newImage('graphics/arrows.png'),
['hearts'] = love.graphics.newImage('graphics/hearts.png'),
['particle'] = love.graphics.newImage('graphics/particle.png'),
['buganimation'] = love.graphics.newImage('graphics/buganimation.png')
}
Attempting to return gTextures['buganimation'] returns a file value as normal. It's not empty.
My brain is so fried right now I can't even remember why I came to edit this. I can't remember.
Global table in Main.lua, all other functions can't access it.
print(gTextures['buganimation']) works inside the function in question. So gTextures is absolutely accessible.
Table isn't empty. AnimationSetValues is not empty.
I'm adding second answer because both are correct in context.
I ended up switching IDE's to VS Code and now the original one works.
I was originally using Eclipse LDT with a Love2D interpreter and in that environment, my original answer is correct, but in VS Code, the original is also correct.
So Dimitry was right, they are equivalent, but something about my actual Eclipse setup was not allowing that syntax to work.
I switched to VS Code after I had another strange syntax problem with the interpreter where goto syntax was not recognized and gave a persistent error. The interpreter thought goto was the name of a variable.
So I switched, and now both things are fixed. I guess I just won't use LDT for now.
Solution: Lua syntax. Brain Fry Syndrome
I wrote:
animationSetValues = {atlasarray = animationQuadArray, width = spriteWidthDivider, height = spriteHeightDivider}
Should be:
animationSetValues = {['atlasfile']=atlasfile, ['atlasarray']=animationQuadArray, ['width']=spriteWidthDivider, ['height']=spriteHeightDivider}
Edit: I'm fully aware of how to use answers. This was posted here to reserve my spot for an answer so I could edit it later when I returned back home, which is exactly what I'm doing right now. I'll keep the old post for archival purposes.
Original:
I solved it. I apologize for not posting the solution right now. My brain is melted into gravy.
I will post it tomorrow. Just wanted to "answer" saying no need to help. Solved it.
Solution is basically, "oh it's just one of those Lua things". Wonderful. I'm having so much fun with this language - you can tell by my blank expression.
From the language without line endings or brackets, but forced print parentheses... ugh. I'm going back to C# when this class is done.

Rails 5.2.0 —— How to delete sub values of cookies?

I have a cookies.permanent[:liked]:
cookies.permanent[:liked] = 'liked1#liked2#'
I removed liked1#:
cookies.permanent[:liked].slice! `liked1#`
I get cookies.permanent[:liked]:
'liked2#'
Next, I removed 'liked2#':
cookies.permanent[:liked].slice! `liked2#`
and I thought I would get '', but I got:
'liked1#'
And I printed cookies.permanent[:liked], I got 'liked1#liked2#'!
I just want to delete a substring of cookies value, but I find it still can be read.
So, how to do that? Note, I must use permanent.
Yeah, I find I can do this by this:
temp = cookies.permanent[:liked]
wanted_deleted = 'liked1#'
temp.slice! wanted_deleted
cookies.permanent[:liked] = temp
Now, value of cookies.permanent[:liked] is 'liked2#'
There has more efficient ways?

web server memory leak issue

i'm create a dating website using symfony 1.4 (it's my first project using symfony). the problem is there server freezes if there is only 10 or less users online. i tryied optimizing my js, css, sprites using yslow i got grade A but still the problem is always there. that's why i think the way i build the application might be wrong so here is the website naijaconnexion.com i'm asking u for advices and things to do so i overcome this problem
If i wasn't clear enough just ask, if you want cpanel admin access i'll post it
i realy realy needs your help
for instance i have this code on my home page action does it seems ok or it needs to be optimized and how
$this->me = $this->getUser()->getGuardUser()->getPerson();
$this->cities = Doctrine_Core::getTable('City')->findByDql("zipcode=''");
$this->countries = Doctrine_Core::getTable('City')->findByDql("zipcode='10'");
$this->contacts = $this->me->getContacts();
$this->favorites = $this->me->getFavorites();
$this->matches = $this->me->getMatches();
$this->pager = new sfDoctrinePager('Conversation', sfConfig::get('app_home_conversations_per_page'));
$this->pager->setQuery($this->me->getConversationsQuery());
$this->pager->setPage($request->getParameter('page', 1));
$this->pager->init();
without HYDRATE_ARRAY
i can do this
if i use HYDRATE_ARRAY
will i be able to do stuff like $this->contacts[0]['username'];
help please
The problem is doctrine...
Try to fetch the needed values as array and set a limit!
How many objects are returned by the following queries:
$this->cities = Doctrine_Core::getTable('City')->findByDql("zipcode=''");
$this->countries = Doctrine_Core::getTable('City')->findByDql("zipcode='10'");
$this->contacts = $this->me->getContacts();
$this->favorites = $this->me->getFavorites();
$this->matches = $this->me->getMatches();
? Do not forget that they are object with references to other objects!
And yes, this will work $this->contacts[0]['username'];.
if you join the tables with the doctrine query, you can access related entities too - without executing additional queries.
$this->contacts = Doctrine_Core::getTable('Contact')
->createQuery('c')
->leftJoin('c.Users u')
->addWhere('...')
->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
$this->contacts[0]['Users'][0]['username']

Nokogiri pull parser (Nokogiri::XML::Reader) issue with self closing tag

I have a huge XML(>400MB) containing products. Using a DOM parser is therefore excluded, so i tried to parse and process it using a pull parser. Below is a snippet from the each_product(&block) method where i iterate over the product list.
Basically, using a stack, i transform each <product> ... </product> node into a hash and process it.
while (reader.read)
case reader.node_type
#start element
when Nokogiri::XML::Node::ELEMENT_NODE
elem_name = reader.name.to_s
stack.push([elem_name, {}])
#text element
when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE
stack.last[1] = reader.value
#end element
when Nokogiri::XML::Node::ELEMENT_DECL
return if stack.empty?
elem = stack.pop
parent = stack.last
if parent.nil?
yield(elem[1])
elem = nil
next
end
key = elem[0]
parent_childs = parent[1]
# ...
parent_childs[key] = elem[1]
end
The issue is on self-closing tags (EG <country/>), as i can not make the difference between a 'normal' and a 'self-closing' tag. They both are of type Nokogiri::XML::Node::ELEMENT_NODE and i am not able to find any other discriminator in the documentation.
Any ideas on how to solve this issue?
There is a feature request on project page regarding this issue (with the corresponding failing test).
Until it will be fixed and pushed into the current version, we'll stick with good'ol
input_text.gsub! /<([^<>]+)\/>/, '<\1></\1>'
Hey Vlad, well I am not a Nokogiri expert but I've done a test and saw that the self_closing?() method works fine on determining the self closing tags. Give it a try.
P.S. : I know this is an old post :P / the documentation is HERE

Resources