text:
Q: Removing small black contours/unwanted contours in Python I have been at this all day, how to we remove the small back noise in the red circle? I would need it to work on other samples of pictures like this.
The idea I used is to findContours and then add a mask with all the small black noise that is less than a certain area (trial and error).
Removing noise in red ellipse
image = cv2.imread("11_Image_after_noise_removal.png")

# copy image
img = image.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY)
thresh = 255 - thresh
# Use cv2.CCOMP for two level hierarchy
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP,
                                       cv2.CHAIN_APPROX_SIMPLE)  # Use cv2.CCOMP for two level hierarchy
cv2.drawContours(img, contours, -1, (0, 255, 0), 1)

cv2.imshow("First detection", img)
# loop through the contours
for i, cnt in enumerate(contours):
    # if the contour has no other contours inside of it
    if hierarchy[0][i][3] != -1:  # basically look for holes
        # if the size of the contour is less than a threshold (noise)
        if cv2.contourArea(cnt) < 70:
            # Fill the holes in the original image
            cv2.drawContours(img, [cnt], 0, (0, 0, 0), -1)
            # display result
# Visualize the image after the Otsu's method application

cv2.imshow("Image after noise removal", img)

cv2.waitKey(0)
cv2.destroyAllWindows().destroyAllWindows()

A: You might check the contour area using area = cv.contourArea(cnt) and if it is below some threshold, ignore it.
Here is the OpenCV documentations:
https://docs.opencv.org/4.3.0/dd/d49/tutorial_py_contour_features.html


text:
Q: How do I describe a count-constrained, CSV-serialized multiselection field using Open API? Using the OpenAPI specification, I want to specify a field in a data model with the following requirements communicated:

*

*It should be serialized as a CSV-string.

*It should only contain values from an enumeration.

*It should contain as many or fewer items as the number specified.

This schema ultimately drives a dropdown in our application's UI.
We can communicate #1 and #2 easily enough, but I wasn't sure about the idiomatic way to communicate #3. My current solution abuses the maxItems property to do this:
{
    enum: ["beagle", "collie", "pitbull"],
    format: "csv",
    maxItems: 2,
    type: "string"
 }

The next best choice seems like the pattern property to describe a CSV string, but that seems like a non-obvious hint for rendering a UI. Since format is open-ended, would it be better use a custom format like csv(2), which communicates the desired item count?
Unfortunately, I cannot alter the API's data model to accept a string array (as opposed to a string serialized as CSV), which would be the most ideal solution.
What's the best way to describe such a field using OpenAPI?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fixing sprockets deprecation: method `register_engine` is deprecated Versions

*

*Ruby 2.4.3

*Rails 5.1.3

*sprockets 3.7.3

*jquery-tmpl-rails 1.1.0

Issue:
The latest version of jquery-tmpl-rails triggers a sprockets deprecation warning of:
DEPRECATION WARNING: Sprockets method `register_engine` is deprecated.
Please register a mime type using `register_mime_type` then
use `register_compressor` or `register_transformer`.

https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
(called from block (2 levels) in <class:Railtie> at /my/path/to/gems/jquery-tmpl-rails-ef6f58001d41/lib/jquery-tmpl-rails/engine.rb:10)

Attempts at resolution:
Following the deprecation warning, the problem within the gem simply resides here: https://github.com/jimmycuadra/jquery-tmpl-rails/blob/master/lib/jquery-tmpl-rails/engine.rb#L10
Which is currently:
app.assets.register_engine(".tmpl", JqueryTemplate)
I then visited the sprockets guide for handling deprecations, extensibility and compliance with sprockets 2,3,4. https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
I made my best attempt at rectifying the problem with a commit on this fork here: https://github.com/oceanshq/jquery-tmpl-rails/commit/de7a59894f512efb3c1eba432da3517f21d921a2
Which was:
asset.register_mime_type 'application/javascript', extensions: ['.tmpl'], charset: :unicode
asset.register_preprocessor 'application/javascript', JqueryTemplate

However, this attempt simply deals out breakages when trying to run the web application at all or test it on the CI. So obviously I've missed something.
Questions

*

*Is there a simple syntactical approach I am missing here?

*It was unclear to me in the docs, although register_engine is deprecated in Sprockets 3, is it actually possible to migrate from register_engine while staying in Sprockets 3?

*If we are remaining on Sprockets 3 for the foreseeable future, is it kosher to silence this? Generally I work viewing deprecations as 'bugs that need fixing'


text:
Q: how to uncheck all other nodes after check one node which are all on same top level? I did once successfully but somehow lost original code, since I'm not expert in jstree so your help is very much appreciated, below is my attempt:
    .on("select_node.jstree", (e, data) => {
      const node = data.instance.get_node(data.node, true);
      if (!node) {
        return;
      }
      if (node[0].ariaLevel == "1" && node[0].ariaSelected == "true") {
        const siblings = node.siblings;
        if (siblings.length > 0)
          siblings(".selected").each(function () {
            data.instance.check_node(this, 0);
          });
      }
    })

runs OK until when i try to loop siblings and uncheck, can anyone help me on below code:   siblings(".selected").each(function () {
data.instance.check_node(this, 0);
});

A: figured out, paste code here in case someone needs reference or give me comment to optimize it, thanks.
    .on("select_node.jstree", async (e, data) => {
      var level = data.node.parents.length;
      var selected = data.node.state.selected;
      var text = data.node.text; // for info only
      var id = data.node.id;
      if (level == 1 && selected) {
        var tree = $(this.treeContainer).jstree(),
          parent = tree.get_node(data.node.parent),
          children = parent.children,
          siblings = [];
        children.forEach(function (child) {
          if (child !== id) siblings.push(child);
        });
        siblings.forEach(function (sibling) {
          var sNode = tree.get_node(sibling);
          if (sNode.state.selected) {
            tree.uncheck_node(sNode);
          }
        });
      }
    })


text:
Q: What is the "correct" way of making a console menu? I've been tasked with writing a program that presents a menu with 4 options to the user, then to take input and do some calculations with the input. What is the best way of doing this?
For reference, my approach is to make an enum with all of the menu options and have it control a switch statement to control what to do.
    private enum MainMenu
    {
        CYLINDER = 1,
        CUBE,
        SPHERE,
        QUIT,
        UNASSIGNED
    }
    MainMenu mmChoice = MainMenu.UNASSIGNED;
    string sInput = Console.ReadLine();
    switch (mmChoice)
    {
        case MainMenu.CYLINDER:
            doWork1();
            break;
        case MainMenu.CUBE:
            doWork2();
            break;
        case MainMenu.SPHERE:
            doWork3();
            break;
        case MainMenu.QUIT:
            Exit();
            break;
        case MainMenu.UNASSIGNED:
            break;
    }

What happens within the cases isn't important but I'd like to know how to make this work syntactically. Since I'm using input from the user, taken by Console.ReadLine() which returns a string and I need it in the form of an enum, I'm lost as to how to proceed. How do I relate sInput with mmChoice and operate the switch?
I know this is sort of asking 2 questions, but for the purposes of the task, I'd prefer someone to answer the specific case and maybe someone can tell me the best general approach in a comment.

A: Just for fun, object-oriented approach
public interface IJob
{
    void Do();
}

public class JobOne : IJob
{
    public void Do()
    {
        // do something
    }
}

public class JobTwo : IJob
{
    public void Do()
    {
        // do something different
    }
}

public class DoNothing : IJob
{
    public void Do() { }
}

public class JobRunner
{
    private readonly Dictionary<string IJob> _jobs;
    private readonly IJob _doNothing;

    public JobRunner()
    {
        _jobs = new Dictionary<string, IJob>
        {
            { "one", new JobOne() },
            { "two", new JobTwo() },
        };
        _doNothing = new DoNothing();
    }

    public void Run(string jobKey)
    {
        _jobs.GetValueOrDefault(jobkey, _doNothing).Do();
    }
}

Usage will look like this:
vr runner = new JobRunner();

var input = Console.ReadLine();
runner.Run(input);

A: Here is another approach, which is to create a class that represents a MenuItem, which has a description and an associated method that should be called if that item is chosen.
private class MenuItem
{
    public string Description { get; set; }
    public Action Execute { get; set; }
}

Then we can populate a list of these items, to be shown in a MainMenu
// Our private list of menu items that will be displayed to the user
private static List<MenuItem> MenuItems;

// A helper method to populate our list.
// We can easily add or remove new items to the menu
// without having to worry about changing an
// enum or adding a command to a switch block
private static void PopulateMenuItems()
{
    MenuItems = new List<MenuItem>
    {
        new MenuItem {Description = "View balance", Execute = ViewBalance},
        new MenuItem {Description = "Deposit", Execute = Deposit},
        new MenuItem {Description = "Withdraw", Execute = Withdraw},
    };
}

Note that each item has an Execute property, which is of type Action, and they are assigned values above. These values are actually methods that can be defined elsewhere in the project. Each method is currently just a stub that calls a helper method to display a title and another helper method to prompt the user to go back to the main menu, but they could contain real functionality:
private static void ViewBalance()
{
    ClearAndShowHeading("Account Balance");
    GoToMainMenu();
}

private static void Deposit()
{
    ClearAndShowHeading("Account Deposit");
    GoToMainMenu();
}

private static void Withdraw()
{
    ClearAndShowHeading("Account Withdrawl");
    GoToMainMenu();
}

private static void ClearAndShowHeading(string heading)
{
    Console.Clear();
    Console.WriteLine(heading);
    Console.WriteLine(new string('-', heading?.Length ?? 0));
}

private static void GoToMainMenu()
{
    Console.Write("\nPress any key to go to the main menu...");
    Console.ReadKey();
    MainMenu();
}

