Function dependent on previous Swift - swift

I have three functions, each dependent on the previous.
let dbPath = createDBPath()
let db = openDatabase(dbPath!)
readQuestionsFromDB(db!)
The first line creates the database path ( if not gives a fatal error, as there is no point in continuing execution if I don't have access to the file stucture ).
The second line opens the database using the path (the unwrap is ok here, as if we don't have a path we'll have crashed by this point in any case).
The third line reads quiz questions from the database that needs to be opened, if the database has an issue it will also crash from within the function as if we can't read a DB there is something seriously wrong.
What is the best way to structure this? An if - let pyramid? I've split this into three functions to try to separate out functionality for readability. Perhaps I should pass the db and db path as class properties? I'm not sure...

I’d do this
if let dbPath = createDBPath(),
let db = openDatabase(dbPath) {
readQuestionsFromDB(db)
}

I don't see anything wrong with your current code, but if you really want to change the aesthetics of your code, you can call map on the optionals.
createDBPath().map(openDatabase).map(readQuestionsFromDB)

Related

I'm wanting to create a separate file of every member who joins the server and then be able to chose them randomly for a 'winner' command sorta thing

So I am using discord.js or Visual studio code or whatever. and I've made a random hug command. And I would like to be able to have it so that the one that gets hugged doesn't get # and it's just their name. I've successfully made a command similar to it, but i don't want to have to keep adding in names manually and theres no promise that the member won't change their name so it's not very reliable.
So I guess what's in my mind is having a file that automatically updates with users leaving or joining or changing their names and then to be able to call on them randomly without #ing them.
So does anybody know how to do this and how i can call on them?
I've done it with the #, and now im at where I manually write in every member's name but I know that is going to end up tedious and their name might change and I don't want to have to worry about them changing their name.
case 'randhug':
var user = message.guild.members.random();
let dismember = ["Klemon", "Second sofira", "CloudBot"]
let disresults = Math.floor((Math.random() * dismember.length));
message.channel.send(`${message.author} SURPRISE huggies you, ${dismember[disresults]}!!!!!`);
if (message.author.bot) return;
break;
The code I have now works, but isn't reliable in the sense that things change.
It sounds like you might find the tag or username properties of a User very valuable in this situation.
User.tag would return Username#1234.
User.username would return Username.
const member = message.guild.members.random();
message.channel.send(`${message.author} surprise huggies you, **${member.user.username}**!`)
.catch(console.error);

Swift - How to modify file metadata like kMDItemDisplayName?

I'm trying to find a way to change a file's metadata attributes (those with the prefix of "kMDItem", listed by mdls), but I didn't find any solution for it. ToT
At first, I've tried using FileManager.default.setAttributes(_attributes:ofItemAtPath:), but this method only gives me few options, it only gives me ability to modify a file's modification date, creation date and posix permissions etc., which is not enough.
Then, I tried using NSMetadataItem with setValue(_value:forKey:) function to change the metadata value, this is my code:
var attributes = NSMetadataItem(url: URL(fileURLWithPath: "/path/to/file")
if let metadata = attributes {
metadata.setValue(newValue, forKey: kMDItemDisplayName as String)
metadata.setValue(newValue, forKey: NSMetadataItemDisplayNameKey)
// I've tried both of them from above (different keys), they both does not work at all
}
I noticed that setValue(_value:forKey:) does not do anything here by repeatedly getting this returning error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Finally, I red this post on StackOverflow, which led my way to this code:
_ = setxattr("/path/to/file".cString(using: .utf8), "kMDItemDisplayName", newValue.cString(using: .utf8), newValue.lengthOfBytes(using: .utf8), 0, 0)
After executing it, I used mdls and xattr -l to check the result, I realized that this is only the solution for adding extended attributes to a file, the metadata didn't change, only the extended attribute with the name of "kMDItemDisplayName" is successfully added.
The result is not what I want (I'm just using kMDItemDisplayName as an example for my question), I do not just want to find a way to add extended attributes to a file, but a way to edit the attributes listed by mdls. Maybe there is no solution for this? Or maybe I should do it in a completely different way?
Not all metadata can be changed. Much of it is not stored directly, it's derived or computed based on other metadata.
The display name for a simple file is derived from its name on disk and the system settings, like whether extensions are hidden or shown. The display name for a bundle (like an app) is slightly more complicated, but, assuming you don't find changing the contents of the bundle (which would break its code signature) acceptable, amounts to the same thing. Those are subject to the system language(s).
There are also certain folders whose names can be localized for display, but that's still based on their on-disk name.
So, to change a file's display name, change its actual name on disk.
For other properties, you can look at URL.setResourceValues(_:) and URLResourceValues to see which properties are settable. You can also look at URLResourceKey to see which are documented as "read-write".

Issue with a topjson object in a Meteor app built with coffeescript

Apologies for the lack of precision in the question, but I'm not completely sure which of possibly many things I'm doing wrong here.
I'm relatively new to Coffeescript and also geo applications in general, but here goes:
I've got a working (simple) Meteor (.7.0.1) application utilizing coffeescript in both client and server. The issue I'm having occurs when attempting to utilize TopoJSON encoded files to create a layer of US congressional districts. (the purpose of the app is to help highlight voter suppression in the US)
So, a few things: Typically in a non-Meteor app, I would just load the topoJSON file like so:
$.getJSON('./data/us-congress-113.json', function (data) {
var congress_geojson = topojson.feature(data, data.objects.districts);
congress_layer.addData(congress_geojson);
});
Now of course this won't work in Meteor because its not asynchronous.
One of the things that was recommended here on SO was to not worry about reading the file, and to instead change the json file to .js, and then set the contents (which are of course just an object) equal to a variable.
Here's what I did:
First, I changed the .json file to a .js file in the server directory, and added the "congress =" to the beginning of the file. It's a huge file so forgive me for omitting the whole object.
congress = {"type":"Topology",
"objects":
{"districts":
{"type":"GeometryCollection","geometries":[{"type":"Polygon"
Now here's where everything starts to give me issues:
In the server.coffee, I've created a variable like so to reference the congress object:
#congress_geojson = topojson.feature(congress, congress.objects.districts)
Notice how I'm putting the # symbol there? I've been told this allows a variable in Coffeescript to be globally scoped? I tried to also use a Meteor feature called "share" where I declare the variable as "share.congress_geojson". That led to the same issues which I will describe below.
Now in the client.coffee file, I'm trying to call this variable to load into a Leaflet map.
congress_layer = L.geoJson(null,
style:
color: "#DE0404"
weight: 2
opacity: 0.4
fillOpacity: 0.1
)
congress_layer.addData(#congress_geojson)
This isn't working, and specifically (despite attempts to find other ways, the errors I'm getting in the console are:
Exception from Deps afterFlush function: TypeError: Cannot read property 'features' of undefined
at o.GeoJSON.o.FeatureGroup.extend.addData (http://localhost:3000/packages/leaflet.js?ad7b569067d1f68c7403ea1c89a172b4cfd68d85:39:16471)
at Object.Template.map.rendered (http://localhost:3000/client/client.coffee.js?37b1cdc5945f3407f2726a5719e1459f44d1db2d:213:18)
I have no doubt that I'm missing something stupidly obvious here. Any suggestions or tips for what I'm doing completely wrong would be appreciated. Is it a case where an object globally declared in a .js file isn't available to code in a .coffee file? Maybe I'm doing something wrong on the Meteor side?
Thanks!
Edit:
So I was able to get things working by putting the .js file containing the congress object in a root /lib folder, causing the object to load first, and then calling the congress object from the client. However, I'm still wanting to know how I could simply share this object from the server? What is the "Meteor way" here?
If you are looking for the Meteor way to order the loading of files, use the Meteor.startup function and put the initialization code there. That function is the $.ready of the Meteor world, i.e., it will execute only after all your files have been successfully loaded on the client.
So in your case:
Meter.startup ->
congress_layer.addData(#congress_geojson)

Moodle: How to set default blocks and their order in a new course?

I want to change default blocks and also order of them when a new course is created. I guess this should be done through editing source code, but if there is a way in application layer, that would be great!
I don't want to send my task to others. Finding out:
What is the proper way;
Which files should be checked;
What is the systematic way of doing it: through code, database or application.
is ok!
You can add following config variables in your config.php file according to your course format setting. In this setting colon is provided to separate the left and right blocks.
$CFG->defaultblocks_site = 'site_main_menu,course_list:course_summary,calendar_month';
$CFG->defaultblocks_social = 'participants,search_forums,calendar_month,calendar_upcoming,social_activities,recent_activity,course_list';
$CFG->defaultblocks_topics = 'participants,activity_modules,search_forums,course_list:news_items,calendar_upcoming,recent_activity';
$CFG->defaultblocks_weeks = 'participants,activity_modules,search_forums,course_list:news_items,calendar_upcoming,recent_activity';

Padrino + MongoMapper/Joint Troubles

I'm using MongoMapper with Joint on Padrino, and trying to get the
upload working. However, I keep getting thrown a NoMethodError
"undefined method 'path' for #<Hash:0xa6fbdf0>". It seems like it
can't see the path, but the parameters are okay. What is the problem
here?
Gist with the code: https://gist.github.com/1323998
I was able to get it to not error, but when I go to find the file with mongofiles, I can't find. The same goes for rack/grid-fs. Where is Joint saving to, and is it saving at all?
See my comments above:
Here's my thought on what you need to do, I think you need to modify the params so that params[:background][:file] is the tempfile object, like so:
params[:background][:file] = params[:background][:file][:tempfile]
background = Background.create(params[:background])
I'm not 100% sure on this, but if this doen't work I could setup a quick Padrino app and test.