text:
Q: Core Data: app crashed when accesing to NSManagedObject attribute I describe the problem. I have an CoreData entity "New". I'm using a fetchedResultsController with a tableView to present the objects. The problem is when app tries to update a label, it crashed (cell has two labels, but app always crashes in the same sentence, updating the same label...).
Some code here:

*

*That is the definition of the CoreDataManager:

{
// MARK: - Shared Instance

/**
*  This class variable provides an easy way to get access
*  to a shared instance of the CoreDataStackManager class.
*/
class func sharedInstance() -> CoreDataStackManager {

    struct Singleton {
        static let instance = CoreDataStackManager()
    }
    return Singleton.instance
}

// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory : NSURL = {

    let urls  = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {

    let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

    let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME)

    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {

    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator

    return managedObjectContext
}()

// MARK: - Core Data Saving support
func saveContext() {

    if managedObjectContext.hasChanges {

        managedObjectContext.performBlockAndWait {
            do {
                try self.managedObjectContext.save()
            } catch {
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }

*

*Here, where the app crashes:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("HotNewsCell") as! NewsTableViewCell
    let new = fetchedResultsController.objectAtIndexPath(indexPath) as! New

    configureCell(cell, new: new)

    return cell
}

private func configureCell(cell: NewsTableViewCell, new: New) {

cell.titleLabel.text = new.title
/* Next line is where app crashes :( */
cell.descriptionLabel.text = new.newBody

if let url = NSURL(string: new.photoReference) {

    cell.activityIndicator.startAnimating()

    if new.image != nil {
        cell.imageViewNews.image = new.image
        cell.activityIndicator.stopAnimating()
    }
    else {

        let task = NetworkRequests.sharedInstance().makeImageRequestFromURL(url) { (data, error) in

            guard error == nil else {
                print(error)
                return
            }

            guard let data = data else {
                print("No data available")
                return
            }

            let image = UIImage(data: data)
            new.image = image

            dispatch_async(dispatch_get_main_queue())
            {
                cell.imageViewNews.image = image
                cell.activityIndicator.stopAnimating()
            }
        }

        cell.taskToCancelifCellIsReused = task
    }
}

It's strange, because if I comment "cell.descriptionLabel.text = new.newBody", app works perfectly.
Thanks!
EDIT
Error was EXC_BAD_ACCESS. Then, I enabled NSZombie, and the error is "message sent to deallocated instance".

A: I believe this is an artefact of using an attribute name which begins new.....  To avoid the problem, just change the name of the attribute.
See also this answer to an unrelated question, which highlights the problem with new....  From the document identified in that answer (the Clang documentation), it seems technically the problem would  not arise if the character immediately after "new" is a lower case letter.  So newbody would be OK, whereas newBody is not.  Also, for completeness, the following prefixes should likewise be avoided (though they are unlikely choices for attribute names):

*

*alloc

*copy

*mutableCopy

*init

Interestingly, Xcode (at least version 7.3; not sure about previous versions) will not permit these attribute names in Objective-C, giving a compiler error:

Property follows Cocoa naming convention for returning 'owned' objects

Sadly the Swift compiler does not give any error or warning.


text:
Q: TextTransfer type resolve issue I am trying out this code from javapractices dot com and Im seeing a type resolve issue :
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.Toolkit;
import java.io.*;

public final class JP_Clipboard implements ClipboardOwner {

    /**
     * @param args
     */
    public static void main(String... aArgs) {
        TextTransfer textTransfer = new TextTransfer();  <- ERROR

            // Do other stuff

    }

I see the following error. How do I resolve this? Im using Eclipse with Java 1.7.0_45
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    TextTransfer cannot be resolved to a type
    TextTransfer cannot be resolved to a type

    at JP_Clipboard.main(JP_Clipboard.java:20)

A: In the example the class name is called TextTransfer. You have renamed it to JP_Clipboard. Either use
JP_Clipboard textTransfer = new JP_Clipboard();

or rename the class back to TextTransfer (preferrable - follows Java naming conventions)

A: The issue is with your example Class name JP_Clipboard - this should be renamed to TextTransfer; referring to link you have provided in your post.

A: I checked your reference.. You have renamed the TextTransfer class by JP_Clipboard in your case
So your code should be:
public final class JP_Clipboard implements ClipboardOwner {

    /**
     * @param args
     */
    public static void main(String... aArgs) {
        JP_Clipboard textTransfer = new JP_Clipboard();

    }

A: You need import for TextTransfer or it must be in same package.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create decorator for class to apply dataclass and JsonSchemaMixin ...not working I did review all the existing SO questions, googled around as best I could, tried a few different options, but can't seem to get what I want working.
Background
Simple problem - I've got a bunch of dataclasses in my code.
I'd like to have them all changed to inherit from the dataclasses-jsonschema JsonSchemaMixin so that I can programmatically generate a schema for them all.
Of course the simple approach is I could change all instances in the code everywhere to inherit from the JsonSchemaMixin mixin.
But I was thinking I could also write my own decorator that would a) apply @dataclass, and b) mixin dataclasses-schema in one go.  ...my thinking being less chance of errors, and I could try writing a class decorator (I've only ever created and used my own function decorators)
# OLD

@dataclass
class X:
    ....

# Add the mixin `by hand` everywhere

@dataclass
class X(JsonSchemaMixin):
    x: int
    y: float

# What I want is to make my own decorator to do both:

@dataclass_mixedin
class X:
    x: int
    y: float

Problem
Pretty simple problem - I can't get this to work :(
What I've tried
try number 1:
from dataclasses import dataclass
from dataclasses_jsonschema import JsonSchemaMixin

def dc_schema(cls):
    @dataclass
    class _decorated(JsonSchemaMixin, cls):
        pass
    return _decorated

@dc_schema
class Data:
    x: int
    y: float

a = Data(x=5,y=1.1)

The above fails, with unexpected keyword args x & y.
Try number 2:
def dc_schema2(cls):
    # Try applying dataclass() directly:
    class _decorated(JsonSchemaMixin, cls):
        pass
    _decorated = dataclass(_decorated)
    return _decorated

@dc_schema2
class Data2:
    x: int
    y: float

d = Data2(x=1, y=1.1)

Again - this fails with unexpected arguments.
So I'm guessing I'm missing dataclass walking the class structure to find class variables with annotations (https://docs.python.org/3/library/dataclasses.html).
But I can't figure out how to do that

A: A possible solution is to use a metaclass.
See this example:
from dataclasses import dataclass, is_dataclass
from dataclasses_jsonschema import JsonSchemaMixin

class EntityMeta(type):
    def __new__(cls, name, bases, class_dict):
        new_class = super().__new__(cls, name, bases, class_dict)
        return dataclass()(new_class)

class BaseEntity(JsonSchemaMixin, metaclass=EntityMeta):
    pass

class SomeClass(BaseEntity):
    id: str
    name: str

assert is_dataclass(SomeClass)
assert issubclass(SomeClass, JsonSchemaMixin)

x = SomeClass(1, "Hello World")

assert x.id == 1
assert x.name == "Hello World"

class SomeOtherClass(BaseEntity):
    foo: str
    name: str

x = SomeOtherClass("foo", "ufo")
assert x.foo == "foo"
assert x.name == "ufo"

print(SomeOtherClass.json_schema())

I don't recommend this, because you
need anyway to inherit from a base class and there is small difference in code verbosity. You lose useful features like type
hints when coding with the help of MyPy (unless of writing a dedicated plugin), or Pylance, in an IDE that provides that kind of help.
I recommend to take into consideration pydantic: it might have the features you desire.


text:
Q: R remove roman numerals from column I have a table in R with the following information. Some rows in employee have roman numerals, some do not:
employee <- c('JOHN SMITH II','PETER RABBIT','POPE GREGORY XIII', 'MARY SUE IV')
salary <- c(21000, 23400, 26800, 100000)
employee_df <- data.frame(employee, salary)
> employee_df
           employee salary
1     JOHN SMITH II  21000
2      PETER RABBIT  23400
3 POPE GREGORY XIII  26800
4       MARY SUE IV 100000

How would I remove the roman numerals so that employee_df$employee would be the follwing?
JOHN SMITH    PETER RABBIT    POPE GREGORY   MARY SUE

A: Try this:
#Code
employee_df$employee <-gsub('^([0-9]+)|([IVXLCM]+)\\.?$','',employee_df$employee)

Output:
       employee salary
1   JOHN SMITH   21000
2  PETER RABBIT  23400
3 POPE GREGORY   26800
4     MARY SUE  100000

Or cleaner:
#Code2
employee_df$employee <- trimws(gsub('^([0-9]+)|([IVXLCM]+)\\.?$','',employee_df$employee))

Output:
      employee salary
1   JOHN SMITH  21000
2 PETER RABBIT  23400
3 POPE GREGORY  26800
4     MARY SUE 100000

The numeric component of regex is not necessary (Many thanks @BenBolker). You can use:
#Code3
employee_df$employee <- trimws(gsub('([IVXLCM]+)\\.?$','',employee_df$employee))

And obtain the same result.

A: If you mean what you say then you do not want to remove the roman numerals in the string with POPE. If that's correct then a way to remove all other numerals is this:
sub("^(?!\\bPOPE\\b)(.*?)\\s[IVXLCM]+$", "\\1", employee_df$employee, perl = T)
[1] "JOHN SMITH"        "PETER RABBIT"      "POPE GREGORY XIII" "MARY SUE"

Here we are using negative lookahead (?!...)asserting that the strings must not include the substring POPE, and backreference \\1 to 'recollect' whatever is matched prior to the sequence of roman numerals at the end of the string.

A: An option with str_remove
library(dplyr)
library(stringr)
employee_df %>%
        mutate(employee = str_remove(employee, "\\s+[IVXLCM]+"))


text:
Q: How to move folders with names listed in a text file I face the following issue in Windows. I have thousands of subfolders in a main folder (let's call it data\ ) and I want to move a big subset of them in another folder (let's call it data2\ ). In a .txt file I have a list of the exact names of the folders that I want to move.
Is there a way to do that with the cmd?
I make a simple example to make the issue more clear. In the folder data\ I have the subfolders A, B, C, D and E. In a text file I have the list of names:
A C E (one name in each line)
I want to move the subfolders A, C and E to the folder data2.
Thanks a lot :)

A: I suggest using PowerShell instead of plain cmd.  You can take advantage of various Linux command aliases.  To move the folder data\A to data2\A it is as easy as mv data\A data2.  Now you also need to do this as part of a loop, because you have a text file containing the names of all these folders that you would like to move.  I am not on a windows system right now, so I can't test the below code.  I adapted a for loop that I saw here
$files = cat list.txt
foreach ($f in $files)
    { mv data\$f data2 }


text:
Q: Apache authentication against FreeIPA's Kerberos I'm currently trying to set up Apache as an authentication portal. It's supposed to act as a reverse proxy with krb authentication.
My apache server is named portal.example.com (debian container)
My IPA server is named freeipa.example.com (centos container)
Here's my current Apache configuration on portal.example.com:
< Location />
   AuthType Kerberos
   AuthName "Login on test domain"
   KrbAuthRealm TEST.COM
   Krb5Keytab /etc/apache2/portal.keytab
   KrbMethodNegotiate on
   KrbMethodK5Passwd off
   KrbServiceName HTTP/portal.example.com@TEST.COM
   require valid-user
< /Location>

I can't get it working as I want: I don't want it to ask users to enter their password, so I configured firefox in order to let it negotiate the authentication but I always get a 401/Unauthorized. However, if I set KrbMethodK5Passwd to on, and then login with my krb username and password, then I get a 200 http response.
Any idea about how to do it without asking for credentials? :(

A: Check if /etc/apache2/portal.keytab is owned by the webserver user (www-data on debian systems) and only readable by this user (-r--------).
Check if you configured your browser for both the domain test.com and subdomains
about:config
network negotiate-auth.trusted-urls  test.com, .test.com


text:
Q: How to use implicit operator with preprocessor directives? I have a shared class library. So I want to create implicit operators accroding to platform.
But this code isn't working.
using System;
using GTANetworkAPI;

namespace FoxRPShared.Utils {
    public class Vector3 {
        public float X;
        public float Y;
        public float Z;
        public Vector3() { }
        public Vector3(float x, float y, float z) {
            X = x;
            Y = y;
            Z = z;
        }
#if SERVER
        public static implicit operator GTANetworkAPI.Vector3(Vector3 v) => new GTANetworkAPI.Vector3(v.X, v.Y, v.Z);
        public static implicit operator Vector3(GTANetworkAPI.Vector3 v) => new Vector3(v.X, v.Y, v.Z);
#else
        public static implicit operator RAGE.Vector3(Vector3 v) => new RAGE.Vector3(v.X, v.Y, v.Z);
        public static implicit operator Vector3(RAGE.Vector3 v) => new Vector3(v.X, v.Y, v.Z);
#endif
    }
}

Unfortunately, I get an error like Cannot implicitly convert type "FoxRPShared.Utils.Vector3" to "GTANetworkAPI.Vector3".(CS0029)

If I remove directives, code compiles.


text:
Q: jQuery - detecting if a button has been pressed You'll have to forgive me for asking a somewhat trivial question here, but I'm generally curious if there's a better way of detecting if a button has been pressed. I'm guessing this would apply to anchor tags also.
Presently I have two submit buttons (so I cannot use $(form).submit in this case), both of which will change another field when they are activated:
<button id="accept" type="submit">Accept</button>
<button id="decline" type="submit">Decline</button>

To achieve this I have detected a click event, and the Enter keypress event separately:
$('#accept').click(function(){ $('#decision').val('Agree');  })
$("#accept").keyup(function(event){
    if(event.keyCode == 13){
        $('#decision').val('Agree');
    }
});

I guess more than anything I'm wondering if there is a way to simplify this code, as it's rather cumbersome, especially if there's a lot of processing (you could create a function, but that's yet another step) and since jQuery seems to have most things covered, I'm surprised after trawling the internet I can't find a cleaner solution.
(with the above I was worried about other ways to mimic the button press, such as hitting space, although that seems to be covered!)
Thanks!

A: you can do something like this to make the click a little better: (using a function is necessary here to get something better):
function setDecision(value){
    $('#decision').val(value);
}

$('button[type=submit]').click(function() {
    var val = $(this).text();

    setDecision(val);
});

$("button[type=submit]").keyup(function(event){
    var val = $(this).text();

    if(event.keyCode == 13){
        setDecision(val);
    }
});

A: For a button element, both the spacebar and the enter key being presses on a button will generate a click event according W3C event specifications. You should not have to do any special processing to handle that.
As for using $(form).submit(), you can. Just change your buttons to not implicitly submit the form by chaning them to push buttons (W3C):
<button type="button" id="...">...</button>

Then in your handler you can do:
$('#accept,#decline').click(function(event){
    $('#decision').val($(event.target).text());
    $(form).submit();
}

If you need to you can do some processing on $(event.target).text() to make 'Decline' null/emptystring if necessary.

A: I think I understand your question, and there may be some precedence to be found in this related topic.
jQuery: how to get which button was clicked upon form submission?
This method avoids adding the .click() event to each button, though that may be a viable option for your application.
Hope this helps!
Mason

A: Add name="decision" and value="Accept" / value="Decline" (accordingly) to the submit buttons
This way you do not need javascript to handle this at all...
And if the 'Accept' button is the first, then pressing enter inside any form field will also trigger that one
Sample:
<form action="1.html" method="get">

<input type="text" name="in">

<button type="submit" name="decision" value="Accept">Accept</button>
<button type="submit" name="decision" value="Decline">Decline</button>

</form>


text:
Q: Executing existing Python Code in Azure ML I have a code written Python and I need to deploy it on Azure ML. The python code consists of many function and returns the output in Jason format.
However when implemented on Azure ML, there are no errors. But, there is no result as such generated. It is displaying the input dataset for both Result Dataset and Python device dataset.
Can I know, how to go about it. I'm new to Azure ML, and have no clue how to go about it

A: https://learn.microsoft.com/en-us/azure/machine-learning/machine-learning-python-data-access
There is everything explained in detail in the link above. Look at sections:
1)How to install the Azure Machine Learning Python client library
2)Access datasets from a local Python application
In fact, I didn't try it by myself. But I hope it will be helpful.


text:
Q: WPF, telerik - GroupRows by Binding I want to use the ShowGroupPanel in the telerik: RadGridView but I want to group them by a Property.
MainClass -Object

*

*Id

*GroupProperty

*Name

how can I Group my Rows after GroupProperty?
<telerik:RadGridView AutoGenerateColumns="False" IsReadOnly="True" CanUserReorderColumns="True"
    CanUserDeleteRows="False" CanUserInsertRows="False" ShowGroupPanel="True" EnableRowVirtualization="True" Name="GridViewlist"
    ItemsSource="{Binding Path=List, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectionUnit="FullRow" >
    <telerik:RadGridView.Columns>

A: You can turn on/off grouping on a column by setting the Groupable property.
If you want to allow grouping on other columns, but show your GroupProperty by default you may want to use:
<telerik:RadGridView.GroupDescriptors>
    <telerik:GroupDescriptor Member="GroupProperty"
                                 SortDirection="Ascending">

     </telerik:GroupDescriptor>
</telerik:RadGridView.GroupDescriptors>


text:
Q: ajax start event does not work in async false I create an ajax request with async false. And then I put some text into textbox in global ajax start event. The input text is not filled before ajax request completed in IE and chrome but it is filled in firefox. Please see below.
<input type="text" id="text1" />
<input type="button" id="button1" />
<script type="text/javascript">
       $(document).ajaxStart(function () {
           $("#text1").val("testing");
       });

      $("#button1").click(function(){
           $.ajax({
               type: 'POST',
               url: '',
               data: '',
               async: false,
               dataType: 'text',
          });
       });
</script>

What is a reason for that? How can I solve this?
P.S. It is working well with async true.


text:
Q: Tkinter Inverting Color of Radiobutton Trying to invert the colour of the radiobutton when it has been selected. Currently when the button is not selected the background is grey and foreground white. When it is selected the background goes white but the foreground also stays white. I want to be able to change the colour of the foreground when it has been selected.
import tkinter as tk
root = tk.Tk()
v = tk.IntVar()
v.set(0)

periods = [
    ("Current"),
    ("-1"),
    ("-2"),
    ("1 Week"),
    ("2 Weeks"),
    ("1 Month"),
    ("3 Months"),
]
def ShowChoice():
    print (v.get())

for val, period in enumerate(periods):
    tk.Radiobutton(root,
              text=period,
              indicatoron =0,
              padx=20,
              variable=v,
              command=ShowChoice,
              value=val,
              background='gray15',
              foreground='snow',).pack(side=tk.LEFT)
root.mainloop()

This is what the buttons currently look like:

Thanks in advance

A: All it was is
selectcolor='gray25'

Options for Radiobutton look like this now:
for val, period in enumerate(periods):
    tk.Radiobutton(root,
              text=period,
              indicatoron =0,
              padx=20,
              variable=v,
              command=ShowChoice,
              value=val,
              background='gray15',
              foreground='snow',
              selectcolor='gray25').pack(side=tk.LEFT)
root.mainloop()

And the outcome is this:


text:
Q: Tensorflow rebuild warning when running I have installed tensorflow through pip, it showed its downloaded and installed properly, but when I run code it shows to rebuild it with correct compiler flags.
This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)
to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

tf.Tensor(-1883.2466, shape=(), dtype=float32)

Above output is what I get as error when I'm running this code:
import tensorflow as tf
print(tf.reduce_sum(tf.random.normal([1000, 1000])))

Is it a bug or anything, please help as I'm trying to learn deep learning

A: The warning is not complaining that AVX is not enabled. It is just an informative message saying only for some ops, Intel's oneDNN would be used and AVX or AVX2 would be turned on.
Please add label "comp:mkl", as requested at https://software.intel.com/content/www/us/en/develop/articles/intel-optimization-for-tensorflow-installation-guide.html


text:
Q: How do I take user input and put on path? I'm very new to python. I want to capture user images by taking user input first and creating a folder in the train and test directory using the given input. For example if user inputs "Bill" as his name, the train and test directory will create a folder named Bill and store images in the particular train folder from webcam. What I got so far is:
originaldir='C:\\Users\\Administrator\\Deep-Learning-Face-Recognition-master'
trainingdir='C:\\Users\\Administrator\\Deep-Learning-Face-Recognition master\\Datasets\\Train'
testingdir='C:\\Users\\Administrator\\Deep-Learning-Face-Recognition-master\\Datasets\\Test'
username = input("Enter username:")
print("Username is: " + username)
os.chdir(trainingdir)
os.mkdir(username)
os.chdir(testingdir)
os.mkdir(username)

I am able to create folders of the user's given name but I am not able to store photos captured from webcam in the specific training folder. It throws a syntax error.
file_name_path = trainingdir '/'  username  '/' + '.jpg'
cv2.imwrite(file_name_path, face)

I'm getting the syntax error below:
file_name_path = trainingdir '/' username '/' + '.jpg'  SyntaxError: invalid syntax –

A: A way with string format:
file_name_path = "%s/%s/%s.jpg" % (trainingdir, username, filename)

A: if you are creating the path by adding strings you need to use '+' operator for each string.
like:
file_name_path = trainingdir + '/' + username + '/' + str(count) + '.jpg'


text:
Q: Storing CSV data in Ruby hash Say I have a CSV file with 4 fields,
ID,name,pay,age

and about 32,000 records.
What's the best way to stick this into a hash in Ruby?
In other words, an example record would look like:
{:rec1 => {:id=>"00001", :name => "Bob", :pay => 150, :age => 95 } }
Thanks for the help!

A: You can use the Excelsior rubygem for this:
csv = ...
result = Hash.new
counter = 1
Excelsior::Reader.rows(csv) do |row|
   row_hash = result[("rec#{counter}".intern)] = Hash.new

   row.each do |col_name, col_val|
      row_hash[col_name.intern] = col_val
   end
   counter += 1
end

# do something with result...

A: Typically we'd want to use an :id field for the Hash key, since it'd be the same as a primary key in a database table:
{"00001" => {:name => "Bob", :pay => 150, :age => 95 } }

This will create a hash looking like that:
require 'ap'

# Pretend this is CSV data...
csv = [
  %w[ id     name  pay age ],
  %w[ 1      bob   150 95  ],
  %w[ 2      fred  151 90  ],
  %w[ 3      sam   140 85  ],
  %w[ 31999  jane  150 95  ]

]

# pull headers from the first record
headers = csv.shift

# drop the first header, which is the ID. We'll use it as the key so we won't need a name for it.
headers.shift

# loop over the remaining records, adding them to a hash
data = csv.inject({}) { |h, row| h[row.shift.rjust(5, '0')] = Hash[headers.zip(row)]; h }
ap data

# >> {
# >>     "00001" => {
# >>         "name" => "bob",
# >>          "pay" => "150",
# >>          "age" => "95"
# >>     },
# >>     "00002" => {
# >>         "name" => "fred",
# >>          "pay" => "151",
# >>          "age" => "90"
# >>     },
# >>     "00003" => {
# >>         "name" => "sam",
# >>          "pay" => "140",
# >>          "age" => "85"
# >>     },
# >>     "31999" => {
# >>         "name" => "jane",
# >>          "pay" => "150",
# >>          "age" => "95"
# >>     }
# >> }

A: Check out the Ruby Gem smarter_csv, which parses CSV-files and returns array(s) of hashes for the rows in the CSV-file.  It can also do chunking, to more efficiently deal with large CSV-files, so you can pass the chunks to parallel Resque workers or mass-create records with Mongoid or MongoMapper.
It comes with plenty of useful options - check out the documentation on GitHub
require 'smarter_csv'
filename = '/tmp/input.csv'
array = SmarterCSV.process(filename)

=>

[ {:id=> 1, :name => "Bob", :pay => 150, :age => 95 } ,
 ...
]

See also:

*

*https://github.com/tilo/smarter_csv

*http://www.unixgods.org/~tilo/Ruby/process_csv_as_hashes.html

A: Hash[*CSV.read(filename, :headers => true).flat_map.with_index{|r,i| ["rec#{i+1}", r.to_hash]}]


text:
Q: Windows 10: A file and folder ownership mess and how to fix it In Windows 10 Pro 64 v 1903
I had a problem changing access permissions for a new user, and a comment on my question about that told me to check the ownership of the folders appearing in the error messages. When I did, I found that their owner name is not that of my account, but is a security ID (SID). The commenter then suggested that I change the ownership of those folders to my admin account. Because this involves a huge number of files, I didn't want to just change the whole directory tree without checking on the current status of ownership. So I used PowerShell to give me a spreadsheet of all my ownerships. I've never looked at ownerships before and I don't know what to make of the results. In particular, I wonder if I need to be concerned about (a) ownerships that are empty, (b) ownerships that are SIDs, and (c) files and folders on my data drive that are not owned by my account.
Here is a summary of the ownerships I found. Drive C is the system drive and has no user-generated data. (I don't use the desktop or Windows' default folders for documents, downloads, etc.) Drive D is my data drive, but also has some system-generated folders and files, as described in the notes below.
Owner                                                  Drive C      Drive D
---------------------------------------------------------------------------
(empty)                                                    365            7
BUILTIN\Administrators                                  57,512        3,320
<ComputerName>\Administrator                                 2
<ComputerName>\<AdminUserName>                          29,568        7,551
NT AUTHORITY\IUSR                                                         2
NT AUTHORITY\LOCAL SERVICE                                 794
NT AUTHORITY\NETWORK SERVICE                               166
NT AUTHORITY\SYSTEM                                    152,389            4
NT SERVICE\TrustedInstaller                             89,829            1
O:S-1-5-21-156xxxxxxx-xxxxxxxxxx-xxxxxxxxxx-1003                          5
O:S-1-5-21-229xxxxxx-xxxxxxxxxx-xxxxxxxxxx-1000              4
O:S-1-5-21-229xxxxxx-xxxxxxxxxx-xxxxxxxxxx-1002             20            2
O:S-1-5-21-297xxxxxxx-xxxxxxxxxx-xxxxxxxxxx-1017            18
O:S-1-5-21-341xxxxxxx-xxxxxxxxxx-xxxxxxxxxx-1000                    183,706
O:S-1-5-21-397xxxxxx-xxxxxxxxx-xxxxxxxxx-4882392             2
Window Manager\DWM-1                                         4
                                                       -------      -------
                                                       330,673      194,598

Notes on the ownerships on C:

*

*Empty:

*

*Five system-generated files in the root folder: "hyberfil.sys", "pagefile.sys", "swapfile.sys", and two encryption data files.

*Several ".dll" and ".bin" files

*Many empty folders

*Hundreds of ".png" files in folders under "C:\Windows\servicing\LCU\"

*<ComputerName>\Administrator:

*

*Two ".regtrans-ms" files in "C:\Windows\appcompat\Programs"

*O:S-1-5-21-229...-1000:

*

*A folder in the recycle bin ("D:\$RECYCLE.BIN") and the only file in that folder, "desktop.ini"

*Two ".sys" files in paths containing my computer manufacturer's name

*O:S-1-5-21-229...-1002:

*

*A folder in the recycle bin and the only file in that folder, "desktop.ini"

*Two ".sys" files in paths containing my computer manufacturer's name

*Six empty folders and ".log" files in paths containing "Norton" or "Symantec"

*One file without an extension under "C:\Windows\System32\"

*Nine ".tmp" files in "C:\Windows\Temp\"

*O:S-1-5-21-227...-1017:

*

*18 ".regtrans-ms" files under "C:\Users\Default" and "C:\Windows\System32\"

*O:S-1-5-21-397...-4882392:

*

*Two ".regtrans-ms" files under "C:\Windows\System32\"

Notes on the ownerships on D:

*

*Empty:

*

*Two system-generated encryption data files

*The only five files on D with filespecs larger than 255 (all user-generated)

*BUILTIN\Administrators:

*

*One system-generated encryption data file

*One system-generated, hidden folder, "D:\System Volume Information"

*Some copies of system-generated files, such as ".dmp" and ".xml" files retrieved after a blue-screen crash and a Symantec ".sdbz" file, as well as copies of some software installation ".exe" files

*Many files in the recycle bin ("D:\$RECYCLE.BIN")

*Thousands of user-generated files, including txt, png, htm, php, and pdf files, and some user-generated folders

*NT AUTHORITY\IUSR:

*

*Two user-generated files, a txt and a csv.

*NT AUTHORITY\SYSTEM:

*

*The root "D:\"

*One folder in the recycle bin

*Two system-generated, hidden folders: "D:\Recovery" and "D:\Recovery\Logs"

*NT SERVICE\TrustedInstaller:

*

*A folder in the recycle bin

*O:S-1-5-21-156...-1003:

*

*A folder in the recycle bin

*Four user-generated folders

*O:S-1-5-21-229...-1002:

*

*A folder in the recycle bin and the only file in that folder, "desktop.ini"

*O:S-1-5-21-341...-1000:

*

*Over 180,000 folders and files, which as far as I can tell are all user-generated. These are not contiguous, but are interspersed with folders and files owned by BUILTIN\Administrators and <ComputerName>\<AdminUserName>.

I've never dealt with the concept of ownership before, so I don't know how unusual these results are. But it does seem that there at least might be a problem with the SID owners because I was not able to change the access permissions for a new user on folders that have those owners. So, as mentioned above, my questions are:

*

*Are the empty ownerships something to be concerned about and fixed?

*Should I change some or all of the SID ownerships to be owned by my account?

*Should I do a recursive change of all files and folders on the data drive (D:) to make them be owned by my account?

*Is there anything else I should be concerned about with this?

*Is there anything more you need to know in order to answer these questions?


text:
Q: How to make this global variable hold its value between calls? I'm trying to reduce the amount of times the database object is initialized in my data access file (variable database inside the file tree-rxdb.mjs). I created a global variable to hold a reference to the database object and check if it has been initialized before, if it has I just return the variable to the caller without initializing it again. For some reason, the database it's always undefined every time I call this function, even after I have successfully written to the database using the same code. Weirdly, the same doesn't happen to the dao variable inside tree.mjs even though I believe I'm giving it the same treatment but obviously getting differing results. I'm just emulating this code but for some reason it's not working out for the database variable inside tree-rxdb.mjs, what am I not seeing?
tree-rxdb.mjs
import RxDB from 'rxdb';
import adapter from 'pouchdb-adapter-leveldb'
import leveldown from 'leveldown'
import Log from '../utils/log.mjs';
const TAG = 'fruits-rxdb'

RxDB.plugin(adapter)

var database;

const treeSchema = {
    title: 'fruits schema',
    description: 'Describes a fruits tree',
    version: 0,
    type: 'object',
    properties: {
        name: { type: 'string' },
        desc: { type: 'string' },
        url: { type: 'string' },
        state: {
            type: 'integer',
            enum: [0, 1]
        },
        favorite: {
            type: 'boolean'
        },
        dateAdded: { type: 'string' },
        userId: { type: 'string' }
    }
}

async function connectDB() {
    Log.debug(`Database object = ${database}`, TAG)
    if (database) return database;
    database = await RxDB.create({
        name: 'fruitsdb',
        adapter: leveldown,
        password: (process.env.DB_PASSWORD || 'myfruitsJsPasswordTemp')
    });
    await database.collection({
        name: 'trees',
        schema: treeSchema
    });
    Log.debug('Database has been initialized', TAG)
    return database;
}

export async function create(tree) {
    const db = await connectDB();
    db.trees.insert(tree.JSON);
}

tree.mjs
import util from 'util'
import logger from '../utils/log.mjs'
import Fruit from './Fruit.mjs'
const TAG = "tree-dao"

var dao;

async function model() {
    logger.debug(`DAO object = ${util.inspect(dao)}`, TAG)
    if(dao) return dao;
    dao = await import(`../dao/tree-${process.env.MODEL}`);
    logger.debug(`DAO model has been initialized: ${util.inspect(dao)}`, TAG);
    return dao;
}

export async function add(){
    const Fruit = new Fruit(undefined, 'Peach', 'peach 123',
        'http://something.com', 0, false, new Date().toISOString(), 'admin');
    (await model()).create(Fruit);
}

app.mjs
import express from 'express';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import { default as fruits } from "./routes/fruits"
import * as tree from './models/tree.mjs'

const app = express();

app.use(logger("dev"));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use("/fruits", fruits);

const add = async () => {
    await tree.add();
    await tree.add();
    await tree.add();
};
add();

export default app

A: The problem is that database is only written when the promise of the creation is resolved. So calling connectDB multiple times will have database === undefined each time.
You should cache the creation-promise and return that from connectDB if it already exists.
Instead of
if (database) return database;
database = await RxDB.create({
    name: 'fruitsdb',
    adapter: leveldown,
    password: (process.env.DB_PASSWORD || 'myfruitsJsPasswordTemp')
});

do
if (database) return await database;
database = RxDB.create({
    name: 'fruitsdb',
    adapter: leveldown,
    password: (process.env.DB_PASSWORD || 'myfruitsJsPasswordTemp')
});

A: I was missing an await in tree.mjs. The line (await model()).create(Fruit); should be await (await model()).create(Fruit); the inner await was throwing me off. Now it's behaving like I expected it to.

A: In Node.js global scope is equal to the files' own scope. If you want to define a global variable accesible by all files at runtime, use global


text:
Q: Targeting a Collection - Liquid Greetings Shopify Pals!
I have a website at: https://www.blakesseedbased.com/ (password: TopSecretPass)
The Goal:
We will have products that vary in quantity and would like to display this quantity information between the product title and price from the featured home page products (raspberry, chocolate chip, pineapple).
The Issue:
Currently we're able to add content to this area, but we cannot seem to get the if else statement to work correctly. We have a collection called "Snack Bars" however our logic isn't recognising this and injecting the proper code. We tried changing the collection Snack Bars to lower and uppercease snack-bars/Snack-Bars but no luck.
The Logic:
IF the product item is from the Snack Bar collection, add the box quantity (box of 12).
Else, add "no quantity"
The Code:
{% if product.collections contains 'snack-bars' %}
         Box of 12
{% else %}
          No Box Amount
{% endif %}

Thanks in advance!!

A: Greetings Birdie Golden!
The issue you're hitting is that product.collections is an array of Collection objects when you're accessing it in Liquid, and no collection object will ever equal a string value.
Luckily, we can easily create an array of handles using the map filter and assign that to a variable, like this:
{% assign collection_list = product.collections | map: 'handle' %}
{% if collection_list contains 'snack-bars' %}
...

The map filter above will create a new array using just the value that you pass it, so the collection_list variable will be an array of just-the-handles.  Since handle is a string, we can use contains as expected to see if the value we want is in the list.
Hope that helps!


text:
Q: A "model plane" or a "plane model": What's the difference? Which question is correct? If they are both correct, what's the difference between these questions?

*

*How do you make a model plane?

*How do you make a plane model?


text:
Q: How do i remove my sender hostname in mail header how do i change example.com to localhost in mail header. I am using ubuntu postfix server and swift mailer for sending mails.
Received: from localhost (example.com. [12.12..121])
    by mx.google.com with ESMTP id s22si1128306qge.14.2016.04.06.00.17.45
    for <............@gmail.com>;
    Wed, 06 Apr 2016 00:17:45 -0700 (PDT)

Thanks

A: You may try to use directly the FQDN (exemple.com) of your mail sending host instead of "localhost" when specifying your Swift_???Transport either directly (Smtp), or via the command line arguments of you mail command (Sendmail).


text:
Q: Spring.net ContextRegistry.GetContext fails with 2 interface implementations I have a .net application, that uses Spring.net.
Also there are 2 implementations of one interface. Which one should be used - it is based on configuration file.
The bootstrap for Spring has
<objects>
 <object id="Impl1" name="Impl1" type="namespace.Impl1, IInterface" >
  </object>
  <object id="Impl2" name="Impl2" type="namespace.Impl2, IInterface" >
  </object>
</objects>

It fails on
var appContext = ContextRegistry.GetContext();

The error message is:

An unhandled exception of type
  'System.Configuration.ConfigurationErrorsException' occurred in
  Spring.Core.dll
Additional information: Unsatisfied dependency expressed through
  constructor argument with index 2 of type [namespace.IInterface] : No
  unique object of type [namespace.IInterface] is defined : expected
  single matching object but found 2:
  System.Collections.Specialized.OrderedDictionary

A: I found another configuration,  where autowire setting was set as autodetect.
<object id="workspaceExportService" type="namespace.Imp3, Namespace"
          autowire="autodetect" />

This class Imp3 has a constructor with IInterface parameter. So, It tries to resolve the implementation of IInterface, but find two of them.
As a solution, you can add lazy-init="true" attribute to object node.


text:
Q: why an event handler doesnt work on the element that created on other function in javascript This is my code, can i ask why the onclick event doesnt work for ini element which is the input.
JavaScript:
window.onload = function() {
    var img = document.getElementsByTagName('img');
    var div = document.createElement("div");
    img[0].onclick = function(event) {
        document.body.appendChild(div);
        var sion = document.getElementsByTagName('div');
        var val = document.defaultView.getComputedStyle(sion[0], null);
        var mouseX = event.clientX;
        var mouseY = event.clientY;
        document.styleSheets[0].cssRules[0].style.top = (mouseY - 20) + "px";
        document.styleSheets[0].cssRules[0].style.left = (mouseX - 20) + "px";
        var ini = document.createElement("input");
        document.body.appendChild(ini);
        var hoftag = document.styleSheets[0].cssRules[0].style.height;
        var result = hoftag.replace("px", "");
        result = parseInt(result);

        document.styleSheets[0].cssRules[1].style.top = (event.clientY - 20 + result) + "px";
        document.styleSheets[0].cssRules[1].style.left = (event.clientX - 40) + "px";
    };
    ini.onclick = function(event) {
        alert("hi");
    };
};

HTML:
<img src="jlin.jpg" id="image">

A: The problem is with the scopes of the variables. Variable ini only lives within img[0].onclick = function(event) {. Please refer to this great picture from "JS ninja" book:

To fix your code, try:
img[0].onclick = function(event){
    ...
    var ini = document.createElement("input");
    document.body.appendChild(ini);
    ini.onclick = function(event){
        alert("hi");
    };
    ...
};


text:
Q: Strategy for determining the boundaries of triple integral Calculate triple integral(zdV) over the area $E$, where $E$ is bounded by the planes $y=0 ~ z=0$ and $x+y=2$ and the cylinder $y^2 + z^2 = 1$ in the first octant.

I have seen the correct answer already, however I have difficulty in understanding why the limits in the triple integral are taken in that way. Could anyone give me advice on what strategy I should use to determine the boundries of the integrals in such relatively complex cases?
Here is the answer is the correct for the sake of completeness:
$$\displaystyle \int\limits_0^1 \int\limits_0^{\sqrt{1-y^2}} \int\limits_0^{2-y} \ z~dx~dz~dy$$
Thanks in advance

A: You want it in the first octant so we have $$x\ge0, y\ge0,z\geq0$$ The lower limit of $y$ is zero but another limit of it is ruled by $y^2+z^2=1$. Since $z=0$ is one of our boundary , so $y^2=1$ and so $y=1$. Clearly, the latter equation gives us the restriction for $z$, that is: $$z\big|_0^{\sqrt{-y^2+1}}$$ Note that here again we have $z\ge 0$. For $x$ is the same, that is $$x\big|_0^{2-y}$$ since we already know that $x+y=2$.


text:
Q: How to Make Eclipse (C++) Switch from/to Debug Perspective Automatically? How do you make Eclipse CDT automatically switch to the Debug perspective when I begin debugging, and automatically switch back to the previous perspective when the debuggees have terminated?
Note: In case this wasn't clear: I'm looking for a solution for switching to Debug and back.

A: I've been after this myself (as it would be very convenient) every now and again, but so far in my search I've come up with nothing.
Short of writing an Eclipse plugin to switch to previous perspective on debugger disconnect there is no "automatic" solution.
However, I have grown accustomed to the CTRL+SHIFT+F8 which is default shortcut (on Windows) to switch back to "Previous Perspective".

A: Perspective Switcher has a configurable feature to automatically switch back to the previous perspective when the debugger terminates.  It can also be configured to automatically switch to any perspective based on file extensions you specify.  When an editor gets activated (i.e. opening a file or switching to a different file), then the perspective is automatically changed.  This makes it easy to work with multiple languages.

A: When you manually switch to Debug mode for the first time while debugging it will show a checkbox with 'Automatically  switch to Debug in future'.


text:
Q: How to evaluate this integral $\int_0^\infty\frac{\sin^2(ax)}{(ax)^2\sqrt{x^2+bi}} dx$? Evaluate-

$$\int_0^\infty\frac{\sin^2(ax)}{(ax)^2\sqrt{x^2+bi}} dx$$

where $a>0$ and $b>0$ are two given constants and $i$ is an imaginary unit.
I have no clue how to solve this problem. I tried to use the Residue theorem to imitate the method of calculating the Dirichlet integral, but it didn't work.


text: Q: Fist time install on fresh machine with bios f.33 I have installed Ubuntu on my hp 250 g7 notebook it previously comes with win10 but i switched to Ubuntu now every time i start my pc i have to repeat whole process of booting via GNU grub ver 2.04. What should I do for login directly from my hard disc if the dvd is not inserted it shows install os on hard disc


text:
Q: tar fail mode: Not exiting on write fail I would like to know why tar is not exiting on a mkdir error. I am measuring the time it takes to untar the linux kernel multiple times, until it fails. I am using the tar command inside the while loop condition statement.
Here is the command I am running:
while sudo /usr/bin/X11/time -a -o out tar -xvf /home/USER_NAME/linux-3.12.tar -C /hdd3/; do sudo mv /hdd3/linux-3.12/ /hdd3/linux-3.12_`date +%s`; done

Here is the kind of error I get:
tar: linux-3.12/net: Cannot mkdir: No space left on device

I get the above error and many more for similar locations.
Basically, I am trying to get the while loop to exit as soon as tar can no longer untar the linux kernel into the /hdd3 directory. The body of the while loop changes the directory name of where the linux kernel was just created.
I want to this while loop to exit when tar is unable to write any further.

A: Your tar, time or sudo must be faulty, not returning the correct exit status. My tar (GNU tar 1.27.1) finally says
tar: Exiting with failure status due to previous errors
 and exits with status 2.

You might check the exit status of tar, time and sudo to find out the culprit.


text:
Q: Can a predator prey isocline, with Holling's Type IV functional response, be generated in R? Using R, I am trying to graphically analyze a predator-prey interaction, with a Holling's Type IV functional response, using predator prey isoclines.
This is the script I am using:
library(deSolve)
library(phaseR)
model.LV <- function(t, y, parameters){
  with(as.list(parameters),{
    N<-y[1]
    P<-y[2]
    dN <- r*N*(1-N/K)-(1.511*N/((N^2/9.2724)+N+1.483))*P*N
    dP <- -b*P+(1.511*N/((N^2/9.2724)+N+1.483))*a*P*N

    list(c(dN,dP))
  })
}

params.LV<-c(r=0.8,K=10,b=4.2,a=6)

data.LV<-as.data.frame(lsoda(c(N=3,P=3),seq(1,100,by=0.5), model.LV, params.LV))

plot(data.LV$N, data.LV$P, type="l", col="blue", main="Trajectory for Type-IV Functional Response",
     xlab="Prey density N", ylab="Predator density P", xlim=c(0,5), ylim=c(0,5))
nullclines(model.LV, x.lim=c(0,5),y.lim=c(0,5), parameters=params.LV, system="two.dim", colour=c("green","red"), add=TRUE)

The isocline should have a parabola with two vertical lines intersecting it, but the graphic is completely wrong. Can this simulation be ran in R? I've seen it done in MATLAB, and was told that R is probably not powerful enough to run this simulation.
Thank you.


text:
Q: Gradle is not place WebJar contents into the correct place in my Jar file I've got a basic Java application in which I would like to use WebJars. I use Gradle as my build system. I would like to use the WebJars for Bootstrap and JQuery so I can easily reference and update them in my Spring-Boot/ThymeLeaf application. The application is basically the one from the form tutorial located here
As I understand it Gradle should place all the files from the WebJars into the META-INF folder in my Jar file. If I understand everything correctly the Spring-Boot resource handler will then load resource from META-INF/ when I reference something in my html page that starts with /webjars/
Unfortunately this doesn't work (yet). Since I see in Tomcat's log output that the resource handler is correctly installed. I decided to check if the files are actually in my Jar file.
When I extract my Jar file the META-INF folder only has a file called MANIFEST.MF with some information about Spring Boot. There is a BootStrap-3.3.7.Jar and a JQuery-3.2-1.Jar file in BOOT-INF/lib but I don't think that is where they are supposed to end up. (Or am I wrong and is there error somewhere in the resource handler?).
How do I tell gradle to do the right thing with these files when I run gradle build?
My gradle.build file looks like this:
buildscript {
    ext {
        springBootVersion = '1.5.8.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: "jacoco"

jar {
    baseName = 'gs-serving-web-content'
    version =  '0.0.1'
}

bootRun {
    addResources = true
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.webjars:jquery:3.2.1")
    compile("org.webjars:bootstrap:3.3.7")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

A: Gradle is doing the right thing as the jars should be packaged in BOOT-INF/lib. The root of each jar in BOOT-INF/lib is then added to the classpath from where each its webjar related content in META-INF content should be found.
I'd recommend asking another question that focuses on what your application's doing at runtime. As far as I can tell, everything's working as it should at build time.


text:
Q: Creating Ruby Gem to insert HTML/JavaScript into main Application I create a Rails Engine to easily include a JavaScript plugin for rails apps. The problem is that this plugin is really only for development and when pushing an app to production the developer needs to remove the require marx in the javascript manifest file and then the actual call in the JavaScript.
What I'm hoping to do is allow the developer to just add this to the Gemfile with gem 'marxjs-rails', group: :development and setup some configurations in config/application.rb or config/environments/development.rb for the plugin settings.
The gem should then insert html to the parent application:
<script src='marx.js'></script>
<script>
  var marx = new Marx()
</script>

I've been playing around with a helper method to insert the html but I can't get it to insert it as html. Rails continues to escape the HTML. Though I don't really like this path any how.
I've been looking through the jasmine-gem and rack-olark as examples, but can't quite get anything to work.
UPDATE
This is not the solution I'm really looking for but this may help others and is what I'm using till I can track down a better way to do this. You can view the whole code here but I'll give you the highlights:
# lib/marxjs/rails.rb
require "marxjs/rails/version"
require "marxjs/view_helpers"

module Marxjs
  module Rails
    class Engine < ::Rails::Engine
      initializer "marxjs.view_helpers" do
        ActionView::Base.send :include, ViewHelpers
      end
    end
  end
end

and the view helpers:
# lib/marxjs/view_helpers.rb
require 'erb'

module Marxjs
  module ViewHelpers
    include ActionView::Helpers::OutputSafetyHelper

    def render_marxjs options={}, dev_only=true
      if dev_only == false || (dev_only && ::Rails.env.development?)
        binding.local_variable_set(:options, options.to_json)
        template_file = ::File.read(::File.expand_path('../templates/marxjs.erb', __FILE__))
        raw ERB.new(template_file).result(binding)
      end
    end
  end
end

biggest thing to take away here is the include ActionView::Helpers::OutputSafetyHelper and also the require 'erb'
This gives us the ability to load a template erb file and use ERB.new to render it and use raw to keep rails from escaping the html. I also bound an options variable to the binding object to send it to the template.
<script src="assets/marx.js"></script>
<script>
  var marx = new Marx(<%= options %>);
</script>

and finally in my main rails application I call render_marxjs(controls: 'toggle-all') in the application.html.haml (or .erb if you like)
Again I'm still looking for someone to help me handle this without a view helper method and also to be able to set some configurations via an environment file, but I hope this may help some...

A: You can achieve this without creating an engine.

*

*Add a file called lib/marxjs/script_inserter.rb
module Marxjs
  module ScriptInserter
    BODY_TAG = %r{</body>}

    JS_SCRIPT = %q{
      <script src='marx.js'></script>
      <script>
        var marx = new Marx()
      </script>
    }

    def insert_marxjs
      if (
        response.content_type == 'text/html' &&
        response.body.match(BODY_TAG)
      )
        response.body = response.body.gsub(BODY_TAG, JS_SCRIPT + '\\0')
      end
    end
  end
end

*Add lib/marxjs/railtie.rb
module Marxjs
  class Railtie < Rails::Railtie
    initializer "marxjs-rails" do |app|
      ActionController::Base.send :include Marxjs::ScriptInserter
      ActionController::Base.after_filter :insert_marxjs
    end
  end
end

*Update lib/marxjs/rails.rb
require "marxjs/rails/version"
require "marxjs/view_helpers"
require "marxjs/script_inserter"

# move rails initialization code to railtie.rb

*Add the gem to Gemfile
gem 'marxjs-rails', group: :development

A: The rack-mini-profiler gem does something like this, where it adds UI elements to your screen but only in development (by default).  See https://github.com/MiniProfiler/rack-mini-profiler/blob/master/lib/mini_profiler_rails/railtie.rb

A: For me the best way is to add the engine on all environments, but require it separately on application.html.haml:
= javascript_include_tag "mark.js" if Rails.env.development?

Be sure to add it to your config/application.rb as well to be compiled:
config.assets.precompile += %w( mark.js )


text:
Q: Is the Playstation VR headset region-locked? I'm going to be buying a Playstation VR headset from the USA. Will it work with my European PS4?

A: Yes you can use a EU Playstation 4 and a US Playstation VR. However do make sure that you have an adapter for the difference in the US and EU power cables.
A few sources:
https://www.reddit.com/r/PSVR/comments/4vsvao/will_there_be_a_region_code_for_the_psvr/
https://www.quora.com/Can-I-use-PlayStation-VR-Launch-Bundle-in-other-countries


text:
Q: Нахождения файла и выполнения команды Здравствуйте мне нужно просматривать папку через Python код и при обнаружении нового файла выполнить команду на тот же найденный файл но имя не известно как это сделать и возможно ли?

A: Можно так сделать:
from os import listdir
from os.path import isfile, join
mypath = 'D:\\'
for f in listdir(mypath):
    if isfile(join(mypath, f)):
        print(f) # тут ваши действия


text:
Q: Why does execve() does not return on success? I have read the man pages.
All I understood from this link http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/lr2/zid-7281.htm is that
A successful call to execve does not have a return value because the new process image overlays the calling process image
I am not very clear as to why this will happen ? And if the new process overlays the calling process, why does it return on failure only and not on success ?

A: Because if it fails to do what it is trying to do, i.e. replace the process with the new one, then it makes sense to return, to inform the caller that it failed.
If it succeeds, then the code that called execve() is no longer present, it has been replaced by the successful execution of that function, so obviously it cannot do anything any more. Returning is such a thing.


text:
Q: Powershell Remove-Item not working from a function I needed to replace the Alias 'cd' with my function named 'cd'.
I tried to remove the alias from a function, but it didn't work. The following was a simple testing script,
function remove_alias {
    get-command cd
    Remove-Item -Path Alias:cd
    get-command cd
}
remove_alias

I ran it from Windows 10 and native Powershell version 5.1.18362.752. The output was below. The alias didn't change
PS> . .\test_remove_alias.ps1

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Alias           cd -> Set-Location

If moved the Remove-Item out of the function. It worked.
get-command cd
Remove-Item -Path Alias:cd
get-command cd

The output was below and the alias was replaced by my function.
PS> . .\test_remove_alias2.ps1

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Function        cd

I'd like to remove the alias from a function as function is better way to manage code.
This seems to be a generic question but I haven't found any answer from internet.

A: I think this is just a problem with your changes being scoped only to the inside of your function. To fix this, you can call the function within the current scope by prefixing with . , see PowerShell - execute script block in specific scope
function remove_alias {
    get-command cd
    Remove-Item -Path Alias:cd
    get-command cd
}

. remove_alias

Result:
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
get-command : The term 'cd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:4 char:5
+     get-command cd
+     ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (cd:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Also works within a ps1 file, also called with . :


text:
Q: ExtJS and JWplayer I have an application in ExtJS that uses a JWplayer for reproduce some videos. But i'm experiencing some weird bugs.
When the page loads it seems that the JWPlayer won't load and then I receive a black line where the player should be displayed.
I am loading the jwplayer inside a extjs panel.
Has anyone experienced this? Is there a way to solve that?

A: I have created a draggable floating panel with an instance of JW Player inside and it works just find.
Check it out, maybe you are doing something wrong there.
Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create('Ext.panel.Panel',{
            title: 'Testing JW Player',
            width: 480,
            height: 300,
            floating: true,
            draggable: true,
            layout: 'fit',
            renderTo: Ext.getBody(),
            items: [{
                xtype: 'panel',
                id: 'testing'
            }],
            listeners: {
                afterrender : function(component) {
                    jwplayer('testing').setup({
                    file: "http://videos-jp.jwpsrv.com/zWLy8Jer/videos/HkauGhRi-1753142.mp4?77c801d752d5207784c49e7ed80fb953798fae0fcca03ecf79558491aa7db70fc9392eb19e958e847c3e486d709eab9f57d25c86934c4b6091bc427de8ab078578054aaba8384904c4762bd67442c3809470687047",
                    image: "http://demo.jwplayer.com/homepage/homepage_preroll.jpg"
                    });
                    }
                }
        });
    }
});

You can access my fiddle here: https://fiddle.sencha.com/#fiddle/blb

*

*JWPlayer is a nice library by the way, this was the first time I saw it, nice work.

A: For those whom may have the same issue that I had.
I was placing the player in a panel but I didn't set the height of the component. Since the player takes a while to load I guess that the Extjs just see it as a common div with no size.


text:
Q: redis key scheme for analytics I want to create analytics using redis - basic counters per object, per hour/day/week/month/year and total
what redis data structure would be effective for this and how can I avoid doing many calls to redis?
would it better to have each model have this sets of keys:
hash - model:<id>:years => every year has a counter
hash - model:<id>:<year> => every month has a counter
hash - model:<id>:<year>:<month> => every day has a counter
hash - model:<id>:<year>:<month>:<day> => every hour has a counter
if this scheme is correct, how would I chart this data without doing many calls to redis? I would have to loop on all year in model:<id>:years and fetch the month, then loop on the month, etc? Or I just grab all fields and their values from all keys as a batch request and then process that in the server?

A: It's better to use a zset for this instead of an hash. Using timestamp as score you will be able to retrieve data for specific time range
For a date range you will use model:<id>:<year>:<month>, for an hour range (using model:<id>:<year>:<month>:<day>) and so on...
Indeed, if the date range is larger than a month (e.g. from January 1st 2014 to March 20th 2014), you will have to retrieve multiple zset (model:<id>:2014:01, model:<id>:2014:02 and model:<id>:2014:03) and merge the results.
If you really want to do a date range inside a single request, you can always store day precision data inside model:<id>:<year>. And if you want to handle date range over multiple years, you will just need to have a single zset e.g. model:<id>:byDay.
However, please note that storing historical data will increase memory consumption over time so you should already think about data retention. With Redis you can either use EXPIRE on zset or do it yourself with crons.


text:
Q: after installing gunicorn3 how to fix Sub-process /usr/bin/dpkg returned an error code (1) root@vps292598:~# sudo apt upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
8 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up python3.5 (3.5.2-2ubuntu0~16.04.12) ...
/var/lib/dpkg/info/python3.5.postinst: 9: /var/lib/dpkg/info/python3.5.postinst: /usr/bin/python3.5: not found
dpkg: error processing package python3.5 (--configure):
 subprocess installed post-installation script returned error exit status 127
dpkg: dependency problems prevent configuration of python3:
 python3 depends on python3.5 (>= 3.5.1-2~); however:
  Package python3.5 is not configured yet.

dpkg: error processing package python3 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-pkg-resources:
 python3-pkg-resources depends on python3:any (>= 3.3.2-2~); however:
  Package python3 is not configured yet.

dpkg: error processing package python3-pkg-resources (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-setuptools:
 python3-setuptools depends on python3-pkg-resources (= 20.7.0-1); however:
  Package python3-pkg-resources is not configured yet.
 python3-setuptools depends on python3:any (>= 3.3.2-2~); however:
  Package python3 is not configured yet.

dpkg: error processing package python3-setuptools (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-gunicorn:
 python3-gunicorn depends on python3-pkg-resources; however:
  Package python3-pkg-resources is not configured yet.
 python3-gunicorn depends on python3-setuptools; however:
  Package python3-setuptools is not configured yet.
 python3-gunicorn depends on python3:any (>= 3.3.2-2~); however:
  Package python3 is not configured yet.

dpkg: error processing package python3-gunicorn (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of gunicorn3:
 gunicorn3 depends on python3-gunicorn (= 19.4.5-1ubuntu1.1); however:
  Package python3-gunicorn is not configured yet.
 gunicorn3 depends on python3:any (>= 3.2~); however:
  Package python3 is not configured yet.

dpkg: error processing package gunicorn3 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-wheel:
 python3-wheel depends on python3:any (>= 3.3.2-2~); however:
  Package python3 is not configured yet.

dpkg: error processing package python3-wheel (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of dh-python:
 dh-python depends on python3:any (>= 3.3.2-2~); however:
  Package python3 is not configured yet.

dpkg: error processing package dh-python (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 python3.5
 python3
 python3-pkg-resources
 python3-setuptools
 python3-gunicorn
 gunicorn3
 python3-wheel
 dh-python
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Before installing gunicorn, it might make sense to ensure Python3 is properly installed and configured:
$ sudo apt install -f --reinstall python3 python3.5 python3-minimal python3.5-minimal libpython3.5-minimal

If this completes without a problem, then you can try to install the gunicorn package.


text:
Q: Difference between uwsgi_pass and proxy_pass in Nginx? I'm running uWSGI behind Nginx and have been using proxy_pass to get Nginx to hit uWSGI. Is there any benefit to switch to uwsgi_pass. If so, what is it?

A: uwsgi_pass uses an uwsgi protocol. proxy_pass uses normal HTTP to contact with uWSGI server. uWSGI docs claims that this protocol is better, faster and can benefit from all of uWSGI special features.
Are there any real benefits? Yes. You can send to uWSGI information what type of data you are sending and what uWSGI plugin should be invoked to generate response. With http (proxy_pass) you won't get that. More on that you can find in uWSGI docs.
But even if there aren't any documented benefits of using uwsgi protocol instead of http for you, you should use uwsgi protocol if you can, because uwsgi is the main protocol of uWSGI server and it just fits better here.
If you want to use uwsgi protocol you must change http-socket parameter in uWSGI start script to socket.


text:
Q: Change user-agent headers only in incognito mode with a Chrome extension I'm trying to have my extension only work while in incognito mode. I can't seem to get it to work by adding "incognito": "split" to my manifest.json, and adding an if statement in the background.js looking for chrome.extension.inIncognitoContext.
Edit:
Okay, so what I'm trying to do is change my user-agent headers while only in incognito. I'm doing this based off this: http://elaineou.com/2016/02/19/how-to-use-chrome-extensions-to-bypass-paywalls/
It works for the said link above, but I can't seem to get it to work for all website while in incognito mode. This also won't be released, and I do have the allowed in incognito button checked.
manifest.json
{
  "name": "Incognito Chrome Extension",
  "version": "0.1",
  "description": "This is an incognito chrome extension.",
  "incognito": "split",
  "permissions": ["webRequest", "webRequestBlocking",
                   "http://localhost:3000/",
                   "http://*/*",
                   "https://*/*"
                  ],
  "background": {
    "scripts": ["background.js"]
  },
  "manifest_version": 2
}

Background.js
var ALLOW_COOKIES = [""];
if(chrome.extension.inIncognitoContext){
    function changeRefer(details) {
    foundReferer = false;
    foundUA = false;

    var reqHeaders = details.requestHeaders.filter(function(header) {
      // block cookies by default
      if (header.name !== "Cookie") {
        return header;
      }

      allowHeader = ALLOW_COOKIES.map(function(url) {
        if (details.url.includes(url)) {
          return true;
        }
        return false;
      });
      if (allowHeader.reduce(function(a, b) { return a || b}, false)) { return header; }

    }).map(function(header) {

      if (header.name === "Referer") {
        header.value = "https://www.google.com/";
        foundReferer = true;
      }
      if (header.name === "User-Agent") {
        header.value = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";
        foundUA = true;
      }
      return header;
    });

    // append referer
    if (!foundReferer) {
      reqHeaders.push({
        "name": "Referer",
        "value": "https://www.google.com/"
      });
    }
    if (!foundUA) {
      reqHeaders.push({
        "name": "User-Agent",
        "value": "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"
      });
    }
    console.log(reqHeaders);
    return {requestHeaders: reqHeaders};
  }

  function blockCookies(details) {
    for (var i = 0; i < details.responseHeaders.length; ++i) {
      if (details.responseHeaders[i].name === "Set-Cookie") {
        details.responseHeaders.splice(i, 1);
      }
    }
    return {responseHeaders: details.responseHeaders};
  }

  chrome.webRequest.onBeforeSendHeaders.addListener(changeRefer, {
    urls: ["<all_urls>"],
    types: ["main_frame"],
  }, ["requestHeaders", "blocking"]);

  chrome.webRequest.onHeadersReceived.addListener(blockCookies, {
    urls: ["<all_urls>"],
    types: ["main_frame"],
  }, ["responseHeaders", "blocking"]);
}

A: I guess that your concern is the extra redundant background page process?
Add "incognito": "split" in the manifest file and close the extension's background page in non-incognito mode:
// background page or event page:
if (!chrome.extension.inIncognitoContext) {
    window.close();
}

Content scripts will still be run in non-incognito pages. To counter that, just exit your code after checking whether your extension is running in incognito mode (similar to the above check).
Note: If the extension is going to be published and only useful in incognito mode, consider checking whether incognito mode is enabled and offer instructions if it's disabled. See e.g. How can I enable my chrome extension in incognito mode?


text:
Q: How to save Image from FLIR AX5 camera into raw format using eBus sdk Intro: I am trying to write a program which connects to a FLIR AX5(GigE Vision) camera and then save images after regular intervals to a pre-specified location on my PC. These images must be 14bit which contains the temperature information. Later I need to process these images using openCV to get some meaningful results from obtained temperature data.
Current Position: I can save image at regular interval but the image which I am getting doesn't contain 14 bit data but 8 bit data instead. This even after I change the PixelFormat to 14 bit, CMOS and LVDT bit depths to 14 bit. I checked the resulting .bin file in matlab and found that the max pixel value is 255 which means image is being stored in 8 bit format. I am using the sample code provided by eBus SDK to do this job. In this code I have made some changes as per my requirement.
Please help in saving the image in the raw format from which I can read the temperature data.
P.S. Relevant code is here.
            // If the buffer contains an image, display width and height.
            uint32_t lWidth = 0, lHeight = 0;
            lType = lBuffer->GetPayloadType();

            cout << fixed << setprecision( 1 );
            cout << lDoodle[ lDoodleIndex ];
            cout << " BlockID: " << uppercase << hex << setfill( '0' ) << setw( 16 ) << lBuffer->GetBlockID();

            if (lType == PvPayloadTypeImage)
            {

                // Get image specific buffer interface.
                PvImage *lImage = lBuffer->GetImage();
                // Read width, height.
                lWidth = lImage->GetWidth();
                lHeight = lImage->GetHeight();
                cout << "  W: " << dec << lWidth << " H: " << lHeight;
                lBuffer->GetImage()->Alloc(lWidth, lHeight, lBuffer->GetImage()->GetPixelType());
                if (lBuffer->GetBlockID()%50==0) {
                    char filename[]= IMAGE_SAVE_LOC;
                    std::string s=std::to_string(lBuffer->GetBlockID());
                    char const *schar=s.c_str();
                    strcat(filename, schar);
                    strcat(filename,".bin");
                    lBufferWriter.Store(lBuffer,filename);
                }

A: Be sure that the streaming is configured for 14 bits stream.
Before create PvStream  you have to set PixelFormat to 14 bits. If you PvDevice object it's called _pvDevice:
_pvDevice->GetParameters()->SetEnumValue("PixelFormat", PvPixelMono14);
_pvDevice->GetParameters()->SetEnumValue("DigitalOutput", 3);


text:
Q: How to update label after submitting mutually exclusive check boxes? I am working on C# coding and I am having problems when clicking the submit button, and select a few different combinations of checkbox answers, they are not updating with "correct" or "incorrect" correctly. How do I adjust the code to where if ONLY Answer2 and Answer3 are checked, that only the "Correct" label will show? Even if one of the wrong answers is selected with the right ones, that'll display "incorrect".
if (Answer2.Checked && Answer3.Checked == true)
    {
        lblQuestionResult4.ForeColor = System.Drawing.Color.Green;
        lblQuestionResult4.Text = "Correct";
    }
    else
    {
        if (Answer1.Checked && Answer4.Checked == true)
        {
            lblQuestionResult4.ForeColor = System.Drawing.Color.Red;
            lblQuestionResult4.Text = "Incorrect";
        }

A: Here is one approach.  In your code snippet there are unaccounted for conditions.  This code avoids that by assuming the worst, and only setting the values for the correct case if it occurs (i.e. Answers 2 & 3 are checked, and all the rest are unchecked).
var color = System.Drawing.Color.Red; //assume incorrect answer
var label = "Incorrect";

if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)
{
  //only the 2 correct answers have been checked
  color = System.Drawing.Color.Green;
  label = "Correct";
}

// set the controls
lblQuestionResult4.ForeColor = color;
lblQuestionResult4.Text = label;


text:
Q: Why doesn't Raiserror get invoked? If I have this block inside a transaction:
Begin Try
  Begin Transaction tran

    Declare @ExpiryDate varchar(100)
        Set @ExpiryDate= (Select NewExpiryDate from NIT n where n.NITNo= @NitNo)
        IF(CONVERT(DATE,@ExpiryDate)) < convert(date,getdate())
        Begin
                RAISERROR('error occurred', 16,1);
                return;
        End

  Commit Transaction tran
End Try
Begin Catch
                select ERROR_MESSAGE()

                Rollback transaction tran1
End Catch

...it reaches the catch block but an error is never raised. It never throws error. Why?

A: I would rewrite it as:
Begin Try
  Begin Transaction tran;

  Declare @ExpiryDate DATE =(Select NewExpiryDate from NIT where n.NITNo= @NitNo);

  IF @ExpiryDate < convert(date,getdate())
      RAISERROR('error occurred', 16,1);

  Commit Transaction tran;
End Try
Begin Catch
   IF @@TRANCOUNT > 0 Rollback transaction tran1;
   THROW;  -- rethrowing error
End Catch


text:
Q: Dynamically change UITableViewCell height - Swift 4 How do I go about dynamically changing the UITableViewCell height? I've tried implementing the following, but for some reason, it isn't working. The code crashes as soon as I load the view controller displaying this table view
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let cell = tableView.cellForRow(at: indexPath) as! AvailableRideCell
    return cell.getHeight()
}

This is the getHeight function in my AvailableRideCell
func getHeight() -> CGFloat {
    return self.destinationLabel.optimalHeight + 8 + self.originLabel.optimalHeight + 8 + self.priceLabel.optimalHeight
}

And this is the optimalHeight function
extension UILabel {
    var optimalHeight : CGFloat {
        get {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude))
            label.numberOfLines = 0
            label.lineBreakMode = NSLineBreakMode.byWordWrapping
            label.font = self.font
            label.text = self.text
            label.sizeToFit()
            return label.frame.height
        }
    }
}

A: Keep in mind that UITableViewCell is reused. So getting the height of the current cell can be unstable.
A better way is to have one fake/placeholder cell (I call the calculator cell) and use that to calculate the size of the cell.
So in the heightForRowAt method, you get the data instead of the cell.
Put that data inside the calculator cell and get the height from there.

A: You code crashes because of this line
let cell = tableView.cellForRow(at: indexPath) as! AvailableRideCell

From Apple Documentation we know that this method is used for optimization. The whole idea is to get cells heights without wasting time to create the cells itself. So this method called before initializing any cell, and tableView.cellForRow(at: indexPath) returns nil. Because there are no any cells yet. But you're making force unwrapping with as! AvailableRideCell and your code crashed.
So at first, you need to understand, why you should not use any cells inside the cellForRow(at ) method.
After that, you need to change the logic so you could compute content height without calling a cell.
For example, in my projects, I've used this solution
String implementation
extension String {
    func height(for width: CGFloat, font: UIFont) -> CGFloat {
        let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let actualSize = self.boundingRect(with: maxSize,
                                           options: [.usesLineFragmentOrigin],
                                           attributes: [NSAttributedStringKey.font: font],
                                           context: nil)
        return actualSize.height
    }
}

UILabel implementation
extension String {
    func height(for width: CGFloat, font: UIFont) -> CGFloat {
        let labelFrame = CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)
        let label = UILabel(frame: labelFrame)
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.font = font
        label.text = self
        label.sizeToFit()
        return label.frame.height
    }
}

With that, all you need to do is to compute your label and store its font.
var titles = ["dog", "cat", "cow"]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // number of rows is equal to the count of elements in array
    return titles.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let cellTitle = titles[indexPath.row]
    return cellTitle.height(forWidth: labelWidth, font: labelFont)
}

Dynamic rows height changing
If you'll need to update row height, all you need to do is to call this method when your content had been changed. indexPath is the index path of changed item.
tableView.reloadRows(at: [indexPath], with: .automatic)

Hope it helps you.

A: You don't mention if you are using Auto Layout, but if you are, you can let Auto Layout manage the height of each row. You don't need to implement heightForRow, instead set:
tableView.rowHeight = UITableViewAutomaticDimension

And configure your UILabel with constraints that pin it to the cell's content view:
    let margins = contentView.layoutMarginsGuide
    NSLayoutConstraint.activate([
        cellLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
        cellLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
        cellLabel.topAnchor.constraint(equalTo: margins.topAnchor),
        cellLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor)
    ])

Each row will expand or contract to fit the label's intrinsic content size. The height is automatically adjusted if the device landscape/portrait orientation changes, without re-loading the cell. If you want the row height to change automatically when the device's UIContentSizeCategory changes, set the following:
cellLabel.adjustsFontForContentSizeCategory = true