So now that we have a list of menu items, we can just create a method to show them, which will also get the user input for which item they select, and then call the associated method (via the Execute property).
Note that there is also some validation done here to ensure the user only selects a valid item. We show the items based on their index in the list (we add one to the index so the list doesn't start with 0.), and then we pass the user input to the int.TryParse method. This method will try to parse the user's input into an integer. If the parsing is successful, the method returns true (and our loop exits) and the out parameter will contain the value.
This is done inside a loop, so if the user enters an invalid number, then we set the cursor back to the beginning of the line, write whitespace over it, and then set the cursor back to the beginning again to re-prompt them for input:
static void MainMenu()
{
    ClearAndShowHeading("Main Menu");

    // Write out the menu options
    for (int i = 0; i < MenuItems.Count; i++)
    {
        Console.WriteLine($"  {i + 1}. {MenuItems[i].Description}");
    }

    // Get the cursor position for later use
    // (to clear the line if they enter invalid input)
    int cursorTop = Console.CursorTop + 1;
    int userInput;

    // Get the user input
    do
    {
        // These three lines clear the previous input so we can re-display the prompt
        Console.SetCursorPosition(0, cursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, cursorTop);

        Console.Write($"Enter a choice (1 - {MenuItems.Count}): ");
    } while (!int.TryParse(Console.ReadLine(), out userInput) ||
             userInput < 1 || userInput > MenuItems.Count);

    // Execute the menu item function
    MenuItems[userInput - 1].Execute();
}

Now, with that out of the way, it's super easy to customize menu items, show them to the user, and execute the correct methods accordingly:
static void Main(string[] args)
{
    PopulateMenuItems();
    MainMenu();

    Console.Write("\nDone! Press any key to exit...");
    Console.ReadKey();
}

Give it a try and see what you think. The menu will look something like this:

Now, what if we want to add a new menu item? Simple! Add this line in the block of code where we assign items to MenuItems inside the PopulateMenuItems method, and run it again:
new MenuItem {Description = "Exit", Execute = Application.Exit}

Now our menu looks like:

A: like Rufus L(How should i convert a string to an enum in C#?) already pointed out in the comments:
all you have to do is convert your input to an enum using TryParse/Parse respectively
please note that it is advisable to use TryParse when dealing with user-input(or pretty much any other time you cant gurantee that parsing will work).
        MainMenu mmChoice = MainMenu.UNASSIGNED;
        Console.WriteLine("?");
        string sInput = Console.ReadLine();
        if(Enum.TryParse(sInput, out mmChoice))
        {
            switch(mmChoice)
            {
                case MainMenu.CYLINDER:
                    Console.WriteLine("cylinder");
                    break;
                case MainMenu.CUBE:
                    Console.WriteLine("cube");
                    break;
                case MainMenu.SPHERE:
                    Console.WriteLine("sphere");
                    break;
                case MainMenu.QUIT:
                    Console.WriteLine("quit");
                    break;
                case MainMenu.UNASSIGNED:
                    break;
            }
        }

EDIT:
since OP asked for a char based solution in the comments:
        Console.WriteLine("?");
        char sInput = Console.ReadKey().KeyChar;
        Console.WriteLine("");
        switch (sInput)
        {
            case 'a':
                Console.WriteLine("cylinder");
                break;
            case 'b':
                Console.WriteLine("cube");
                break;
            case 'c':
                Console.WriteLine("sphere");
                break;
            case 'd':
                Console.WriteLine("quit");
                break;
            default :
                break; // error handling here
       }


text:
Q: Python Programming for Data Science For Loop support Hi everyone I have this task:
Write a python program that takes two numeric inputs x and y.
a) [5 pts] The program should take numeric inputs continuously.
b) [10 pts] The program should ensure the range of x and y is between 0 and 1. If either one of the input values is out of range, smaller than 0 or greater than 1, then the program should quit.
c) [10 pts] Implement XOR gate, where the program returns 1 if both x and y values are different; otherwise, it returns 0.
The program should work for floating-point values.
For example,
If x = .3 and y = .3, then xor output should be 0
If x = .6 and y = .3, then xor output should be 1
If x = .3 and y = .6, then xor output should be 1
If x = .6 and y = .6, then xor output should be 0
So far I have done this but I still keep getting errors
x=float(input("enter x: "))

y=float(input("enter y : "))
while True:

  if(x>=0 and x<=1) and (y>=0 and y<=1):
        def XOR (x, y):
            if x != y:
              return 1
            else:  return 0
  print(XOR(x,y))
continue
  elif(x>=0 and x<=1) and (y>=0 and y<=1):
        break
I get this error
 File "<ipython-input-337-80599671f24c>", line 13
    elif(x>=0 and x<=1) and (y>=0 and y<=1):
    ^
IndentationError: unexpected indent

A: A couple of issues. x can't be both < 0 and > 1. Same for y. You need to try or. Also there's no return from second if or break. But it could be the indentation as I understand. I tried little simpler implementation. Try this out.
def xor(x, y):
    if x != y:
        return 1
    else:
        return 0

def main():
    x = float(input("Enter x: "))
    y = float(input("Enter y: "))
    if x < 0 or x > 1 or y < 0 or y > 1:
        print("Invalid input")
        return
    print(xor(x, y))
    if xor(x, y) == 1:
        main()

if __name__ == "__main__":
    main()

Also tried fixing your code and seems to work now:
x=float(input("enter x: "))

y=float(input("enter y : "))

if(x>0 and x<1) and (y>0 and y<1):
  def XOR (x, y):
    if x != y:
      return 1
    else:  return 0
  print(XOR(x,y))

A: While the loop will get input until the input is empty. This might work
def XOR(x, y):
    if x != y:
        return 1
    else:
        return 0

while True:
    str=input("Enter X and Y:")
    if str=="":
        break
    x,y=map(float,str.split())
    if (x<0 and x>1) and (y<0 and y>1):
        break
    else:
        print(XOR(x,y))


text:
Q: Can we reuse Seeds and RutaBasic annotations for multiple script executed sequentially on same cas object we have multiple ruta script which is setup to run sequentially on incoming emails. Is it a good idea to create seeds and rutabasic annotations once and use them to execute multiple ruta script one by one and once all the scripts are executed we empty the cas.
CAS cas = jCas.getCas();
//initialize the seeds and ruta basic
for (String rutaScript : rutaScripts) {
//execute the ruta one by one

}
//clear the cas

A: The TokenSeed annotations are commonly only created once as they should represent some simple static layer. The RutaTokenSeedAnnotator, for example, creates only new annotations if there are no TokenSeed annotations yet. They can be shared like any other annotation.
The RutaBasic annotations store additional information about the annotations. They need to be updated for each addition or removal of any annotations, i.e internal maps need to be up to date all the time or else the rules will be executed incorrectly. The RutaBasic annotations can be shared across different analysis engines processing the same CAS and the RutaEngine provides parameters configuring the internal update strategy. These parameters are named PARAM_INDEX_** or PARAM_REINDEX_**.
If there are only two consecutive RutaEngines in your pipeline, then you can set PARAM_REINDEX_UPDATE_MODE to NONE as no other analysis engine modified the indexes.
If runtime is not an issue, then you can set PARAM_REINDEX_UPDATE_MODE to COMPLETE and the RutaEngine will update everything.
If you know that analysis engines in between two RutaEngine do not remove any annotations, then you can set PARAM_REINDEX_UPDATE_MODE to ADDITIVE. The internal update is faster in this mode.
The other parameters can be used to optimize different aspects of the Ruta indexing and reindexing improving speed as well as memory consumption.


text:
Q: Calculate integral $\int x^{1 \over x} dx$ Are there any known methods so that we can calculate the integral below :
$$
\int x^{1 \over x} dx
$$

A: Using $$\bullet\; x = e^{\ln x}$$ and $$\displaystyle \bullet\; n\cdot \ln(m) = \ln(m)^n$$
We can write $$\displaystyle x^{\frac{1}{x}} = e^{\ln(x)^{\frac{1}{x}}} = e^{\frac{\ln x}{x}}$$
Now Using $$\displaystyle \bullet e^x = 1+\frac{x}{1!}+\frac{x^2}{2!}+\frac{x^3}{3!}+...........\infty$$
So we get $$\displaystyle e^{\frac{\ln x}{x}} = 1+\left(\frac{\ln x}{x}\right)+\frac{1}{2!}\cdot \left(\frac{\ln x}{x}\right)^2+\frac{1}{3!}\cdot \left(\frac{\ln x}{x}\right)^3+........\infty$$
Now $$\displaystyle \int e^{\frac{\ln x}{x}}dx = \int \left[1+\left(\frac{\ln x}{x}\right)+\frac{1}{2!}\cdot \left(\frac{\ln x}{x}\right)^2+\frac{1}{3!}\cdot \left(\frac{\ln x}{x}\right)^3+........\infty\right]dx$$
https://en.wikipedia.org/wiki/Sophomore%27s_dream


text:
Q: jquery load json when document load i confuse why my this simple code is wrong.
i just want to list json data in select when document is load.
this is my jquery code :
<script>
$(document).ready(function(){
        $("#choose").load(function(event){
            $.getJSON('data/colors.json', function(jd) {
                $('#choose').html('<option value="' + jd.name'">' + jd.name + '</option>');
                $('#choose').append('<option value="' + jd.name'">' + jd.name + '</option>');
            });
        });
   });
</script>

this is my html :
<select id="choose" style="width:200px">

   </select>

and last this is my json file :
[
{
"name": "Yoza",
"age" : "22",
"sex": "male"
},
{
"name": "nayla",
"age" : "18",
"sex": "female"
}
]

how to load that json with each. so i can load more than that data.

A: Try
$(function(){

    $.getJSON('data.json', function(jd) {
        $.each(jd, function(i, v){
            $('#choose').append('<option value="' + v.name + '">' + v.name + '</option>');
        })
    })

});

Demo: Fiddle

A: Try this
      var data = [];

    $.getJSON( 'data/colors.json', function( jd ) {

          $.each( jd, function( k,v ){

              data.push('<option value="' + v.name'">' + v.name + '</option>');

             });
            $('#choose').append( data.join('') );
        });

A: why do you wait for $('#choose') to be loading ? Your function is executed when document is ready, so $('#choose') is ready too.


text:
Q: How to override M2M field names and models in Django with an existing database? I'm using Django 3.1.3 and working with an existing postgresql database. Most of the models and fields names of this DB are badly chosen and/or way too long. Most of the time its easy to change them with some handy Django options like so :
class NewModelName(models.Models):

    new_field_name = models.CharField(max_length=50, db_column='old_field_name')

    class Meta:
        managed=False
        db_table='database_old_table_name'

But let say I want to change a M2M field name and the corresponding model name. I'd like to have something like :
class Foo(models.Models):

    new_m2m_field_name = models.ManyToManyField('RelatedModel', blank=True, db_column='old_m2m_field_name')

    class Meta:
        managed=False
        db_table='foo_old_table_name'

class RelatedModel(models.Models):

    name = models.CharField(max_length=50)

    class Meta:
        managed=False
        db_table='related_model_old_table_name'

But if I do that, Django will throw an error stating
django.db.utils.ProgrammingError: relation "foo_new_m2m_field_name" does not exist. It is like it is ignoring the db_column option. Any idea how I could get to a similar result ?
Thanks!

A: From Django documentation regarding ManyToManyField

ManyToManyField.db_table The name of the table to create for storing
the many-to-many data. If this is not provided, Django will assume a
default name based upon the names of: the table for the model defining
the relationship and the name of the field itself.

Also depending on column names (non standard names) in original database you might have to define through model ( pivot table) as through table

A: You could add a property db_table (link)
linking to the previous table, named foo_old_table_name  in your case.
According to the doc,

By default, this table name is generated using the name of the
many-to-many field and the name of the table for the model that
contains it

So for the field new_m2m_field_name, the previous table making the link was named : old_field_name_database_old_table_name.
Hence :
new_field_name = models.CharField(max_length=50, db_column='old_field_name', db_table='old_field_name_database_old_table_name')

The option through could be changed too, but I do not think it is necessary if the modifications on names are coherent.

A: You will probably need to manually define the Through model (that Django would otherwise implicitly create behind the scenes) in order to make it unmanaged.
class Foo(models.Models):

    new_m2m_field_name = models.ManyToManyField(
        "RelatedModel",
        blank=True,
        db_column="old_m2m_field_name",
        through="FooRelatedJoin",  # <- new
    )

    class Meta:
        managed = False
        db_table = "foo_old_table_name"

class RelatedModel(models.Models):

    name = models.CharField(max_length=50)

    class Meta:
        managed = False
        db_table = "related_model_old_table_name"

class FooRelatedJoin(models.Models):  # <- all new
    foo = models.ForeignKey(Foo)
    related_model = models.ForeignKey(RelatedModel)

    class Meta:
        managed = False
        db_table = "foo_join_table"


text:
Q: creating an executable jar file with ant which includes the build.xml file I am trying to use ant to build an application, run the application's main() method, run junit tests, and package everything in a jar file (source+build+libraries+build.xml). The classes include a runner class with a main() method entry point.
The objective however is to inlcude all libraries used, like junit.jar, and the ant build.xml itself.
I was wondering if there is a way for the executable jar file, to run selected targets of the ant build file itslef, instead of just the main() method. Obviously I wouldn't need to run the compile targets again, but only the main() method (the java element in my run target) and the junit target. Is that possible?
Many thanks in advance for the insight!

A: "Executable jar" is not what you think it is. It allows you pack all your classes together (you can add source to it as well though I see little point in that) and declare a main class using Main-Class attribute in the jar manifest. Details are here.
You can then launch that jar using "java -jar my.jar" command line which would invoke main() method of the class you've specified. You can also specify classpath via Class-Path attribute in the manifest file that can point to other jars needed by your application. That DOES NOT MEAN those jars are archived within your jar; in fact if you were to do that, JVM won't be able to load classes from those jars unless you were to take special precautions and write a custom classloader.


text:
Q: Real time data value display in C#
Possible Duplicate:
Real time data value display in C#

Simple C# question: I was trying to design a simple C# DLL that uses a
third party library to stream images from a digital camera.
Really beginner C# programmer here, so bear with me through this question :)
I added a counter to the code so that whenever an image was retrieved
the counter incremented.
I built a pointless and simple GUI with a start and stop button to
make sure that everything was working properly because we were having
some problems in the past where the camera would stop streaming
suddenly, so I wanted to monitor this timer counter to make sure that
it is continuously incrementing.
What is the sensible way to do this to get a real time display of the
timer value? The value is just a UInt32 and is part of the object
instationed from the DLL.
What I actually implemented was sloppy:
I have a button that would pop up a message box displaying the timer
value when pressed, so to check if everything was still working, I
would press this button twice to make sure the value had incremented
somewhat.
What is the proper way to do this? Data binding? What would most of
you do in this simple case? I just want a label / textbox / anything
that will constantly refresh with the value of my counter data member.
Thanks!

A: everytime the counter is incremented just update a label or text box. then it will be "live".
    private int _counter = 0;
    public int counter
    {
       get { return _counter; }
       set { _counter = value; UpdateLabel(); }
    }

private void UpdateLabel()
{
   label1.Text = "Counter is: " + counter + " Last updated: " + DateTime.Now.ToShortTimeStrong();
}

if the library has any events, then subscribe to those events to alert you as to what's going on.

A: The proper way to do this is to set up a polling mechanism; on your form, or even within your wrapper object, set up a timer that will fire its "tick" or "elapsed" event every 100 millis (1/10 second). Attach a handler to that event that will read the variable from the native code, and update a label or textbox with that value.


text:
Q: R return a conditioned number of objects in a FUNCTION I have a function in which I want to return a different object per column of a matrix. However, I don't know how to make the return such that it identifies how many variables  to create within a list given that it will be conditioned to the number of columns of the input matrix.  In other words, how do I change the last command in the following function:
f <- function(Treat) {
for (i in c(1:ncol(Treat))) {
assign(paste0("Treat",i), as.matrix(Treat[,i]))
}
return(dat = list(Treat1=Treat1 , Treat2=Treat2, .....Treatn=Treatn))
}

A: lapply is what you are looking for
f <- function(Treat){
    lapply(1:ncol(Treat), function(i) as.matrix(Treat[,i]))
}

A: lappy works nicely here. But you could also do it with an explicit loop (as per your original example) that assigns to a (pre-initialised) list as it goes:
empty_list <- list()                          # inititalise an empty list
f <- function(Treat, empty_list) {            # set up the function
for (i in c(1:ncol(Treat))) {                 # set up the loop
     empty_list[[i]] <- as.matrix(Treat[,i])) # write each column to a new element
}
return(empty_list)                            # return the list
}

You could then use this with:
full_list <- f(Treat, empty_list)


text:
Q: (Audio) captureStream is not a function in Safari I'm trying to get the CaptureStream of an HTML audio element.
  const sUsrAg = navigator.userAgent;
  var playBackStream = null

  if (sUsrAg.indexOf("Firefox") > -1) {
    console.log("Firefox");
    playBackStream = this.$refs.localaudio.mozCaptureStream();
  }
  else {
    console.log("Other");
    playBackStream = this.$refs.localaudio.captureStream();
  }

I'm using Nuxt, so that's where the $refs come from. Basically referring to something like this:
<audio
  id="localaudio"
  ref="localaudio"
  ...
></audio>

While this does work in Chrome and Firefox, it doesn't work in Safari.

TypeError: this.$refs.localaudio.captureStream is not a function. (In
'this.$refs.localaudio.captureStream()',
'this.$refs.localaudio.captureStream' is undefined)

I read somewhere about a Safari solution like this:
this.$refs.localaudio.captureStream = () => playBackStream

But that gives me:

Unhandled Promise Rejection: TypeError: S.stop is not a function. (In
'S.stop()', 'S.stop' is undefined)


text:
Q: How to use active record query with symbols and operators? Could this be converted to use symbols and operators notation instead for better readability:
  scope :visible, where("is_hidden = false")
  scope :current, where("exp_date IS NULL OR exp_date > " + timestamp)

Convert into something like this:
scope :active, where(   :is_hidden => false,
                        (:exp_date => nil || :exp_date > timestamp)
                    )

Sorry for the screwed up syntax (I'm brand new to ruby)

A: I kinda feel like I'm stealing the glory from the people commenting your question, but here's a possible solution as well:
With squeel, you could write your scopes something like this:
def self.active
  where{!is_hidden}
end

def self.current(timestamp)
  where{exp_date.nil? | exp_date > timestamp}
end


text:
Q: Twitter bootstrap Filter only works when typing I want to set the filter value of a table by using Javascript. The problem i have is that when im typing in the value in the filter field everything works correctly but when im doing something like :
$("input[type=text]").val("boe");

The "boe" is set in the field but the filter is not responding on the input. This is probably something stupid that the filter only reacts on keyup. I am using Twitter bootstrap data tables library from : Twitter boostrap datatable
Any advice is welcome! And thanks in advance!

A: try this after your line:
$("input[type=text]").keyup();

or even better as @h2ooooooo suggested in the comment:
$("input[type=text]").val("boe").keyup();


text:
Q: Issue getting a shape from custom class to be added to driver class Hey everyone I'm writing a program the is a pizza builder, it has several check boxes and whenever you click on it will add 0.50 to the total and add a shape of whatever topping user chose. I created a class called Toppings that will create several different shapes. Everything seems to work but whenever I try to create it in the driver class it keeps throwing an error. Here is some code from the Toppings class:
public class Toppings {

private String shapeName;
private int radius, xCoor, yCoor;

// Constructor for Toppings-------------------------------------------------
public Toppings(String shapeName, int radius, int xCoor, int yCoor) {
     this.radius = radius;
     this.xCoor = xCoor;
     this.yCoor = yCoor;

}

public Toppings() {

}

public void createPepperoni() {

    // Create a circle for pepperoni----------------------------------------
    Circle pepperoni = new Circle();
    pepperoni.setRadius(radius);
    pepperoni.setCenterX(xCoor);
    pepperoni.setCenterY(yCoor);

}

And here is where I'm trying to create a pepperoni in the driver class:
    pepperoni = new Toppings("pepp1", 50, 550, 150);
    pepperoni.createPepperoni();

    list.addAll(pizzaDough, pepperoni);

When I try it like this it gives me a runtime error at list.addAll but it is not very specific as to what the issue is. I have also tried it like this:
Group pizza1 = new Group(pizzaDough, pepperoni);

Attempting it this way has an error that says "constructor Group in class Group cannot not be applied to given types." Can anyone help figure out what I'm doing wrong? I have imported the Circle from javafx just FYI.
I adjusted my Toppings class to this:
public Shape createPepperoni() {

    // Create a circle for pepperoni----------------------------------------
    Circle pepperoni = new Circle();
    pepperoni.setRadius(radius);
    pepperoni.setCenterX(xCoor);
    pepperoni.setCenterY(yCoor);
    return new Circle(xCoor, yCoor, radius);
}

I'm still getting this error, "Exception in Application start method
java.lang.reflect.InvocationTargetException."

A: pepperoni is a Toppings.  If you want to put it in a Group, it would need to be a Node (which it is not).
You already have a method to make a node for a pepperoni.  That method creates a circle. You could make the createPepporoni() method return the circle it created and add that to a group, e.g. group.add(pepperoni.createPepporoni()).
public Shape createPepperoni() {
    return new Circle(xCoor, yCoor, radius);
}

Where the arguments of the circle constructor are class field values or constants that you have previously established values for.
There are numerous other issues with your code and design, as well as the naming strategy for identifiers in your app, which I won't discuss here at this time, but hopefully the info I provided might help solve some of your immediate issues.


text: Q: Unable to launch the URL in robot framework Unable to launch the URL in robot framework. Browser window is opening and URL is also entered in address bar after that showing error message like "Unable to connect". Can anyone help me on this. Please give the instructions to setup the robot framework. Im using intelliJ Idea for run the robot framework.


text:
Q: how to import or require CSS file conditionally eg(According to IOS version) checkVersion() {
        if (typeof window !== 'undefined' && window && window.navigator && window.navigator !== undefined) {
            let agent = window.navigator.userAgent, start = agent.indexOf("OS");
            if ((agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && start > -1) {
                return window.Number(agent.substr(start + 3, 3).replace("_", "."))
            }
            return 0;
        }
        },
const checkVersion = Common.checkVersion();
require("../assets/style.css");
require("../assets/style2.css");
require("../assets/sprite.css");
require("../assets/ondemandpagestyle.css");
require("../assets/newstyle.css");
require("../assets/landingpage.css");
     if (checkVersion <= 14) {
    require("../assets/styleIOSUpgrade.css");
}

Here u see I have require the last CSS file conditionally(according to IOS version) , here i have used  CheckVersion function to detect the Ios version and according to it and i have require the different CSS file

A: checkVersion() {
        if (typeof window !== 'undefined' && window && window.navigator && window.navigator !== undefined) {
            let agent = window.navigator.userAgent, start = agent.indexOf("OS");
            if ((agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && start > -1) {
                return window.Number(agent.substr(start + 3, 3).replace("_", "."))
            }
            return 0;
        }
        },
const checkVersion = checkVersion();
require("../assets/style.css");
require("../assets/style2.css");
require("../assets/sprite.css");
require("../assets/ondemandpagestyle.css");
require("../assets/newstyle.css");
require("../assets/landingpage.css");
     if (checkVersion <= 14) {
    require("../assets/styleIOSUpgrade.css");
}

U can use above code to require CSS file conditionally


text:
Q: Strings in strings.xml are causing problems in Android What can I do? I want to offer multilanguage versions, but for this I need every string in strings.xml...with Context.getString it isn't working because of non-static method in static class/method.

A: Then do this:
How can I get a resource content from a static context?

A: Oh I see what your trying to do.
The R.string.blah is just an int reference.
To get the actual string you need to do
Context.getResources().getString(R.string.blah);

Get String Resource


text:
Q: _Noreturn in a struct in c: error: expected specifier-qualifier-list before '_Noreturn' I am trying to compile a piece of code that contains _Noreturn:
#ifndef SOMEHEADER_H
#define SOMEHEADER_H

#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>

extern struct s {

    _Noreturn void (*somenoreturnfunc)(bool);
} svar;

#endif

Which gives me:
error: expected specifier-qualifier-list before '_Noreturn' on:
_Noreturn void (*somenoreturnfunc)(bool);
So I tried the suggestion from here:
#ifndef SOMEHEADER_H
#define SOMEHEADER_H

#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>

#include "noreturn.h"

extern struct s {

    noreturn void (*somenoreturnfunc)(bool);
} svar;

#endif

noreturn.h:
#ifndef NO_RETURN_H
#define NO_RETURN_H
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#define noreturn _Noreturn
#elif defined(__GNUC__)
#define noreturn __attribute__((noreturn))
#else
#define noreturn
#endif
#endif

But the error still happens:
In file included from ../include/someinclude.h:8:0,
                 from src/main.c:17:
../include/noreturn.h:4:18: error: expected specifier-qualifier-list before '_Noreturn'
 #define noreturn _Noreturn
                  ^
../include/someinclude.h:19:5: note: in expansion of macro 'noreturn'
     noreturn void (*somenoreturnfunc)(bool);
     ^

I am baffled because it is compiled with c11 so it should work:
make V=1
cc src/main.c
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -std=c11 -Wall -pedantic -ffreestanding -static -I../libopencm3/include -I../include -DSTM32F1 -g -DDEBUG -DBUILD_STYLE=\"DEBUG\" -O0 -Iinclude -I../librt/include  -MMD -MT build/main.o -MF build/main.d -o build/main.o -c src/main.c
In file included...

GCC version is 5.4.1:
arm-none-eabi-gcc --version
arm-none-eabi-gcc (15:5.4.1+svn241155-1) 5.4.1 20160919
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

which should support all C11 features (_Noreturn is supported since 4.7).
What am I doing wrong and how could I resolve this error?
--
Edit: Maybe a self contained example can help:
main.c:
#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>

struct s {

    _Noreturn void (*somenoreturnfunc)(bool);
} svar;

int main()
{
        svar.somenoreturnfunc = 0;
        return 0;
}

Compiling this:
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -std=c11 -Wall -pedantic -ffreestanding -static -DSTM32F1 -g -DDEBUG -DBUILD_STYLE=\"DEBUG\" -O0 -MMD -MT main.o -MF main.d -o main.o -c main.c
main.c:7:5: error: expected specifier-qualifier-list before '_Noreturn'
     _Noreturn void (*somenoreturnfunc)(bool);
     ^
main.c:5:8: warning: struct has no members [-Wpedantic]
 struct s {
        ^
main.c: In function 'main':
main.c:12:6: error: 'struct s' has no member named 'somenoreturnfunc'
  svar.somenoreturnfunc = 0;
      ^

Yet when compiling with the same command line and removing _Noreturn the compilation succeeds.
This also happens when compiling with
gcc -std=c11 -o main main.c:
$ gcc -std=c11 -o main main.c
main.c:7:5: error: expected specifier-qualifier-list before '_Noreturn'
     _Noreturn void (*somenoreturnfunc)(bool);
     ^~~~~~~~~
main.c: In function 'main':
main.c:12:6: error: 'struct s' has no member named 'somenoreturnfunc'
  svar.somenoreturnfunc = 0;
      ^
$ gcc --version
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

A: In ISO C, _Noreturn cannot be used on the declaration of a function pointer.  It can only be used on the declaration of a function. (Ref: C11 6.7.4/2).
You will have to abandon this idea.  The function specifiers (inline and _Noreturn) are not part of a function's type.
There is another problem in your code: you define svar in the header, this will cause an ODR violation if the header is included in two or more translation units. It should only have a declaration in the header, and a definition in one unit.

To call through the function pointer and retain _Noreturn semantics , perhaps you could make a shim, e.g.:
inline _Noreturn void call_somefunc( struct s *ps, bool b )
{
    ps->somenoreturnfunc(b);
}

but there is no way to have the compiler enforce that when you assign to the function pointer, it is actually a _Noreturn function.

A: The function specifiers _Noreturn and inline are not part of the type of a function, they are part of the declaration. And the C17 standard states in 6.7.4 that function specifiers "shall be used only in the declaration of an identifier for a function." This means they cannot be used in the in the declaration of a pointer to a function.
So unfortunately this is not possible; a typedef won't help either.

A: Many good answers already, but for clarity I would like to ad the following:
From C11, 6.7.4.9:

The implementation should produce a diagnostic message for a function declared with a _Noreturn function specifier that appears to be capable of returning to its caller.

So _Noreturn has the purpose of informing the compiler to check there is no control path in the function declared as _Noreturn where it actually returns.
Knowing this, it is now clear why you cannot declare a function pointer to be _Noreturn because the compiler cannot check the return semantics of the function assigned.
(Of course, a compiler could see _Noreturn as part of the type and then check that only _Noreturn functions are assigned to the function pointer. The current definition in the standard seems a bit useless to me.)


text:
Q: How do I narrow a JetBrains IDE tool window? In some of my JetBrains IDEs my the tool windows launched for the bottom bar open to fill the full width of my IDE window, while in others they are limited to the width of the middle pane of the IDE window. I prefer the latter, but can't figure out how to get there from the former.
How do I narrow a JetBrains IDE tool window to the width of the middle pane of my IDE?

A: *

*Settings/Preferences

*Appearance & Behavior | Appearance

*Widescreen tool window layout option under Window options section.


text:
Q: How to separate numbers from letters in text of list I have a list[] which contains phrases like list = ['123Abc','234Asx','456Aio','...'].I would like to separate numbers from letters. The recurrent model is 3 numbers followed by capital A. How can I do that? I tried many ways using list.replace but I don't know how to set it, or whether the existence or not of a better method to use.

A: To get continuous groups of items, using a function to determine to what group each item belongs, use itertools.groupby. In your case, you (presumably) want continuous sets of digits and non-digits, so the key is isdigit(), applied to each of the characters in your input string.
The number of digits can be variable, the letter-part does not need to start with A, and you actually can have any series of digits and letters in any order: groupby will sort it out.
The result of groupby is an iterator (so you must convert it to something definitive such as a list), in the format "key result, group object". You can see the isdigit fired correctly for all characters by printing out the immediate result:
from itertools import groupby

l = ['123Abc','234Asx','456Aio']
print ([(i,list(j)) for i,j in groupby (l[0], key=lambda x:x[0].isdigit())])

which is
[(True, ['1', '2', '3']), (False, ['A', 'b', 'c'])]

Converting the list(j) back to a single string only needs a join. You don't want to know whether you have a list of digits or not, so you can discard the boolean result and store only the strings. This
print ([''.join(j) for i,j in groupby (l[0], key=lambda x:x[0].isdigit())])

yields
['123', 'Abc']

for the first item in your list, and if your desired result is a list for every item in your current list, add an iteration around this one:
print ([[''.join(j) for i,j in groupby (item, key=lambda x:x[0].isdigit())] for item in l])

returns
[['123', 'Abc'], ['234', 'Asx'], ['456', 'Aio']]

A: you can use list comprehension and add a space at position 3 in each string:
[e[:3] + ' ' + e[3:] for e in my_list]

output:
['123 Abc', '234 Asx', '456 Aio', '... ']

A: numbers = [int(val[:3]) for val in list]
text = [val[3:] for val in list]

A: try this :
text = ['A'+i.split('A')[1] for i in list]
numbers = [i.split('A')[0] for i in list]

output:
['Abc', 'Asx', 'Aio']
['123', '234', '456']

A: Here is another way to do it to get the result you want. This is done using re.findall and is independent of the scenario where the separating character is 'A'.
import re

test_list = ['123Abc','234Asx','456Aio']

result = [' '.join(re.findall(r'[A-Za-z]+|\d+', x)) for x in test_list]

print(result)

Output
['123 Abc', '234 Asx', '456 Aio']

Time taken to run:
3.62 µs ± 13 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
This seems to run faster than the accepted solution. From my analysis, the accepted solution runs in approximately:
5.79 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


text:
Q: make list clickable (jquery/html) I'm using python flask with my site to display content from a database, and I'm trying to make each list item clickable. I've looked at various questions on stackoverflow about how to make a list item clickable, which I can do, but only the first list item in this list is clickable, and the rest do nothing. Can someone please show me what I'm doing wrong? This is my first time doing html/js/jquery stuff so I'm confused.
HTML code:

    {% for listing in listings %}

                <input type="hidden" class="id_align" name="id_align" value="{{ listing.id }}">

{{ listing.listing_name }}

{{ listing.address }}

                        {{ listing.rooms }} bed
                          ·
                        {{ listing.bathrooms }} bath

Comments: {{ listing.comments }}

${{ listing.price }}

    {% endfor %}

JQuery code:
$( "#listing" ).click(function() {
    var list_id = $( ".id_align" ).val();
    //alert(list_id);
    var location = "/create_review/" + list_id;
    //alert('' + location);
    window.location.href = location;
});

A: ID should be unique , in your case, its repeating for mulitple elements hence the click event handler is triggered only for the first item in the DOM with this ID listing.
So,Use class selector instead.
Also to extract the id_align value of the current clicked list item you need to traverse within the clicked item , you can do that calling .find() against the current item else it will always give you the first .id_align() field value always.
HTML Code:

JS Code:
$( ".listing" ).click(function() {
   var list_id = $(this).find(".id_align" ).val(); // to fetch current current id_align
   var location = "/create_review/" + list_id;
  window.location.href = location;
});

A: I'm guessing the error is that you looping through your list creating N divs dynamically and assigning them the same id. Remember elements's ids in HTML most be document-wide unique (you can read the specifications here)
So, to fix this you may end with something like this:

    {% for listing in listings %}

                <input type="hidden" class="id_align" name="id_align" value="{{ listing.id }}">

{{ listing.listing_name }}

{{ listing.address }}

                        {{ listing.rooms }} bed
                          ·
                        {{ listing.bathrooms }} bath

Comments: {{ listing.comments }}

${{ listing.price }}

    {% endfor %}

And your javascript code
$( ".listing" ).click(function() {
    var list_id = $( ".id_align" ).val();
    //alert(list_id);
    var location = "/create_review/" + list_id;
    //alert('' + location);
    window.location.href = location;
});

A: In your iteration you are adding items with same id, therefore it stops on the first item. Use class listing instead of id listing:

    {% for listing in listings %}

    ...

$( ".listing" ).click(function() {
    var list_id = $(this).find(".id_align").first().val();
    //alert(list_id);
    var location = "/create_review/" + list_id;
    //alert('' + location);
    window.location.href = location;
});


text:
Q: Help with Equivalence Statements and Tautologies I apologize for this bulky, cumbersome post but in reviewing for a proofs midterm I have tomorrow I was asked some questions on logical equivalence and tautologies that I want to make sure I understand.
We're asked to consider the following statements:
a) $P \land Q$
b) $P\land\neg Q$
c) $\neg P\land Q$
d) $\neg P\land\neg Q$
e) $P\land\neg P$
f) $P\lor Q$
g) $P\lor\neg Q$
h) $\neg P\lor Q$
i) $\neg P \lor \neg Q$
j) $P\lor \neg P$
k) $P\Rightarrow Q$
l) $P\Rightarrow \neg Q$
m) $\neg Q\Rightarrow P$
n) $\neg P \Rightarrow \neg Q$
o) $\neg Q \Rightarrow \neg P$
p) $[P\land(P\Rightarrow Q)]\Rightarrow Q$
q) $[Q\land(P\Rightarrow Q)]\Rightarrow P$

*

*Find all statements logically equivalent to $P\Rightarrow Q$.

While $P\Rightarrow Q$ and itself are obviously equivalent, its contrapositive version $\neg Q \Rightarrow \neg P$ also works. However, I'm unsure if $P\land Q$ and $[P\land(P\Rightarrow Q)]\Rightarrow Q$ should also be included.

*Find all statements logically equivalent to $\neg(P\Rightarrow Q)$.

I want to say $P\Rightarrow\neg Q$ and $P\land\neg Q$ are equivalence statements but I feel like there may be more.

*Find all statements logically equivalent to $P\lor Q$.

I thought about using a negation of negations via DeMorgan's Laws but no such thing was listed as a possibility, so I can't think of any above statements being equivalent to this one (except itself).

*Which of these are tautologies?

$P\lor\neg P$ is an obvious tautology since $P$ is either true or false.
$[P\land(P\Rightarrow Q)]\Rightarrow Q$ is a tautology because if $P$ implies $Q$ and $Q$ is true, then $P$ must be true.
Again, I'm sorry for how bulky this question is but I need to assure myself that I'm not overlooking any equivalences or tautologies. Thanks for taking the time to read this.

A: *

*While the contrapositive $\neg Q \Rightarrow \neg P$ is clearly equivalent to $P \Rightarrow Q$, neither $P \wedge Q$ nor $[P \wedge (P \Rightarrow Q)] \Rightarrow Q$ is equivalent.  The only case in which $P \Rightarrow Q$ is false is when $P$ is true and $Q$ is false.  The only case when $P \wedge Q$ is true is when both $P$ and $Q$ are true.  Finally, $[P \wedge (P \Rightarrow Q)] \Rightarrow Q$ is always true.  On the other hand, $\neg P \vee Q$ is equivalent to $P \Rightarrow Q$.

*The statement $\neg(P \Rightarrow Q)$ is equivalent to $\neg(\neg P \vee Q)$, which is equivalent to $P \wedge \neg Q$.  It is not equivalent to $P \Rightarrow \neg Q$, which is equivalent to $\neg P \vee \neg Q$.

*$P \vee Q$ is, however, equivalent to $\neg P \Rightarrow Q$ as well as $\neg Q \Rightarrow P$.

*Yes, those are the two tautologies.
The one rule that will likely help you the most is the one that establishes the equivalence of $x \Rightarrow y$ and $\neg x \vee y$.


text:
Q: MacBook Pro Early 2008 Fan running while in standby The fans in my MBP (MacBook Pro4,1) continue to run after closing the MacBook.
This is not because of the CPU running under high power, it's also happening when the CPU has done nothing for about 15 minutes. The fan runs either for about 5 hours or as long as it takes the MacBooks battery to get empty.
Info:
- I'm running 10.9.2
- I have this problem for about 2 years
- I ran an Apple Hardware Test
- I resetted the SMC and the PRam
- I reinstalled the MacBook with the original reinstall DVD (OS X 10.5.2) and updated version-by-version (10.6 -> 10.7 -> 10.8 -> 10.9)
- I replaced the battery
And it's getting worse with the time (until now, it stopped after about 5-10 minutes, but since last December, it doesn't stop anymore)
Note: Some people might say this is a duplicate of this question, but it's different, as in my case, the fans won't stop.

A: It would make sense from my point of view to look for a certified Apple Service Provider or Apple Retail Store and ask them about replacing your Mac thermal grease. Chances are they offer this in a sort of "spring cleaning" program. Over time the thermal paste between your CPU and GPU and the heat sink dries up and doesn't do what it is suppose to do. This can happen but doesn't mean it is, sometimes the fans just get full of dust and need to be cleaned out. The important thing is just making sure the mac is getting good airflow and that its vents are several inches (6-8) away from anything that could be obstructing airflow.


text:
Q: How can I import a namespace? I have a JavaScript file which contains the following:
const api = {
  call(type, url, data) {
    console.log(type + "bar");
  },

  get(url, query) {
    this.call("foo");
  }
}

I'm wanting to be able to call api.get() across multiple different files where necessary, but I'm having trouble importing this.

*

*Loading the file alone through import gives me a ReferenceError when I attempt to access the api variable:
import "services/api.js";
console.log(api);

Uncaught ReferenceError: api is not defined

*Giving the import a name (of api) returns an Object, but it has no inner methods:
import api from "../../services/api.js";
console.log(api);
console.log(api.get);

Object {}
  undefined

What am I doing wrong?

A: Your api.js is not exporting anything. You should rewrite it to export every of these functions:
export function call(type, url, data) {
    console.log(type + "bar");
}
export function get(url, query) {
    call("foo");
}

(which is much better than default-exporting an api object literal)
and then you can use it like
import * as api from "../../services/api.js";
console.log(api);
console.log(api.get);

A: First you have to export it, as such:
const api = {
  call(type, url, data) {
    console.log(type + "bar");
  },

  get(url, query) {
    this.call("foo");
  }
}

export {api}

And then, import it:
import {api} from './path/to/api' // no .js

This approach is used when you're exporting multiple items (functions, classes, variables) from one file. If in your case api is the only item that you're exporting, you can use the default keyword and you will no longer need to use the accolades during import:
const api = {
  call(type, url, data) {
    console.log(type + "bar");
  },

  get(url, query) {
    this.call("foo");
  }
}

export default api

and
import api from './path/to/api'

Good luck!

A: You need to export your api:
const api = ...

export default api;

A: As a side note to this: export / import like this is ES6 module spec, be aware. For Node / CommonJS Module environments without any transpiler, it would be
// export
module.exports.api = api

// or
module.exports = { api: api } ...

// import
var module = require(....)


text:
Q: Creating a difference of the data frame with 1 col in python I am new to python and trying to replicate things in python that are done in excel.
I want to take difference of the col(A,B,C) with the mean(fixed)
    Unnamed:0   A   B   C   mean    Mean diffA
0   2020-08-28  1   6   11  6.0 -5.0
1   2020-08-29  2   7   12  7.0 -5.0
2   2020-08-30  3   8   13  8.0 -5.0
3   2020-08-31  4   9   14  9.0 -5.0
4   2020-09-01  5   10  15  10.0    -5.0

1 way is to manually put in the col name and find the difference, but is there any other less manual way?
new_df['Mean diffA']=new_df['A']-new_df['mean']

A: You can subtract the mean from a range of columns:
diffs = new_df.loc[:, 'A':'C'].subtract(new_df['mean'], axis=0)

Then combine the differences and the original DataFrame:
new_df.join(diffs, rsuffix='_mean')

A: You have a few options to do this. I tried the following and it worked.
import pandas as pd

dt = {'START DATE':['2020-08-28','2020-08-29','2020-08-30',
                      '2020-08-31','2020-09-01'],
      'A':[1,2,3,4,5],
      'B':[6,7,8,9,10],
      'C':[11,12,13,14,15]}

df = pd.DataFrame(dt)

df['Mean'] = df.loc[:,'A':'C'].mean(axis=1)

df[['dA','dB','dC']] = df.loc[:, 'A':'C'].subtract(df['Mean'], axis=0)

print(df)

OR you can try and do something like this as well
df[['dA','dB','dC']] = df.loc[:,'A':'C'] - df[['Mean','Mean','Mean']].values

print(df)

Both of these will provide the same output:
   START DATE  A   B   C  Mean   dA   dB   dC
0  2020-08-28  1   6  11   6.0 -5.0  0.0  5.0
1  2020-08-29  2   7  12   7.0 -5.0  0.0  5.0
2  2020-08-30  3   8  13   8.0 -5.0  0.0  5.0
3  2020-08-31  4   9  14   9.0 -5.0  0.0  5.0
4  2020-09-01  5  10  15  10.0 -5.0  0.0  5.0

The second option is not a good way to use it. Pandas provides you subtract function. Use this.


text:
Q: How to not build gradle subproject using docker plugin if docker not available? I have a small multiproject Gradle build.  I first constructed a Maven build structure for it, and that works fine.  There are three subprojects.  Two of them construct WAR files.  The last constructs a Docker image using the other two WAR files.
The top-level Maven aggregator uses profile activation so that the Docker image project is only ever built if the OS is Linux.  Eventually, I'll need a better conditional check for that (when Docker becomes a first-class element in Windows).  For now, the Maven profile activation check works fine.
I'd like to do something similar in the Gradle build, as presently it tries to build the Docker image on Windows, which doesn't work.
What's the best way to have the Gradle build in the Docker-building subproject to do nothing if Docker isn't available (might as well do it right for the future)?  If that's too hard I can settle for only building it on Linux.

A: I don't think, there is a simple solution for this. Especially if you want it to be platform independent. The only solution I can suggest is to make function to run CLI command gradle -v and parse this command output. Though, to run this command you have to do platform specific calls. Something like this:
import org.apache.tools.ant.taskdefs.condition.Os

//if true then Docker is available locally, otherwise false
ext.isDockerAvailable = { ->
    def commandStdOut = new ByteArrayOutputStream()
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        //for Windows OS
        exec {
            commandLine "cmd", "/c", 'gradle', '-v'
            standardOutput = commandStdOut
        }
    } else if (Os.isFamily(Os.FAMILY_UNIX)) {
        //for Unix-family OS
        exec {
            commandLine "sh", "/c", 'gradle', '-v'
            standardOutput = commandStdOut
        }
    } else {
        //if OS is unsupported
        println 'Unsupported OS version'
    }
    commandStdOut = commandStdOut.toString().trim()
    //check command output for predefined words
    return commandStdOut.contains('Build time:') && commandStdOut.contains('Revision:')
}.call()

task buildDockerImage {
    enabled = isDockerAvailable
}

Sure, this works for Windows- and Unix-family OS.
And if you don't care much about whether image will be built or not, why don't you simply set ignoreFailures for docker-tasks and ignore them if they fail on Windows.
Anyway, I suppose, it's much better to use remote build server (with Docker remote API available) for such a task. In that case neither you, nor someone else need local Docker distribution to be installed if you are in the same LAN.


text:
Q: Understanding separation Axioms in Topology Weak separation Axioms $(T_0\text{ or Kolmogorov},T_1\text{ or Frechet},T_2\text{ or Hausdorff})$ codify how a topology can distinguish between points in the underlying set, or in the other words how well it can separate points with open sets. They are really intuitive as they show how sequence convergence.
But I couldn't see how Strong separation Axioms $(T_3\text{ or regular }T_1,T_4\text{ or normal }T_1)$ are stronger than Weak separation Axioms. I failed to make an intuition like weak separation Axioms does with sequence convergence.
I see there are different definition for $T_3$ and $T_4$, hence mentioning them below what I am following now:

*

*A topology space $(X,\tau)$ is said to be $T_1$ if for any pair of distinct points $x,y\in X$, there exist open sets $U$ and $V$ such that $U$ contain $x$ but not $y$, and $V$ contain $y$ but not $x$.

*A topology space $(X,\tau)$ is said to be regular if for any $x\in X$ and any closed set $C$ not containing $x$, there are disjoint open sets $U$ and $V$ such that $x\in U$ and $C\subseteq V$.

*A topology space $(X,\tau)$ is said to be $T_3$ if it is both $T_1$ and regular.

*A topology space $(X,\tau)$ is said to be normal if for any two disjoint, nonempty, closed subsets $C,D\subseteq X$, there are disjoint open sets $U$ and $V$ containing $C$ and $D$, respectively.

*A topology space $(X,\tau)$ is said to be $T_4$ if it is both $T_1$ and normal.

I read all of those in fact that course by my own, maybe that's why I couldn't connect them. It will be great help if someone help me to understand/build an intuition on them.

A: I think one key point is to keep in mind how $T_1$ links points and closed sets: the $T_1$ axiom is equivalent to "all singletons are closed." With this in mind, we can think of strong separation axioms as being the "set-ified" versions of weak separation axioms - if we assume $T_1$-ness as well. For example, normality basically is Hausdorffness if we replace "(distinct) points" with "(disjoint) closed sets," and regularity is a sort of halfway-point between Hausdorffness and normality (we only "set-ify" halfway).

For example, to see that $T_4$ implies $T_2$ (= Hausdorff), given distinct points $x,y$ in a $T_1$ normal space (= $T_4$ space), by $T_1$-ness we know that $\{x\}$ and $\{y\}$ are disjoint nonempty closed sets so by normality we can find disjoint open $U\ni x, V\ni y$ - and this gives the Hausdorff condition.
The proof that $T_3$ implies $T_2$ is basically the same, except we only "set-ify" one of the points: given distinct points $x,y$ in a $T_1$ space regular space, by $T_1$-ness we get that $\{y\}$ is a nonempty closed set not containing $x$ so by regularity we get disjoint opens $U\ni x, V\ni y$ (the latter since $V\supseteq \{y\}$ is equivalent to $V\ni y$).

Of course this analogy breaks down if we don't assume $T_1$. For example, the Sierpinski space is normal but neither $T_1$ nor regular.


text:
Q: get data of listview item on click hey guys i am new to xamarin android , i created a listview which takes value of json format i want to get the name or the id of the listview clicked item and i don't know how..
here is my class
  class Doctors
    {
        public int id;

        public string Name;
        public string address;
        public string spec;
        public string rating;
        public string fee;

        public Doctors(string Name, string address, string spec, string rating, string fee)
        {
            this.Name = Name;
            this.address = address;
            this.spec = spec;
            this.rating = rating;
            this.fee = fee;
        }

    }

and here is my adapter
 class DoctorsAdapter : BaseAdapter<Doctors>
    {
        private Context mContext;
        private int mRowLayout;
        private List<Doctors> mFriends;

        public DoctorsAdapter(Context context, int rowLayout, List<Doctors> friends)
        {
            mContext = context;
            mRowLayout = rowLayout;
            mFriends = friends;

        }

        public override int Count
        {
            get { return mFriends.Count; }
        }

        public override Doctors this[int position]
        {
            get { return mFriends[position]; }
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View row = convertView;

            if (row == null)
            {
                row = LayoutInflater.From(mContext).Inflate(mRowLayout, parent, false);
            }

            TextView name = row.FindViewById<TextView>(Resource.Id.docname);
            name.Text = mFriends[position].Name;

            TextView spec = row.FindViewById<TextView>(Resource.Id.docspec);
            spec.Text = mFriends[position].spec;

            TextView address = row.FindViewById<TextView>(Resource.Id.docadd);
            address.Text = mFriends[position].address;

            TextView feeetv = row.FindViewById<TextView>(Resource.Id.feetv);
            feeetv.Text = mFriends[position].fee;

            RatingBar doctorrating = row.FindViewById<RatingBar>(Resource.Id.docrating);
            doctorrating.Rating = Int32.Parse(mFriends[position].rating);

            return row;
        }

    }

and this the method which populates listview with json
  private void populatelistview()
    {
        if (jsonString == null)
        {
            Toast.MakeText(this, "json is null", ToastLength.Long);

        }
        else
        {
            try
            {
                //  jsonobject = JObject.Parse(jsonString);
                jsonArray = JArray.Parse(jsonString);
                mDoctors = new List<Doctors>();
                int count = 0;
                while (count < jsonArray.Count)
                {
                    Doctors doctor = new Doctors(jsonArray[count]["Name"].ToString(), jsonArray[count]["spec"].ToString(), jsonArray[count]["address"].ToString(), jsonArray[count]["rating"].ToString(), jsonArray[count]["fees"].ToString());
                    //      Toast.MakeText(this, jsonArray[count]["name"].ToString(), ToastLength.Long).Show();
                    mDoctors.Add(doctor);
                    count++;
                }

                mListView = FindViewById<ListView>(Resource.Id.docview);
                mAdapter = new DoctorsAdapter(this, Resource.Layout.ticket_result, mDoctors);
                mListView.Adapter = mAdapter;
                mListView.ItemClick += MListView_ItemClick;
            }
            catch (System.Exception exception)
            {

                Toast.MakeText(this, exception.ToString(), ToastLength.Long);
            }

        }

A:
i want to get the name or the id of the listview clicked item

You can implement your MListView_ItemClick like this:
private void MListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    var position = e.Position;
    var item = mDoctors[position] as Doctors;
    var name = item.Name;
    var id = item.id;
}

First get the position where the item is clicked, then find the matched item in your mDoctors, and finally you can get the Name and id you defined in this item.


text:
Q: Forward declaring a class in a UI file I just wondered if there was a way to forward-declare a class in a Qt UI file. The issue that I have is that I use (the same version of) a same widget in two different projects : a project that uses the widget and an independant project that allows me to do testing with this widget while I'm working on its features.
Now, what happens is that when uic generates the ui_widget.h file, it adds this in it:
#include "widgets/custom_line_edit.h"

That's the include path for one of my promoted widgets. The thing is that the path to this file is not the same on the "real" project, as it should be
#include "modules/this_module/widgets/custom_line_edit.h"

I don't really know what to do not to have to edit my UI file each time to match my "current" project's file organization.
I've found this which was quite satisfying:

It is sometimes necessary to forward declare classes, particularly if code is being written in .ui.h files within Qt Designer. Each forward declaration is listed as it should appear in the generated C++ code.
<forwards>
   <forward>class QStringList;</forward>
</forwards>```

But unfortunately this documentation is quite old (Qt 3.3) and the syntax seems not to work anymore - I get an Error 1.
What are my options here?

A: The issue isn't one of forward declarations. I've never seen that "forward" mechanism in a UI file, but even it still works somehow, all that it does is put "class QStringList;" (or whatever) in the include file that uic generates. If you look at those include files, they will have "new SomeWidget ()" statements, and you can't create an object without its full declaration, so a forward declaration for something the UI file creates isn't helpful.
The UI definition needs the include file where the widget is defined for exactly that reason. It has to include the class definition in the file generated from uic, and the relationship between where the files reside is going to have to be consistent.
What I would do to solve this is put the widget(s) in a library, and then reference the library from my main application and my test application. Then the uic generation happens within the library, not the applications, and within the library, the relative locations of the files will remain constant. The applications don't need access to the .ui file nor the generated include file, so how the application source files are laid out in folders won't matter.
I don't see any other way to do this.


text:
Q: Help ID a 70s-era SF novel: post-eco-disaster, psychic forces What I remember of it: Toxic future Earth. Cities under domes. A train crash exposes a woman to the contaminated outside world, but she sneaks back in, with a stone from "outside" secreted in her pocket. I think she was part of a team of people using their minds to try and construct a psychic whatsamajig, a force that was going to somehow scrub the Earth clean. I suspect the name of the psychic whatsit was the name of the book. Thanks.

A: This is Gordon Dickson's The Pritcher Mass
The main character, Chaz Sant, was the one exposed to the outside:

[...]the car Chas was in had broken open.
He was outside.
He was exposed to the rot, potentially infected. According to law, neither he nor any of the other commuters in that particular car could be allowed back into a sterile area again.
Oh yes, he would.
The grim refusal to accept what had happened to him exploded instinctively inside him. He was bound for the Pritcher Mass, not doomed to wander a desolated world until he died of starvation or choked on the feathery white fungus growing inside his lungs. In this one case - his own - the inevitable must not be allowed to happen.
He took the rock from his forehead, about to toss it aside - then something stayed his hand. In the flickering light that he now saw come from the burning engine section of the first car, which lay on its side, he looked at the rock; and a word came into his mind.
Catalyst.
This was his chance, if he wanted to take it. A Heisenbergian catalyst, reportedly, was most often something just like this. A piece of wood or stone, not different from any other - illegal only because it was from an unsterilized area as this was.


text:
Q: Do non-neutral plasmas follow a Maxwell-Boltzmann energy distribution in ion traps Ion traps are interesting, and when thinking about them, I was wondering about this.

*

*Non-neutral plasmas or just ions interact through Coulomb interactions rather than 2 body collisions. So, does the Maxwell-Boltzmann distribution still apply?

*Since, in ion traps, electric and magnetic fields exist, how would this affect the energy distribution of the ions?

*And if the ions were to escape the ion trap, will this happen if the particles' kinetic energy ( Thermal energy or random kinetic energy) is greater than the potential energy needed to cross the barrier? I was wondering if we could use the ideal gas equation, PV=nRT, to calculate the pressure arising from temperature, and then add it to the pressure due to Coulomb interactions. Is this right?
Thanks


text:
Q: How to avoid connection timeout when server sends response late? I have built a server which does some action(run some scripts) which takes around 10 seconds and then sends response to client.
When I make curl call from the same server using
curl http://localhost/get-me-status

I have it working properly but when I make
$ curl http://server/get-me-status
curl: (56) Recv failure: Connection reset by peer

Currently my server doesn't send any response to client for around 10 seconds till the action on its side is completed. How do I keep the socket alive till the client gets response? My server is currently in Java and I use vertx on server side.
My impression is that one of the intermediatery router is killing the connection after seeing that the connection is idle for few seconds since it is working fine when client is also in the same machine. Is there any way I keep sending noob or any other messages to client to keep the connection alive?
I face this problem even when I do http request from the browser.

A: Why not just using Tomcat to handle this for you.

A: You have to increase the client connection timeout. In curl, set the options --connect-timeout and --max-time.


text:
Q: Existence of morphisms between diagrams First of all, as they say, first time-long time. I made an effort to find any duplicate or relevant questions but my vocabulary was limited and so was my success. Hopefully I can articulate myself clearly enough to communicate my meaning.
I have a fairly basic question about category theory. I'm working through chapter 1 of Aluffi's Algebra: Chapter 0 and while I can more or less make sense of most of the material, there's one thing in particular that's really wrinkling my brain.
Aluffi makes use of some categories as examples (specifically of note here: $C^A$, $C^{A,B}$ et al). In particular, he asserts that the morphisms between objects in these diagrams are themselves commutative diagrams, which sort of makes sense (still working on it). Here's a snippet.
My specific question is: how can we be certain of the existence of these morphisms $\sigma$ (morphisms in $C$, I guess) that can have the same image (am I thinking too much in terms of set-functions here?)? In other words, I think I'm having trouble understanding how we can be so certain of the commutativity of the diagrams above.
Please let me know if I can clarify the question. Thanks in advance.

A: For given $A$ and $B$ there may or may not be any diagrams like the one at the top of the page. If there are the category $C_{A,B}$ is nonempty
and these diagrams are the objects. Given two such diagrams with $Z_1$
and $Z_2$ there may or may not exist $\sigma$ making the final diagram
commute. In any case the $\sigma$ that make the diagram commute are the
morphisms in $C_{A,B}$ between the two diagrams. (There may be no such $\sigma$).
A good exercise is to prove that the composition of two morphisms
of $C_{A,B}$ is also a morphism of $C_{A,B}$.


text:
Q: The integration has two answers $\int \cot(x)*\csc^2 (x)$, which one is correct in the definite integral? When you integrate $\int \cot \theta \csc^2 \theta d \theta$ it has two answers.
Using simple substitution you can solve like this:
$u=\cot \theta$, $du=-\csc^2 \theta d \theta$
$\int - u du=-\frac{u^2}{2}+C=-\frac{\cot^2 \theta}{2}+C$
However, if you apply trigonometical identities and express the integral like this: $\int \cot \theta \csc^2 \theta d \theta=\int \frac{\cos \theta}{\sin^3 \theta}d \theta$
You then can clearly use simple substitution to solve this but in a different way:
$u=\sin \theta$, $du=\cos \theta d \theta$
$\int \frac{du}{u^3}=-\frac{1}{2u^2}+C=-\frac{1}{2\sin^2 \theta}+C=-\frac{1}{2}\csc^2 \theta + C$
Now, when the integral is indefinite, both answers are exactly the same because of the trigonometrical identity: $\cot^2 \theta + 1 =\csc^2 \theta$. However, when the integral is definite from a point $a$ to a point $b$: $\int_a ^b \cot \theta \csc^2 \theta d \theta$. It gives two different answers.
So, what is the correct answer to the definite integral?


text:
Q: ActiveRecord::ReadOnlyRecord Exception raised when parent is readonly I have the following two models:
# app/models/customer.rb
class Customer < ActiveRecord::Base
  has_paper_trail

  serialize :mail_opt_out, Set

  before_create :generate_token

  has_many :wallets
  has_many :tickets, through: :wallets

  ...

  # We have a special seeded customer with id -1 that we don't want changing
  def readonly?
    persisted? && id < 0
  end
end

# app/models/ticket.rb
class Ticket < ActiveRecord::Base
  include SparkCast

  has_paper_trail

  belongs_to :price
  belongs_to :basket
  belongs_to :occurrence

  has_one :event,       through: :occurrence
  has_one :wallet,      through: :basket
  has_one :basket_type, through: :basket
  has_one :customer,    through: :basket

  delegate :id, to: :customer, allow_nil: true

  ...

  def admit
    ensure_can_admit

    self.state = 'admitted'
    self.save!
  end
  cast_on :admit, room: :admittance

  def as_cast
    {
      id: id,
      customer_id: customer_id
    }
  end
end

The relevant association is a little convoluted, but is customers -> wallets -> baskets -> tickets.
When I call admit on an instance of a ticket that belongs to our customer with id -1, (which is read only) I get an ActiveRecord::ReadOnlyRecord exception.
I'm confused as to what is causing this, as neither ticket nor customer have any before_update callbacks. If I change
 has_one :customer, through: :basket

to
 delegate :customer, to: :basket

then everything is fine. Something seems to be either trying to update the customer, or at least checking if it is readonly.
I've done a bit of stepping through the save procedure using byebug, but haven't been able to find anything useful.
What is likely to be checking if an associated model is readonly, and how do I get around this? Is using delegate the best option here?
Edited to add:
Also including SparkCast, which I had omitted previously. Removing the cast_on method from my ticket model is fixing the problem.
# app/models/concerns/spark_cast.rb
module SparkCast
  extend ActiveSupport::Concern

  module ClassMethods
    def cast_on(*args)
      # Options are the last argument.
      options = args.pop

      room   = options[:room]

      args.each do |operation|
        class_eval do
          begin
            alias_method "#{operation}_without_cast", operation

            define_method operation do |*args|
              cast_hash = as_cast

              ...

              send("#{operation}_without_cast", *args)
              cast(room, operation, cast_hash)
            end
          rescue NameError => e
            raise "#{e.name} has not been defined yet. Include cast_on after method definition"
          end
        end
      end
    end
  end
end

Backtrace:
 - activerecord (4.1.0) lib/active_record/persistence.rb:481:in `create_or_update'
 - activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `block in create_or_update'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
 - activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `create_or_update'
 - activerecord (4.1.0) lib/active_record/persistence.rb:103:in `save'
 - activerecord (4.1.0) lib/active_record/validations.rb:51:in `save'
 - activerecord (4.1.0) lib/active_record/attribute_methods/dirty.rb:21:in `save'
 - activerecord (4.1.0) lib/active_record/transactions.rb:268:in `block (2 levels) in save'
 - activerecord (4.1.0) lib/active_record/transactions.rb:329:in `block in with_transaction_returning_status'
 - activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:209:in `transaction'
 - activerecord (4.1.0) lib/active_record/transactions.rb:208:in `transaction'
 - activerecord (4.1.0) lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
 - activerecord (4.1.0) lib/active_record/transactions.rb:268:in `block in save'
 - activerecord (4.1.0) lib/active_record/transactions.rb:283:in `rollback_active_record_state!'
 - activerecord (4.1.0) lib/active_record/transactions.rb:267:in `save'
 - activerecord (4.1.0) lib/active_record/autosave_association.rb:393:in `save_has_one_association'
 - activerecord (4.1.0) lib/active_record/autosave_association.rb:188:in `block in add_autosave_association_callbacks'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:424:in `block in make_lambda'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:221:in `block in halting_and_conditional'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
 - activerecord (4.1.0) lib/active_record/callbacks.rb:310:in `update_record'
 - activerecord (4.1.0) lib/active_record/timestamp.rb:70:in `update_record'
 - activerecord (4.1.0) lib/active_record/persistence.rb:482:in `create_or_update'
 - activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `block in create_or_update'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
 - activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
 - activerecord (4.1.0) lib/active_record/callbacks.rb:302:in `create_or_update'
 - activerecord (4.1.0) lib/active_record/persistence.rb:125:in `save!'
 - activerecord (4.1.0) lib/active_record/validations.rb:57:in `save!'
 - activerecord (4.1.0) lib/active_record/attribute_methods/dirty.rb:29:in `save!'
 - activerecord (4.1.0) lib/active_record/transactions.rb:273:in `block in save!'
 - activerecord (4.1.0) lib/active_record/transactions.rb:329:in `block in with_transaction_returning_status'
 - activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction'
 - activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:219:in `within_new_transaction'
 - activerecord (4.1.0) lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction'
 - activerecord (4.1.0) lib/active_record/transactions.rb:208:in `transaction'
 - activerecord (4.1.0) lib/active_record/transactions.rb:326:in `with_transaction_returning_status'
 - activerecord (4.1.0) lib/active_record/transactions.rb:273:in `save!'
 -  () home/hayden/development/SparkSeat/api/app/models/ticket.rb:79:in `admit'


text:
Q: How can we prove that Gaussian integers are algebraic integers? I heard in a lecture that every gaussian integer is in fact a root of a monic 2nd degree polynomial, it has been a day now and I can't figure this out.

A: There are a few things to say here:
It's a general fact that the sum of two algebraic numbers/integers is also one and clearly, $bi = b\sqrt{-1}$ and $a$ are algebraic integers so $a+bi$ is one too.
But in this example, we can be more explicit: $a+bi$ is the root of the polynomial $x^2 - 2ax + (a^2+b^2) = 0$.

A: In the second-degree polynomial $f(x) = \Big( x-(a+bi)\Big)\Big( x - (a-bi)\Big),$ the imaginary parts cancel out and the coefficients are then real integers.


text:
Q: Dynamic height in cell Issue in iPhone6 and iPhone6 plus I am implementing a functionality in which all labels of my cell has been resized as per the text containing with each label.I have implemented this functionality with the help of RayWanderlich tutorial and its working fine for iPhone 4s,5 and 5s with iOS 8.1. as shown in image below which shows iPhone 5s simulator with iOS 8.1

while I am running my app with iPhone 6 or iPhone 6 plus I got unexpected behavior as shown below image which shows iPhone 6 simulator

and iPhone 6 plus simulator.

I have created two custom cell nib files one for iPhone 4,4s,5 and 5s and second one is for iPhone 6 and 6 plus. As I am new with auto layout I have set constraints same both nibs. I am showing both custom cell nib files with set constraints at below images.
iPhone 4,4s,5 and 5s nib file snapshot

iPhone 6 and iPhone 6 plus Custom cell nib file snapshot

I also used following code snippet from where cell has been resized with dynamic height. The code works for iPhone iPhone 4(for iOS 7),4s,5 and 5s (for iOS 7 and iOS 8 and 8.1) fine but not for iPhone 6 and iPhone 6 plus.
Code Snippet
- (CGFloat)calculateHeightForConfiguredSizingCell_3:(MemberListTableViewCell_WithoutImage_3_iPhone *)sizingCell {

    sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tblView.frame), CGRectGetHeight(sizingCell.bounds));

    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    //CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize withHorizontalFittingPriority:UILayoutPriorityDefaultHigh verticalFittingPriority:UILayoutPriorityDefaultHigh];

    return size.height + 1.0f; // Add 1.0f for the cell separator height
}

Please give me a proper solution where am I going wrong.I have surfed lot of things but unable to get proper way to solve this issue. Your help would be appreciable.Thanks in advanced.

A: According to your question of cell height in iPhone6,6 Plus you need to write below lines.
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

Dynamic Cell Size using auto layout
reference:  http://www.appcoda.com/self-sizing-cells/

A: Is there a reason you have two different xibs for the same cell? The whole point of AutoLayout is that a single layout can be flexible enough to support all screen sizes.
When using auto sizing cells, the key things to remember are:

*

*tableView.estimatedRowHeight = <estimated_value>

*tableView.rowHeight = UITableViewAutomaticDimension

*Make sure you have a non-ambiguous layout inside of your UITableViewCell subclass and all elements are subviews of .contentView
Your layout looks like a perfect fit for UIStackView. I would suggest using a vertical UIStackView containing your 3 labels. Then a horizontal UIStackView containing the previous UIStackView and the UIImageView. The only NSLayoutConstraints you would need to create would be pinning the outer UIStackView to all sides of .contentView
For more info on UIStackViews, check out my blog post:
http://www.raizlabs.com/dev/2016/04/uistackview/


text:
Q: Converting only the first level of object tree using Jackson ObjectMapper Is it possible to make ObjectMapper convert only the actual object without converting the rest of the object tree recursively ?
So that :
Map<String,Object> props = new ObjectMapper().convertValue(obj, Map.class);

results in a map of [field, value] where values are the actual references to instances of the fields of obj instead of Maps ?

A: There is no such feature right now with Jackson. You can probably achieve this with a custom Serializer/Deserializer pair that could share some data and "protocol". But, why bother doing this when the easier (and a LOT faster) way would be to have a generic way to go from POJO to Map, probably using reflection.

A: I am not sure I understand what you are really trying to do here.
But one thing that may help is to keep in mind that java.lang.Object type (as well as JsonNode) can be freely included in the structure, to get sort of "untyped" binding deeper in the structure. With these types, you can avoid rigid data-binding for some subsets of the object model; and possibly convert to POJOs using ObjectMapper.convertValue() more dynamically.


text:
Q: Using smtpjs to send the value of the form in pure javascript I am trying to use SmtpJS to capture the value of my form and send it to my email.
So far I have the following form markup:
<form>
  <input type="text" name="fullname" placeholder="Full Name" />

  <input type="text" name="idea" placeholder="Idea" />

  <input type="checkbox" id="apple" name="apple" value="apple">
   Apple

   <input type="checkbox" id="orange" name="orange" value="orange">
   Orange

  <input type="radio" id="male" name="gender" value="male">
    Male

    <input type="radio" id="female" name="gender" value="female">
    Female

 <input type="submit" value="submit" onclick={() => sendEmail() }/>

</form>

I understand in order to use smtpjs, you first need to include it like this:

And then you need a function that will actually capture and send the email like this:
function sendEmail(){

    Email.send({
        Host : "smtp.yourisp.com",
        Username : "username",
        Password : "password",
        To : 'them@website.com',
        From : "you@isp.com",
        Subject : "This is the subject",
        Body : "And this is the body"
    }).then(
      message => alert(message)
    );

    }

How do I capture the inputs values, checked checkbox and selected radio buttons values and include them on the body of my email that will send to my email?

A: Instead of using an onClick attribute on the button, I would use an event listener on the submit event of the form.  The e.target for this event is the form element itself so you can make use of the FormData object to access properties on your form by their name property.
You can create a FormData object from your event handler by using const data = new FormData(e.target) and then you can access properties like data.get("fullname").  You can also use data.get() inside of a Template Literal to create texts like Welcome ${data.get("fullname")}.

function sendEmail(to, subject, body){
  console.log("Sending Email:");
  console.log("Subject:\n", subject);
  console.log("Body:\n", body);
    Email.send({
        Host : "smtp.yourisp.com",
        Username : "username",
        Password : "password",
        To : to,
        From : "you@isp.com",
        Subject : subject,
        Body : body
    }).then(
      message => console.log(message)
    );
}

const form = document.getElementById("myform");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const data = new FormData(e.target);
  const subject = `Welcome ${data.get("fullname")}`;
  const fruits = [data.get("apple"), data.get("orange")].filter(fruit => fruit !== null);
  const body = `Your idea ${data.get("idea")} has been submitted. Your selections are ${fruits.join(" ")} ${data.get("gender")}.`;
  sendEmail("them@website.com", subject, body);
});

<form id="myform">
  <input type="text" name="fullname" placeholder="Full Name" />

  <input type="text" name="idea" placeholder="Idea" />

    <input type="checkbox" id="apple" name="apple" value="apple">
     Apple

    <input type="checkbox" id="orange" name="orange" value="orange">
    Orange

    <input type="radio" id="male" name="gender" value="male">
    Male

    <input type="radio" id="female" name="gender" value="female">
    Female

 <input type="submit" value="submit"/>

</form>

A: In the script, you can include the following
var apple_checked;
var orange_checked;
var male_checked;
var female_checked;

function getCheckedValues(){
if (document.getElementById('apple').checked) {
            apple_checked="isChecked!";
        }else{
apple_checked="notChecked:(";
}

if (document.getElementById('orange').checked) {
            orange_checked="isChecked!";
        }else{
orange_checked="notChecked:(";
}

if (document.getElementById('male').checked){
male_checked="isChecked!";
}else{
male_checked="notChecked:(";
}

if (document.getElementById('female').checked){
female_checked="isChecked!";
}else{
female_checked="notChecked:(";
}

}

Obviously, you will need to call the function getCheckedValues() somewhere.

Then, for the Body of your Email.Send(), you could set the following value (give ids of inputs for firstname and idea as id="firstname" and id="idea":
Body : "First Name: "+document.getElementById('firstname').value+" Idea: "+document.getElementById('idea').value+"apple: "+apple_checked+" orange:"+orange_checked+" male: "+male_checked+" female: "+female_checked;


text:
Q: mailto fails to load email on Safari for iPhone, but works on iPad I was putting together a mobile website, and I wanted to create an email link that lets the user send links to their searches to other email address. The mailto link I generated  works fine in Chrome, IE, and Safari for the iPad. But on Safari for the iPhone, the link fails to bring up the default mail client.
Email your search results

A: After a lot of testing, and a lot of reading, I stumbled across this link to the iOS developer's website:
https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/MailLinks/MailLinks.html
The key was this: "When specifying a mailto URL, you must provide the target email address."
Basically, safari for iPhone requires a target email address in the mailto. With most other browsers, you can leave it blank. To fix the issue, I inserted a dummy email address to make it work.
Email your search results

EDIT: This issue may no longer be the case for Safari browsers for iPhone version 7+.


text:
Q: Spring Boot different data.sql files for different h2 tests @RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class TaskProviderTest {
}

I'm using h2 database configured in property file
spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL
spring.datasource.platform=h2
spring.jpa.hibernate.ddl-auto=none
spring.datasource.continue-on-error=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop

And I'm using schema.sql and data.sql files for unit tests. Both scripts are executed on test startup.
Is there anyway to use different data.sql files for different Junit test cases ?

A: Try to use EmbeddedDataSource and configure it from method in code.
The code below is demonstrates how to create datasource with 2 sql scripts
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();

    return builder
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("sql/create-db.sql")
            .addScript("sql/fill-db.sql")
            .build();
}

A: You can use Spring's EmbeddedDatabaseBuilder to construct the database in the setUp() method of your unit tests, providing different data.sql scripts for different tests.
Example:
public EmbeddedDatabase database(String dataScript) {
    return new EmbeddedDatabaseBuilder().
            setType(H2).
            addScript("schema.sql").
            addScript(dataScript).
            build();
}

Reference:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.html


text:
Q: What is the limit of this function as x approaches 2? I saw a video on Khanacademy where they said that given the following function:
$$F(x) = \begin{cases}x^2 & x \not = 2 \\ 1 &  x = 2 \end{cases}$$
the limit of the function when x approached 2 was equal to 4. Is that right? From what I learned we can approach a value either from the right or left and in this case it woud be 4 if x approached 2 from the left but not from the right so in general there wouldnt be a limit for when x approaches 2. Thanks.

A: Yes, it is true that
$$
\lim_{x \to 2} F(x) = 4.
$$
To see why, note that $F(x) = x^2$ whenever $x \neq 2$. That is, $F(x) = x^2$ for $x < 2$ and for $x > 2$. So, the left and right limits are given (respectively) by
\begin{align*}
\lim_{x \to 2^-} F(x) = \lim_{\substack{x \to 2\\x < 2}} F(x)
=  \lim_{\substack{x \to 2\\x < 2}} x^2 = \lim_{x \to 2^-} x^2 = 4
\end{align*}
and
\begin{align*}
\lim_{x \to 2^+} F(x) = \lim_{\substack{x \to 2\\x > 2}} F(x)
=  \lim_{\substack{x \to 2\\x > 2}} x^2 = \lim_{x \to 2^+} x^2 = 4.
\end{align*}
Looking at the graph of $F(x)$ helps to understand why the right limit also behaves this way.

A: For $x$ in $(0,4)$, $$|x^2-4|=|x+2||x-2|<6|x-2|.$$
So by an $\epsilon,\delta$ argument, the limit is indeed $4$. The value of $F$ at $x=2$ plays no role.