text:
Q: Switch between different view controllers using swift I want to switch between different view controllers, here is my codes,
let sb = UIStoryboard(name:"Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("tabBarController") as ViewController
self.presentViewController(vc, animated: true, completion: nil)

'tabBarController' is the storyboad ID I had wrote in the identifier inspector.but I got some error at this line.
let vc = sb.instantiateViewControllerWithIdentifier("tabBarController") as ViewController

and here is the screenshot,

What's the problem?
And I have another question, here is the screenshot after the sb was initialized, the storyboardFileName is "Main.storyboardc", shouldn't it be "Main.storyboard"?

Thanks very much!!!!

A: The error is saying that the view controller returned by instantiateViewControllerWithIdentifier cannot be cast to a ViewController.
This is probably because you did not set the Custom Class property of your view controller in the storyboard to ViewController.
Go to your storyboard, select your view controller, then open the Identity inspector and look for the Custom Class property. Set it to ViewController and tab out of the field to make sure it takes. Then run again.


text:
Q: Following a Twitter Authorization Dialogue with an Alert in iOS5 I am using the iOS5 Twitter API to get a user's permission to use their Twitter account. This pops open a dialogue from which they can choose to Give or Decline permission to the application. I would like to be able to open an alert if the user accepts but doesn't have a Twitter account set up on their iPhone, however as there is already a dialogue open, opening an alert at this point fails. How can I add an alert immediately after the Twitter permissions dialogue is dismissed?
- (IBAction)logInToTwitter:(id)sender
{
    //  First, we need to obtain the account instance for the user's Twitter account
    ACAccountStore *store = [[ACAccountStore alloc] init];

    ACAccountType *twitterAccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [store requestAccessToAccountsWithType:twitterAccountType
                     withCompletionHandler:^(BOOL granted, NSError *error) {
      if (granted)
      {
        NSArray *twitterAccounts = [[store accountsWithAccountType:twitterAccountType] autorelease];

        if ([twitterAccounts count] > 0)
        {
           //All good
        }
        else
        {
           //Open Alert
        }

      }
   }];
}

A: This does cause an error when showing the alert view.  The way to make this work is to create a separate function.
- (void)noTwitterAccountMessage {
    UIAlertView *alertViewTwitter = [[UIAlertView alloc] initWithTitle:@"No Twitter Accounts"
                                                           message:@"There are no Twitter accounts configured. You can add or create a Twitter account in Settings."
                                                          delegate:nil
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil];

    [alertViewTwitter show];
}

and then inside the account store callback, you should call it like this
-(void)requestTwitterAccess
{
    [self.accStore requestAccessToAccountsWithType:self.twitterType
                     withCompletionHandler:^(BOOL granted, NSError *error) {
                         if (!granted) {
                             [self performSelectorOnMainThread:@selector(noTwitterAccountMessage) withObject:self waitUntilDone:NO];
                         }
}];

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't remove a binary search tree I have a C code which creates an AVL Tree. I've coded all of the functions to create a tree, but I stuck in the last step which is removing the tree. The function simply does not work. Here is my tree_free function;
void tree_free(TREE tree){

     if (tree != NULL){
        tree_free(tree->root->right);
        free(tree->root->data);
        tree_free(tree->root->left);
        free(tree);
     }

}

So for those who will want to see the insertion function and structs, I will share the codes of these function below.
Here is how I insert numbers in my tree;
void avl_insert(TREE tree, unsigned long long data){

    tree->root = avl_insert_recursive(tree->root, data);

}

And here is the avl_insert_recursive function;
NODE avl_insert_recursive(NODE node, unsigned long long data){

    int balance = 0;

    if( node == NULL){

        return(node_init(data));
    }

    if( data < node->data ){

        node->left = avl_insert_recursive(node->left, data);
        return node;

    }else if( data > node->data){

        node->right = avl_insert_recursive(node->right, data);
        return node;

    }else{

        return node;
    }

    node->height = 1 + max(local_height(node->left), local_height(node->right));

    return node;

}
Lastly, I want to share with you the structs which I created for the TREE and NODE data types.
typedef struct NODE_s *NODE;
typedef struct NODE_s
{
    NODE right;
    NODE left;
    unsigned long long data;
    int height;
} NODE_t[1];

typedef struct TREE_s *TREE;
typedef struct TREE_s
{
    NODE root;
} TREE_t[1];

So Can you diagnose the problem? Thanks for the help.

A: In your tree_free() function, you have this: free(tree->root->data);. But tree->root->data is not a pointer to memory that you previously allocated. You compiler should have warned you about that.
Additionally, your avl_insert_recursive() function seems wrong. There is a code path that will never be reached: height will never be updated because of the if else block. Also, node->data never gets set.
I would also recommend changing the avl_insert_recursive() signature. Instead of accepting a pointer to an already allocated memory for a node, it should accept a pointer to the root node, and allocate and insert the node itself. This way, you could remove free(tree->root->data); from tree_free().


text:
Q: Why is JavaScript so forgiving? I'm new to JavaScript. Recently, I was writing a program and by mistake in the 'for' loop, I made an error in the spelling of length. If I would have made this mistake in other languages I must have got an error and the code wouldn't have continued beyond the for loop but in JavaScript, the code got executed and returned null value.
Could someone throw some light on why the below code doesn't throw an error? Why JS is so forgiving?
for (var i = 0; i < this.x.lenght; i++)


text:
Q: Multiple Services hosted on single Host with common Contract I want to achieve multiple endpoint services from single host address, all are having same Binding contract, for example my host address is
"net.pipe://MyUri/0"

and I created 3 endpoint services against it like
"net.pipe://MyUri/0",
"net.pipe://MyUri/0",
"net.pipe://MyUri/0"

Is it possible or it will cause some problem in results.


text:
Q: How to know Darwin kernel scheduler time slice? On Linux, sched.h contains the definition of

int sched_rr_get_interval(pid_t pid, struct timespec * tp);

to get the time slice of a process. However the file shipping with OS X El Capitan doesn't hold that definition.
Is there an alternative for this on OS X?

A: The API's related to this stuff are pretty byzantine and poorly documented, but here's what I've found.
First, the datatypes related to RR scheduling seem to be in /usr/include/mach/policy.h, around line 155. There's this struct:
struct policy_rr_info {
    ...
    integer_t quantum;
    ....
};

The quantum is, I think, the timeslice (not sure of units.) Then grepping around for this or related types defined in the same place, I found the file /usr/include/mach/mach_types.def, which says that the type struct thread_policy_t contains a field policy_rr_info_t on line 203.
Next, I found in /usr/include/mach/thread_act.h the public function thread_policy_get, which can retrieve information about a thread's policy into a struct thread_policy_t *.
So, working backwards. I think (but haven't tried at all) that you can

*

*Use the thread_policy_get() routine to return information about the thread's scheduling state into a thread_policy_t

*That struct seems to have a policy_rr_info_t sub-substructure

*That sub-structure should have a quantum field.

*That field appears to be the timeslice, but I don't know about the units.

There are no man pages for this part of the API, but this Apple Developer page explains at least a little bit about how to use this API.
Note that this is all gleaned from just grepping the various kernel headers, and I've definitely not tried to use any of these APIs in any actual code.


text:
Q: Create list of objects from csv upload I have a model called leads. I upload them via CSV. The problem is that I would like to name each of the lead lists when uploading so I can filter and view specific lists. Do i need to create another model called list and add the leads to that list.
Models.py
class Lead(models.Model):
  first_name = models.CharField(max_length=20)
  last_name = models.CharField(max_length=20)
  address = models.CharField(default=0, max_length=50)
  city = models.CharField(max_length=30, default="")
  state = models.CharField(max_length=20, default="")
  zipcode = models.IntegerField(default=0)
  phone = models.CharField(max_length=10, null=True, default="", blank=True)
  email = models.EmailField(default="")

  def __str__(self):
   return f"{self.first_name} {self.last_name}"

View.py
def csv_upload(request):

  template = "leads/lead_csv_upload.html"
  data = Lead.objects.all()

  prompt = {
    'order': 'Order of the CSV should be name, email, address,
      phone, profile',
    'profiles': data
          }
  if request.method == "GET":
    return render(request, template, prompt)
  csv_file = request.FILES['file']

  if not csv_file.name.endswith('.csv'):
    messages.error(request, 'THIS IS NOT A CSV FILE')
  data_set = csv_file.read().decode('UTF-8')
  io_string = io.StringIO(data_set)
  next(io_string)
  for column in csv.reader(io_string, delimiter=',', quotechar="|"):
    _, created = Lead.objects.update_or_create(
        first_name=column[0],
        last_name=column[1],
        address=column[2],
        city=column[3],
        state=column[4],
        zipcode=column[5],
        phone=column[6],
        email=column[7],

    )
  context = {}
  return render(request, template, context)

Csv_upload.html
<form action="" method="POST" enctype="multipart/form-data">

    <label for="file1"> Upload a file </label>
    <input type="file" id="file1" name="file">

    <button type="submit">Upload</button>
</form>

A: Because you use update or create, you can simply add a value with the name of the list and then you can filter by that therefore in the frontend you need to create an input and pass it with alongside the csv to the backend.


text:
Q: Inserting a node into a linked list in constant-time? I'm working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes.  It wants me to insert an item y before position p.  Can anybody please look over my code and tell me if I'm on the right track?  If not, can you provide me with any tips or pointers (no pun intended)?
tmp = new Node();
tmp.element = p.element;
tmp.next = p.next;
p.element = y;
p.next = tmp;

I think I may be wrong because I do not utilize the header and tail nodes at all even though they are specifically mentioned in the description of the problem.  I was thinking of writing a while loop to traverse the list until it found p and tackle the problem that way but that wouldn't be constant-time, would it?

A: Just write it down if you get stuck with an algorithm:
// First we have a pointer to a node containing element (elm)
// with possible a next element.
// Graphically drawn as:
// p -> [elm] -> ???

tmp = new Node();
// A new node is created. Variable tmp points to the new node which
// currently has no value.
// p   -> [elm] -> ???
// tmp -> [?]

tmp.element = p.element;

// The new node now has the same element as the original.
// p   -> [elm] -> ???
// tmp -> [elm]

tmp.next = p.next;

// The new node now has the same next node as the original.
// p   -> [elm] -> ???
// tmp -> [elm] -> ???

p.element = y;

// The original node now contains the element y.
// p   -> [y] -> ???
// tmp -> [elm] -> ???

p.next = tmp;

// The new node is now the next node from the following.
// p   -> [y] -> [elm] -> ???
// tmp -> [elm] -> ???

You have the required effect, but it can be more efficient and I bet you can now find out yourself.
It is more clear to write something like:
tmp = new Node();
tmp.element = y;
tmp.next = p;
p = tmp;

Which of course does not work if p is not mutable. But your algorithm fails if p == NULL.
But what I meant to say, is, if you have problems with an algorithm, just write the effects out. Especially with trees and linked lists, you need to be sure all pointers are pointing to the righ direction, else you get a big mess.

A: Hint: insertion into a linked list is only constant when position n = 0, or the head of the list.  Otherwise, the worst-case complexity is O(n).  That's not to say that you cannot create a reasonably efficient algorithm, but it will always have at least linear complexity.

A: The reason why the header and tail node is given in the question is to the update the header and tail reference if the the replacement node that your creating happens to become the header or tail. In other is words, the given previous node is either a header or tail.

A: What you are not doing is linking the element that was before p prior to insertion of y to y. So while y is inserted before p, no one is pointing to y now (at-least not in the code snipped you showed).
You can only insert in constant time if you know the positions of the elements between which you have to insert y. If you have to search for that position, then you can never have a constant time insertion in a single link list.

A: How about using code that is already there? LinkedHashMap, LinkedList, LinkedHashSet. You can also check out the code and learn from it.

A: create a node ptr
ptr->info = item //item is the element to be inserted...
ptr->next = NULL
if (start == NULL) //insertion at the end...
    start = ptr
else
    temp = ptr
    while (temp->next != NULL)
        temp = temp->next
    end while
end if
if (start == NULL) //insertion at the beginning...
    start = ptr
else
    temp = start
    ptr->info = item
    ptr->next = start
    start = ptr
end if
temp = start //insertion at specified location...
for (i = 1; i < pos-1; i++)
    if (start == NULL)
        start = ptr
    else
        t = temp
        temp = temp->next
    end if
end for
t->next = ptr->next
t->next = ptr

A: In a singly LinkedList only adding a Node to the beginning of the list or creating a List with only one Node would take O(1). OR as they have provided the TailNode also Inserting the Node at End of list would take O(1).
every other inserting operation will take O(n).

A: The whole explanation and the 2 codes are in Java... but its easy to translate it to any other language of your choice.
I do want to help you however I am a beginner myself...
Still I have used the logic, sharing it from the queues implementation...
I have pasted two codes one is in O(N) the other contains a method called append which is in O(1)
Now, the explanation

*

*declare the tail node with head node in the class

*now in the method append class in the 2nd code below just look at the tail pointer

*CASE 1: when LL empty
usually people check if (head == null) if true then they point the head to the
new Node and return
whereas what I have done is I checked if (tail == null) and if it was true
then tail = head = newnode meaning that the tail and head both now point to
the new Node to be added.

*CASE 2: when LL is not empty
wait, haha, hear me out first, I know you might be thinking that what if the
LL has just 1 node currently, then what? well... for that...
this case 2 handles it automatically, in case 1 it sets the head and tail
equal to the newnode right, so it now just changes and modifies the tail node
keeping the head node intact.
this way, the head keeps pointing to the first node and the tail keeps updating and pointing to the newnodes created with each append function call.
Hope this explanation helps...
PS. check from line 24 for O(N) and 102 for O(1) and every time a newnode is added to the LL by the append method call, the tail will point to the new node to be added.
import java.io.*;
import java.util.*;

public class Solution {

    // class Solution is what should be called as the LINKEDLIST class but its ok

    Node head;  // declaring a head for the LL

    class Node {    // Node class

        int data;   // the .data variable
        Node ref;   // .ref aka .next

        Node(int data) {    // constructor for initializing the values

            this.data = data;
            this.ref = null;

        }
    }

    public void append(int data) {  // i call 'to join at the end' as append
        // O(N)

        Node newnode = new Node(data);  // new node creation

        if (head == null) {     // checking is head is null aka None in Py
            head = newnode;
            return;
        }

        Node curr = head;   // assigning head to a curr node ready for traversal

        while (curr.ref != null) {  // traversal begins
            curr = curr.ref;
        }                           // traversal ends

        curr.ref = newnode; // this is the last node where the join happens

    }

    public void p() {   // i name printing function as p()

        if (head == null) { // if head is null then print empty
            System.out.println("Empty");
            return;
        }

        Node curr = head;   // same thing - traversal begins here

        while (curr != null) {
            System.out.println(curr.data);
            curr = curr.ref;
        }   // by now all data values have been printed out already

    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);    // scanner class for input

        Solution l = new Solution();    // object creating for LL as Solution class name

        int numberOfNodes = sc.nextInt();   // input for number of NODEs in LL

        for (int i = 0; i < numberOfNodes; i++) {   // loop for .data values

            int data = sc.nextInt();
            l.append(data); // function append call for each (i)

        }

        l.p();  // finally print func call to display output LL

    }
}

class PractGG {
    Node head;
    Node tail;

    class Node {
        int data;
        Node ref;
        Node(int data) {
            this.data = data;
            this.ref = null;
        }
    }
    public void push(int data) {
        Node newnode = new Node(data);
        if (head == null) {
            tail = head = newnode;
            return;
        }
        newnode.ref = head;
        head = newnode;
    }
    public void append(int data) {
        // O(1)
        Node newnode = new Node(data);
        if (tail == null) {
            tail = head = newnode;
            return;
        }
        tail.ref = newnode;
        tail = newnode;
    }

    public void p() {
        if (head == null) {
            System.out.println("Empty");
        }
        Node curr = head;
        while (curr!=null) {
            System.out.print(curr.data + "==>");
            curr = curr.ref;
        }
        System.out.println();
    }
    public static void main(String[] args) {
        PractGG l = new PractGG();
        l.append(1);
        l.append(2);
        l.append(3);
        l.p();
    }
}


text:
Q: how to update secrets manager secret value from lambda function? I have a access token retrieved from an api and its lifetimes is 5 hours. I saw that secrets manager can rotate a secret but minimum rotation time is 1 day. Because of this i thought that i can write a lambda function that works every 5 hours and takes a new token from api and updates secret with this token. This answer https://stackoverflow.com/a/66610124/11902308 mentions that it can be done but i couldn't find any resource about how to update a secret from a lambda function.
Note:
I have multiple task and token is invalid when a new one is generated because of that task have to share it.

A: You didn't mention which AWS SDK you are using, but here is an example for AWS SDK for JS to create or update a Secret.
Additionally, it handles the case for deleted secrets (SecretsManager doesn't delete secrets immediately, it marks them as scheduled for deletion) and restores and updates them.
import { AWSError } from 'aws-sdk';
import SecretsManager, { SecretARNType } from 'aws-sdk/clients/secretsmanager';

const secretsManager = new SecretsManager({ apiVersion: '2017-10-17' });

const putSecret = async (name: string, secret: Record<string, unknown>, secretId?: SecretARNType): Promise<SecretARNType> => {
  try {
    const result = secretId
      ? secretsManager.updateSecret({
          SecretId: secretId,
          SecretString: JSON.stringify(secret),
        })
      : secretsManager.createSecret({
          Name: name,
          SecretString: JSON.stringify(secret),
        });

    const { ARN } = await result.promise();

    if (!ARN) throw new Error(`Error saving secret ${name}`);

    return ARN;
  } catch (error) {
    const awsError = error as AWSError;

    // InvalidRequestException indicates that the secret is scheduled for deletion
    if (awsError.code === 'InvalidRequestException') {
      // restore existng secret
      await secretsManager
        .restoreSecret({
          SecretId: secretId || name,
        })
        .promise();
      // update secret
      const { ARN } = await secretsManager
        .updateSecret({
          SecretId: secretId || name,
          SecretString: JSON.stringify(secret),
        })
        .promise();

      if (!ARN) throw new Error(`Error restoring secret ${name}`);

      return ARN;
    }

    throw error;
  }
};

The code is in TypeScript, but should be easily converted into the language of your choice because the AWS SDK functions have the same name in other languages.


text:
Q: Module not found: com.amazonaws#aws-Java-sdk I'm trying to submit a spark job with these two packages:
com.amazonaws:aws-Java-sdk:1.7.4,org.apache.hadoop:hadoop-aws:2.7.1
My spark version is 3.1.2, hadoop version is 2.7.4 and java version is 11.0.12. The Airflow (2.2.2) is on Kubernetes (k8s).
When I submit the job, I got the message bellow:

Here are all the debug infos. Note that the package was found successfully!
[...]
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - :: loading settings :: url = jar:file:/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - Ivy Default Cache set to: /home/airflow/.ivy2/cache
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - The jars for the packages stored in: /home/airflow/.ivy2/jars
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - org.mongodb.spark#mongo-spark-connector_2.12 added as a dependency
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - com.amazonaws#aws-Java-sdk added as a dependency
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - org.apache.hadoop#hadoop-aws added as a dependency
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - :: resolving dependencies :: org.apache.spark#spark-submit-parent-427a6d1b-6847-4f25-8345-a134eb6d8e19;1.0
[2021-12-20, 12:51:20 -03] {spark_submit.py:523} INFO - confs: [default]
[2021-12-20, 12:51:21 -03] {spark_submit.py:523} INFO - found org.mongodb.spark#mongo-spark-connector_2.12;3.0.0 in central
[2021-12-20, 12:51:24 -03] {spark_submit.py:523} INFO - found com.amazonaws#aws-java-sdk;1.7.4 in central <---------- FOUND!
[...]
2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ---------------------------------------------------------------------
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - |                  |            modules            ||   artifacts   |
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ---------------------------------------------------------------------
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - |      default     |   75  |   1   |   0   |   0   ||   74  |   0   |
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ---------------------------------------------------------------------
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - :: problems summary ::
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - :::: WARNINGS
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - module not found: com.amazonaws#aws-Java-sdk;1.7.4
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ==== local-m2-cache: tried
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - file:/home/airflow/.m2/repository/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.pom
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - -- artifact com.amazonaws#aws-Java-sdk;1.7.4!aws-Java-sdk.jar:
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - file:/home/airflow/.m2/repository/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.jar
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ==== local-ivy-cache: tried
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - /home/airflow/.ivy2/local/com.amazonaws/aws-Java-sdk/1.7.4/ivys/ivy.xml
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - -- artifact com.amazonaws#aws-Java-sdk;1.7.4!aws-Java-sdk.jar:
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - /home/airflow/.ivy2/local/com.amazonaws/aws-Java-sdk/1.7.4/jars/aws-Java-sdk.jar
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ==== central: tried
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - https://repo1.maven.org/maven2/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.pom
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - -- artifact com.amazonaws#aws-Java-sdk;1.7.4!aws-Java-sdk.jar:
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - https://repo1.maven.org/maven2/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.jar
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ==== spark-packages: tried
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - https://repos.spark-packages.org/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.pom
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - -- artifact com.amazonaws#aws-Java-sdk;1.7.4!aws-Java-sdk.jar:
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - https://repos.spark-packages.org/com/amazonaws/aws-Java-sdk/1.7.4/aws-Java-sdk-1.7.4.jar
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ::::::::::::::::::::::::::::::::::::::::::::::
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ::          UNRESOLVED DEPENDENCIES         ::
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ::::::::::::::::::::::::::::::::::::::::::::::
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - :: com.amazonaws#aws-Java-sdk;1.7.4: not found
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - ::::::::::::::::::::::::::::::::::::::::::::::
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO -
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - :: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
[2021-12-20, 12:51:26 -03] {spark_submit.py:523} INFO - Exception in thread "main" java.lang.RuntimeException: [unresolved dependency: com.amazonaws#aws-Java-sdk;1.7.4: not found]

Some important notes:

*

*If I run on my machine (same config) it works;

*If I navigate thought the path looking for the jar, I can found it on "~/.ivy2/cache/com.amazonaws/aws-java-sdk/jars" (a different path of "Ivy Default Cache");

*I don't know how to set the spark.jars.ivySettings and/or spark.jars.ivy properties - I'm not the "java guy";

*If I click on link to the maven repo, It downloads the jar as expected

A: After some other tries I realize that the "J" in uppercase on the string caused the error. When I changed the string to this one:
com.amazonaws:aws-java-sdk:1.7.4,org.apache.hadoop:hadoop-aws:2.7.1
The build got fine. I think I have bad luck when copying the reference for this dependency from the web, which came with this upper "j".


text:
Q: Find the largest minimum distance of n points in a convex compact set Suppose you have to place n points in a convex compact set X $\in R^m$, using the Euclidean distance as the metric, how does the largest minimum distance between those n points change with the number of points n?
To clarify, when you place n points in the set X, you can compute the minimum distance between those n points. I would like to have the placement such that this minimum distance is maximized. I assume that this largest minimum distance decreases with the number of points n. My question is at what rate this distance decreases?

A: It would be difficult  for a given $X$ and a given $k$ to find
$$\rho_{X,k}\colon =\max_{a_1, \ldots, a_k \in X} \min_{i\ne j} d(a_i, a_j)$$
except some easy particular cases ($X$ is a segment, or a circle).
I think that $\rho_{X, k}$ behaves like the radius of $k$ balls tightly packed inside $X$, so it should be
$$k \cdot \rho_{X,k}^n\simeq \operatorname{vol}(X)$$

A: Since every nonempty compact convex subset of $R^m$ is homeomorphic to the closed unit ball of suitable dimension, your argument can be extended to the mth-dimensional inscribed regular polytope that connects the n points that you want to place in the convex set.


text:
Q: Postgres partitioning use case for business to be implemented Please find my use case below and suggest the appropriate solution:
We have done declarative partitioning over our table A based on some key and further range sub partitioned each partition on the basis of createddate range of 90 days.
In the search query to display last 90 day data , I give both column B and  createddate which may pick any of the required partitions.
But how can I display last 90 days data in which a record which is modified last is also shown at the top but its created date might not lie in the last 90 days range..
Basically, I need to partition my huge table based on some key and also on date to split the data into smaller dataset for faster query . The UI needs to display the latest modified records first but the created date also needs to be given in the query to pick the right partition...
Can we do partition differently to achieve this?
Should i find the max modified date  and give it in the range of the created date.
Yes I have a btree index on the modified_date column currently.
SELECT  *  FROM partitioned_table  where
A ='Value'
AND created_date >= '2021-03-01 08:16:13.589' and created_date <= '2021-04-02 08:16:13.589'  ORDER BY viewpriority desc OFFSET 0 ROWS FETCH NEXT 200 ROWS ONLY;
Here viewpriority is basically a long value containing created_date in milliseconds.
Issue here is : I want to  somehow include modified_date also in this query to get the records sorted by modified_date . But that sorting will happen only in the specified created_date range only.  I want those latest modified records also whose created_date might not lie in this range.


text:
Q: Bind radio buttons to enum in a specific list of objects i have got the following situation:

*

*I have a list of objects (List<MyObjects>).

*The Class MyObjects contains an enum called States and some other Properties like ObjectName:
public enum States { State1, State2, State3, State4, State5 }
public string ObjectName { get; set; }
// some more Properties

and a private field and a property like this:
private States _state = States.State1; // State1 is the default state

public States State
{
  get { return _state; }
  set
  {
    if (_state != value)
    {
      _state = value;
      OnPropertyChanged("State");
    }
  }
}

*In my XAML I want to display the list of MyObjects in a ListView and five Radio Buttons for each state of my enum. I do this as follows:
<ListView x:Name="myObjectsListView"
          ItemsSource="{Binding MyObjectList}">
  <ListView.View>
    <GridView>
       <GridViewColumn DisplayMemberBinding="{Binding ObjectName}"
                       Header="Object Name"
                       Width="Auto"/>
       <!-- some more GridViewColumns -->
     </GridView>
   </ListView.View>
</ListView>
<StackPanel>
    <RadioButton x:Name="state1RB"
        Content="{x:Static States.State1}"
        IsChecked="{Binding ElementName=myObjectsListView, Path=SelectedItem.State,
            UpdateSourceTrigger=PropertyChanged,
            Converter={StaticResource enumToBool},
            ConverterParameter={x:Static States.State1},
            Mode=TwoWay}"/>

    <RadioButton x:Name="state2RB"
        Content="{x:Static States.State2}"
        IsChecked="{Binding ElementName=myObjectsListView, Path=SelectedItem.State,
            UpdateSourceTrigger=PropertyChanged,
            Converter={StaticResource enumToBool},
            ConverterParameter={x:Static States.State2},
            Mode=TwoWay}"/>

    <RadioButton x:Name="state3RB"
        Content="{x:Static States.State3}"
        IsChecked="{Binding ElementName=myObjectsListView, Path=SelectedItem.State,
            UpdateSourceTrigger=PropertyChanged,
            Converter={StaticResource enumToBool},
            ConverterParameter={x:Static States.State3},
            Mode=TwoWay}"/>

    <RadioButton x:Name="state4RB"
        Content="{x:Static States.State4}"
        IsChecked="{Binding ElementName=myObjectsListView, Path=SelectedItem.State,
            UpdateSourceTrigger=PropertyChanged,
            Converter={StaticResource enumToBool},
            ConverterParameter={x:Static States.State4},
            Mode=TwoWay}"/>

    <RadioButton x:Name="state5RB"
        Content="{x:Static States.State5}"
        IsChecked="{Binding ElementName=myObjectsListView, Path=SelectedItem.State,
            UpdateSourceTrigger=PropertyChanged,
            Converter={StaticResource enumToBool},
            ConverterParameter={x:Static States.State5},
            Mode=TwoWay}"/>
</StackPanel>

*I'm using an EnumToBoolean Converter which looks like this:
[ValueConversion(typeof(System.Enum), typeof(bool))]
public class EnumToBooleanConverter : IValueConverter
{
  public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
  {
     return value.Equals (parameter);
  }

  public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
  {
    if ((Boolean)value)
      return parameter;
    return null;
  }
}

The binding works, the display of the radio button works but the problem is when i check another Radio Button for the first element in the ListView, the
State is saved correctly. When i now change the selected item in the ListView and then select the first item in the ListView again, no Radio Button is checked, because the getter of the State property doesn't get called.
I was searching for a solution but my specific problem is, that i have a list of MyObjects which contains a state and on changing the selected item, the selected radio button should also be changed.
I hope someone understand my problem and can help.
Thanks in advance,
Mike

A: If you're using MVVM, I have found a good approach to be using an ICommand to  update the SelectedItem in the view model.  The XAML would look like this.
    <RadioButton x:Name="state5RB"
    Content="{x:Static States.State5}"
    Command="{Binding UpdateSelectedItemCommand}"
    IsChecked="{Binding Path=State,
        UpdateSourceTrigger=PropertyChanged,
        Converter={StaticResource enumToBool},
        ConverterParameter={x:Static States.State5},
        Mode=TwoWay}">
       <RadioButton.CommandParameter>
           <myEnum:State>State5</myEnum:State>
       </RadioButton.CommandParameter>

   </RadioButton>

The ViewModel would look something like this:
ICommand UpdateSelectedItemCommand {get;set;}

..

UpdateSelectedItemCommand = new DelegateCommand( (param) =>
{
   State= (States) param;
});

Replace DelegateCommand with your custom object that implements ICommand.

A: Your code works, I've re-created it all in a fresh project and it correctly updates the radio button to reflect the up to date value when you change the SelectedItem (i.e. after changing the selection to non-default).
I think you have something else in the project which is interfering and you should try taking out pieces of the solution and testing them out in isolation.


text:
Q: How to work around amqplib's Channel#consume odd signature? I am writing a worker that uses amqplib's Channel#consume method. I want this worker to wait for jobs and process them as soon as they appear in the queue.
I wrote my own module to abstract away ampqlib, here are the relevant functions for getting a connection, setting up the queue and consuming a message:
const getConnection = function(host) {
  return amqp.connect(host);
};

const createChannel = function(conn) {
  connection = conn;
  return conn.createConfirmChannel();
};

const assertQueue = function(channel, queue) {
  return channel.assertQueue(queue);
};

const consume = Promise.method(function(channel, queue, processor) {
  processor = processor || function(msg) { if (msg) Promise.resolve(msg); };
  return channel.consume(queue, processor)
});

const setupQueue = Promise.method(function setupQueue(queue) {
  const amqp_host = 'amqp://' + ((host || process.env.AMQP_HOST) || 'localhost');

  return getConnection(amqp_host)
    .then(conn => createChannel(conn)) // -> returns a `Channel` object
    .tap(channel => assertQueue(channel, queue));
});

consumeJob: Promise.method(function consumeJob(queue) {
  return setupQueue(queue)
    .then(channel => consume(channel, queue))
  });

My problem is with Channel#consume's odd signature. From http://www.squaremobius.net/amqp.node/channel_api.html#channel_consume:
#consume(queue, function(msg) {...}, [options, [function(err, ok) {...}]])
The callback is not where the magic happens, the message's processing should actually go in the second argument and that breaks the flow of promises.
This is how I planned on using it:

return queueManager.consumeJob(queue)
  .then(msg => {
     // do some processing
  });

But it doesn't work. If there are no messages in the queue, the promise is rejected and then if a message is dropped in the queue nothing happens. If there is a message, only one message is processed and then the worker stalls because it exited the "processor" function from the Channel#consume call.
How should I go about it? I want to keep the queueManager abstraction so my code is easier to reason about but I don't know how to do it... Any pointers?

A: As @idbehold said, Promises can only be resolved once. If you want to process messages as they come in, there is no other way than to use this function. Channel#get will only check the queue once and then return; it wouldn't work for a scenario where you need a worker.

A: just as an option. You can present your application as a stream of some messages(or events). There is a library for this http://highlandjs.org/#examples
Your code should look like this(it isn`t a finished sample, but I hope it illustrates the idea):
let messageStream = _((push, next) => {
  consume(queue, (msg) => {
   push(null, msg)
  })
)
// now you can operate with your stream in functional style
message.map((msg) => msg + 'some value').each((msg) => // do something with msg)

This approach provides you a lot of primitives for synchronization and transformation
http://highlandjs.org/#examples


text:
Q: Datatable with form on multipage validation issue I have created table using datatable with in each row have td with input or select field.
with having on multiple pages.
The issues is the datatable render 10 row html element at time by default and jquery validation render per page as html.
I need solution to put validation of entire cell of all pagination(pages) using jQuery.
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

         <input id="bn_0" name="bd[0][bn]" placeholder="Enter Bank Name" value="testbank" aria-required="true" class="valid" aria-invalid="false">

         <select id="sts_0" class="sts" name="bd[0][sts]" aria-required="true">
                    <option value="">Select Status</option>
                    <option value="Y" selected="">on</option>
                    <option value="N">off</option>
                </select>

   100 more tr td input select

    </style>

         $(document).ready(function() {
                    $('#banklist').DataTable({
                        scrollX:        true,
                        scrollCollapse: true,
                    });
     });

https://jqueryvalidation.org/
jQuery Validation:
$("#banklist").validate({
                    errorPlacement: function(error, element) {
                        var ele_name = element.attr('name');
                        console.log(ele_name);
                        $('.valid').attr('style','border : 1px solid #c2bfbf !important');
                        if($('input,select').hasClass('error')) {
                            //$('label.error').remove();
                            $('input.error, select.error').attr('style','border : 1px solid red !important');
                            error.appendTo( $('.error[name="'+ele_name+'"]').parent('td'));
                        }
                }
  });

A: Look at ajax method. Here as example how I used it for almost the same problem:
$('#dt-all-orders').DataTable({
    "ajax": "ajax_files/dt_get_all_orders.php",
    "language": {
        "url": "js/datatables/datatables.lang.ua.txt"
    },
    "initComplete": function () {
        $('[data-toggle="popover"]').popover();
    },
    "columnDefs": [
        {width    : "30px", targets: [0]},
        {width    : "120px", targets: [2]},
        {width    : "120px", targets: [3]},
        {width    : "120px", targets: [4]},
        {width    : "120px", targets: [5]},
        {width    : "80px", targets: [6]},
        {className: "text-center", targets: [0, 2, 3, 4, 5]},
        {className: "td-actions text-center", targets: 6},
    ],
    "aoColumns": [
        null,
        { "bSortable": false },
        null,
        null,
        null,
        null,
        { "bSortable": false }
    ],
    "lengthMenu": [
        [10, 25, 50, 100],
        [10, 25, 50, 100]
    ],
    "stateSave": true,
    "deferRender": true,
    "order": [
        [0, "desc"]
    ],
});

But in this case you have to manually create all columns and use php file with sql query.


text:
Q: Rx.Net : perform asynchronous side-effect when subscription is disposed I have a device that communicates with the computer via the serial port. Upon sending a "START" command, the device responds with an acknowledgement and it starts monitoring some external activity. It then asynchonousely transmitts some messages on the serial port depending on that external activity. When the device receives a "STOP" command, it responds with an acknowledgement, and then it stops sending more messages (representing the external activity).
I've implemented the Start/Stop commands with cold observables, that perform side-effects (send command on the serial port), and emits a single Unit.Default if an ackowledge is received on the SerialPort. I want to construct an IObservable that emits messages coresponding to the external activity, and perform "START" side-effect when it is subscribed to, and "STOP" side-effect when the subscription is disposed.
"START" is easy, i just have to do a `SelectMany', but i dont know how to perform "STOP".
  class MonitoringDevice
{
    private SerialPort _sp;
    private IObservable<byte> _receivedBytes;

    public IObservable<ExternalActivity> ActivityStream { get; }

    public  MonitoringDevice()
    {
        _sp = new SerialPort("COM1");
        _receivedBytes = Observable
                         .FromEventPattern<SerialDataReceivedEventHandler, SerialDataReceivedEventArgs>(
                          h =>
                          {
                              _sp.DiscardInBuffer();
                              _sp.DataReceived += h;
                          },
                          h =>
                          {
                              _sp.DataReceived -= h;
                          })
                         .SelectMany(x =>
                         {

                             byte[] buffer = new byte[1024];
                             var ret = new List<byte>();
                             int bytesRead = 0;
                             do
                             {
                                 bytesRead = _sp.Read(buffer, 0, buffer.Length);
                                 ret.AddRange(buffer.Take(bytesRead));
                             } while ((bytesRead >= buffer.Length));
                             return ret;

                         })
                         .Publish()
                         .RefCount();

        ActivityStream = StartMonitoringAsync()
                         .SelectMany( _receivedBytes.ToActivity());
                         // we need to execute StopMonitoringAsync
                         // when a subscription to ActivityStream is disposed

        _sp.Open();
    }

    private IObservable<Unit> StartMonitoringAsync()
    {
        return Observable
               .Create<Unit>(
                obs =>
                {
                    _sp.Write("START");
                    return _receivedBytes
                           .ToAcknowledge()
                           .FirstAsync()
                           .Timeout(TimeSpan.FromMilliseconds(1000))
                           .Subscribe(obs);
                });
    }

    private IObservable<Unit> StopMonitoringAsync()
    {
        return Observable
               .Create<Unit>(
                obs =>
                {
                    _sp.Write("STOP");
                    return _receivedBytes
                           .ToAcknowledge()
                           .FirstAsync()
                           .Timeout(TimeSpan.FromMilliseconds(1000))
                           .Subscribe(obs);
                });
    }

}

ExternalActivity is just a POCO.
ToAcknowledge is an extension method returning an IObservable that emits Unit.Default when the device transmitts an acknowledgement. - this is working as expected;
ToActivity is an extension method returning an IObservable that parses the incomming serial data and emits ExternalActivity objects. - this is working as expected;

Edit : Added implementation for ToAcknowledge and ToActivity extension methods.
public static IObservable<Unit> ToAcknowledge(this IObservable<byte> source)
    {
        return source.Buffer(3, 1)
               .Where(bfr => bfr.SequenceEqual(new byte[] { 65, 67, 75 })) // ACK
               .Select(x => Unit.Default);

    }

    public static IObservable<ExternalActivity> ToActivity(this IObservable<byte> source)
    {
        return source
               .Publish(ps => ps.Buffer(ps.Where(x => x == 1),             // SOH
                                           bo => ps.Where(x => x == 4)))   // EOT
               .Select(bfr => bfr.Take(bfr.Count - 1).Skip(1))
               .Where(bfr => bfr.Count() == 12)
               .Select(bfr =>
               {
                   var timestamp = BitConverter.ToInt64(bfr.Take(8).ToArray(), 0);
                   var id = BitConverter.ToInt32(bfr.ToArray(), 8);
                   return new ExternalActivity(timestamp, id);
               });
    }

A: You can modify your StartAsync to be this:
private IObservable<Unit> StartAsync(Action unsubscribe)
{
    return
        Observable
            .Create<Unit>(o =>
            {
                var subscription =
                    Observable
                        .Timer(TimeSpan.FromSeconds(1))
                        .Select(_=> Unit.Default)
                        .Subscribe(o);
                return new CompositeDisposable(
                    subscription,
                    Disposable.Create(unsubscribe));
            });;
}

Then you can inject in any Action unsubscribe you like.
Try testing with this code:
var subscription =
    StartAsync(() => Console.WriteLine("Done"))
    .Subscribe();

Thread.Sleep(3000);

subscription.Dispose();

You'll see "Done" written to the console after 3 seconds.


text:
Q: Ruby On Rails 3 and Webrick issue Thanks for taking a look at this.
I started a beginner's tutorial on RoR through lynda.com. I followed the instructions to the letter. Everything was working so far until I got to accessing Webrick. When I typed in "rails server" to begin work, I got this error message below.
/Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle: dlopen(/Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib (LoadError)
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle

from /Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2.rb:8
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:68:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:68:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:66:in `each'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:66:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:55:in `each'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb:55:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.12/lib/bundler.rb:120:in `require'
from /Users/macuser/Sites/simplecms/config/application.rb:7
from /Library/Ruby/Gems/1.8/gems/railties-3.0.6/lib/rails/commands.rb:28:in `require'
from /Library/Ruby/Gems/1.8/gems/railties-3.0.6/lib/rails/commands.rb:28
from /Library/Ruby/Gems/1.8/gems/railties-3.0.6/lib/rails/commands.rb:27:in `tap'
from /Library/Ruby/Gems/1.8/gems/railties-3.0.6/lib/rails/commands.rb:27
from script/rails:6:in `require'
from script/rails:6

I'm using a

*

*iMac

*Ruby 1.87

*Gem 1.7.2

Since I'm not experienced with anything Ruby, I'm lost on how to fix this.
Thanks in advance for your attention and help if possible.

A: Run these at the terminal:
gem install bundler
bundle

And then you should be able to boot the server.
Edit: You should really look into using rvm to manage your ruby installs and gemsets. It'll save you a lot of time and effort in installing them too.

A: I ran into the same problem as you (also attempting to go through the Lynda course), and also being a newbie I got pretty frustrated pretty quickly.
Buuuuut, after some searching, I found and answer here I got it to work.
First, I installed the 32-bit version of MySQL, as opposed to the 64-bit version, but I'm not sure if that made a difference.
Then, uninstall the Mysql gem
 gem uninstall mysql2

then reinstall it
sudo gem install mysql2

and finally
sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Ruby/Gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle

and you should be good to go! Worked for me anyways. good luck!

A: export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

This is the code that worked for me :D

A: I had the same problem. I simply ran the following code:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib

Press enter, and then run
rails server

and it worked!

A: Correct way that worked for me was:
cd ~ [command]
nano .bash_profile [command]
add this line of code:

export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$DYLD_LIBRARY_PATH"

ctrl+x [save]
y [yes]
cd Sites/sitename/ [command]
rails server [run WEBrick server]
and you should get this message:

=> Booting WEBrick
  => Rails 3.2.11 application starting in development on localhost:3000
  => Call with -d to detach


text:
Q: Read random string from a file without reading all file how to read a random line from a file without reading all the file?
I tried FileStream class and Seek, Read functions. But didn't get luck with 100% working method.

A: This isn't possible as a line is defined by a carriage return or line break. There is no way to know how many lines there are in the file without reading all of it unless you know something about the structure of the file; for example, that every line is 80 characters. In that case you're picking a random 80 characters from a file of length N, in which case your FileStream seek is the way to go.


text:
Q: C - Find Prime number This is my prime number function and I have a problem. Why does it return 0 when I pass it 2147483647?
int     ft_is_prime(int nb)
{
  if (nb<2)
    return (0);
  else if (nb==2)
    return (1);
  else if (nb%2==0)
    return (0);
  else
  {
    int i=3;
    int carre=9;
    while (carre <= nb)
    {
        if (nb % i == 0)
            return (0);
        carre=carre+4*i+4;
        i=i+2;
    }
    return (1);
  }
}

A: As @Eugene-Sh said, there is an overflow while computing carre.
Also, the standard int is at minimum 16bits. However most of compilers now make it 32bits. So at least you should check the limit, in order your code gets well in all the ways.
Change to long long to ensure you will have good result, both for carre and nb, such that you got 64 bits. But it is only half of the path. as said in a comment, you could still have an overflow when you go over this limit.
So something like this, without changing type:
int max = INT_MAX; // from limits.h
int maxsqrt = sqrt(INT_MAX); // cast to int, such that maxsqrt² is the max square
if (maxsqrt % 2 == 0)
   maxsqrt--; // only odd number considered
int maxcarre = maxsqrt*maxsqrt; // this is the max square (carre in french) for an odd INT

Then in your loop, you could now check if carre is the last one you can compute since maxcarre is the biggest one:
while (carre <= nb)
{
    if (nb % i == 0)
        return (0);
    if (carre >= maxcarre) // this is the last odd square we could compute before overflow
        return (-1); // if this -1 represents a "don't" know code for you
    carre=carre+4*i+4; // this compute the next square of an odd number
    i=i+2;
}

I would recommend however to use at least long (and therefore changing max to LONG_MAX) in order to get more capacity and still in the range of the CPU (64 bits on modern compiler), or even long long since at least it is 64 bits on all compilers.
As @Veltas said: long is 64-bit on some 64-bit compiler implementations. It's not dependant on the OS. Also, IIRC Microsoft's VC++ uses 32-bit long on 64-bit as well.
Thanks to @Veltas, @EugeneSh. and other helping people for their precious feedback!

A: #include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
/* As we know 2,3,5,7,11..19....
What is prime number
A prime number (or a prime) is a natural
number greater than 1 that has no positive
divisors other than 1 and itself.
so the formula in if we have n numbers as a input
how we find the prime number ,the formula is
divisible by 2 ...n-1. so 3%2=1 then 3 is a
prime number,10%2=0 so 10 is not a prime number
now 9%2=1 but 9%3=0 that is why we will make a
condition of for loop that divisible 9 with all
the numbers from 2...9-1 and find out whether it
divisible value is 0.
*/
int main()
{
    int i,n,j;
 bool flag;
    printf("Enter the Range Number:");
    scanf("%d",&n);
        for(i=2;i<=n;i++)
        { bool flag=true;
            for(j=2;j<=i-1;j++)
            {

                if (i%j==0){
            flag=false;
            break;}
            }
 if (flag==true)
                printf("%d\n",i);
            }

    return 0;

}


text:
Q: Mobile Push Contact Info to Email Studio/Contact Builder In my data schema, I have information going into the Mobile Push contact attributes. Unfortunately, I do not know how to bring this data into the Email Studio/Contact Builder.
I would like to do this because if I can get this information into a Data Extension, then I believe I could utilize this information for Journey Builder/Automation Studio.
Does anyone have any ideas if/how this can be accomplished?

A: According to this post the _MobilePush system data view includes the following:
| Name             | FieldType | MaxLength | IsRequired |
| :-               | :-        | :-        | :-         |
| _Alias           | Text      | 100       | FALSE      |
| _APID            | Text      | 38        | TRUE       |
| _Badge           | Number    | FALSE     |            |
| _Channel         | Text      | 20        | FALSE      |
| _City            | Text      | 200       | FALSE      |
| _ContactID       | Text      | TRUE      |            |
| _CreatedBy       | Text      | FALSE     |            |
| _CreatedDate     | Date      | TRUE      |            |
| _Device          | Text      | 100       | FALSE      |
| _DeviceID        | Text      | 200       | TRUE       |
| _DeviceType      | Text      | 20        | FALSE      |
| _FirstName       | Text      | 100       | FALSE      |
| _HardwareId      | Text      | 100       | FALSE      |
| _IsHonorDST      | Boolean   | FALSE     |            |
| _LastName        | Text      | 100       | FALSE      |
| _LocationEnabled | Boolean   | FALSE     |            |
| _ModifiedBy      | Text      | FALSE     |            |
| _ModifiedDate    | Date      | TRUE      |            |
| _OptInDate       | Date      | FALSE     |            |
| _OptInMethodID   | Text      | FALSE     |            |
| _OptInStatusID   | Text      | TRUE      |            |
| _OptOutDate      | Date      | FALSE     |            |
| _OptOutMethodID  | Text      | FALSE     |            |
| _OptOutStatusID  | Text      | FALSE     |            |
| _Platform        | Text      | 100       | FALSE      |
| _PlatformVersion | Text      | 100       | FALSE      |
| _ProviderToken   | Text      | 200       | FALSE      |
| _Source          | Text      | FALSE     |            |
| _SourceObjectId  | Text      | 200       | FALSE      |
| _State           | Text      | 200       | FALSE      |
| _Status          | Text      | FALSE     |            |
| _SystemToken     | Text      | 4000      | FALSE      |
| _TimeZone        | Text      | 50        | FALSE      |
| _UTCOffset       | Decimal   | 4         | FALSE      |
| _ZipCode         | Text      | 20        | FALSE      |


text:
Q: Is there a way to make a scrollable gridview without putting it inside a div? I know a gridview can be made scrollable by including it inside a div and making the overflow to auto. But I'm using tables to align my page and found out that it's not necessarily a good idea to put a div inside a td, so are there any other way around it?

A: you can use this library. it's crosss browser and work seamlessly. Scrolling grid
<yourNameSpace:ScrollingGrid runat="server" ID=sg1
       Width=450 Height=240 CssClass=sgTbl>

    <asp:DataGrid runat="server" ID=Grid2 CellPadding=5 CellSpacing=1
      AutoGenerateColumns=True AllowSorting=True
      AllowPaging=True PageSize=35>
        <HeaderStyle BackColor=red ForeColor=white Font-Bold=True />
        <ItemStyle BackColor=#fefefe />
        <AlternatingItemStyle BackColor=#eeeeee />
        <PagerStyle BackColor=silver ForeColor=White
                    Mode=NumericPages />
    </asp:DataGrid>

  </yourNameSpace:ScrollingGrid>

this will automatically make your gridview scrollable with fixed header.

A: As gridview is reader as table.
Try using the overflow CSS property. There are also separate properties to define the behavior of just horizontal overflow (overflow-x) and vertical overflow (overflow-y).
Since you only want the vertical scroll, try this:
table {
  height: 500px;
  overflow-y: scroll;
}

EDIT:
Apparently <table> elements don't respect the overflow property. This appears to be because <table> elements are not rendered as display: block by default (they actually have their own display type). You can force the overflow property to work by setting the <table> element to be a block type:
table {
  display: block;
  height: 500px;
  overflow-y: scroll;
}

Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.


text:
Q: Python: concatenate pandas multiindex I need to generate a pd.DataFrame with columns being composed by a list and a Multiindex object, and I need to do it before filling the final dataframe with data.
Say the columns are ['one', 'two'] and the multiindex obtained from from_product:
import pandas as pd

col_21 = ['day', 'month']
col_22 = ['a', 'b']

mult_2 =  pd.MultiIndex.from_product([ col_21, col_22 ])

I would like to get a list of columns which looks like this:
'one' | 'two' | ('day','a') | ('day','b') | ('month','a') | ('month','b')

One possible solution would be to use two different and separate Multiindex, one with a dummy column, both generate by from_product

col_11 = ['one', 'two']
col_12 = ['']
col_21 = ['day', 'month']
col_22 = ['a', 'b']

mult_1 =  pd.MultiIndex.from_product([ col_11, col_12 ])
mult_2 =  pd.MultiIndex.from_product([ col_21, col_22 ])

How could I get to this?
(one, '') | (two, '') | ('day','a') | ('day','b') | ('month','a') |  ('month','b')

I have tried several trivial solutions, but each gave me a different error or a wrong result
mult_1+mult_2 #TypeError: cannot perform __add__ with this index type: MultiIndex

pd.merge #TypeError: Can only merge Series or DataFrame objects, a <class 'list'> was passed

pd.MultiIndex.from_arrays([ mult_1, mult_2 ]) #NotImplementedError: isna is not defined for MultiIndex

Thank you for your advices

A: If possible, the best is create MultiIndex in index by columns one, two and then MultiIndex in columns by pairs - so not mixed non multiindex with multindex values:
col_21 = ['day', 'month']
col_22 = ['a', 'b']
mult_2 =  pd.MultiIndex.from_product([ col_21, col_22 ])

one = range(5)
two = list('ABCDE')
mult_3 =  pd.MultiIndex.from_arrays([ one, two], names=['one','two'])

df = pd.DataFrame(0, columns=mult_2, index=mult_3)
print (df)
        day    month
          a  b     a  b
one two
0   A     0  0     0  0
1   B     0  0     0  0
2   C     0  0     0  0
3   D     0  0     0  0
4   E     0  0     0  0

Use Index.append:
print (mult_1.append(mult_2))

MultiIndex([(  'one',  ''),
            (  'two',  ''),
            (  'day', 'a'),
            (  'day', 'b'),
            ('month', 'a'),
            ('month', 'b')],
           )

Or Index.union with sort=False:
print (mult_1.union(mult_2, sort=False))

MultiIndex([(  'one',  ''),
            (  'two',  ''),
            (  'day', 'a'),
            (  'day', 'b'),
            ('month', 'a'),
            ('month', 'b')],
           )


text:
Q: Can I dynamically load additional Spring configuration files into an existing WebApplicationContext? Upon starting my webapp within Tomcat 6.0.18, I bootstrap Spring with only what is necessary to initialize the system -- namely, for now, database migrations.  I do not want any part of the system to load until the migrations have successfully completed.  This prevents the other beans from having to wait on the migrations to complete before operating, or even instantiating.
I have a startup-appcontext.xml configured with a dbMigrationDAO, a startupManager which is a ThreadPoolExecutor, and lastly, a FullSystemLauch bean.  I pass a list of configuration locations to the FullSystemLaunch bean via setter injection.  The FullSystemLaunch bean implements ServletContextAware, gets a reference to the current WebApplicationContext and thus I can have a ConfigurableListableBeanFactory.  Unfortunately, this bean factory isConfigurationFrozen() returns true, so by calling beanFactory.setConfigLocations(configLocations) has no effect.
Can I accomplish this or is Spring preventing me from doing so because it's a bit out of the ordinary?  It seems reasonable if understood, but also a bit dangerous.  And yes, I'm willing to blow away the current context b/c the currently loaded Singletons are not needed once initialization is complete.
Thank you for the help.

A: My opinion would be to allow Spring to initialise your beans is it sees fit - in the order of their declared dependencies.
If you need database migrations there are a couple of patterns to have them run first:

*

*if you're using Hibernate/JPA make your sessionFactory/persistenceManager depend-on the migration beans;

*if you're using plain JDBC create a wrapper DataSource and in its init-method invoke the migrations ( code sample)

The advantage is clear: simplicity.

A: You could use the existing context as parent context for the other contexts, although I doubt that you could replace the existing WebApplicationContext.
If you use EAR - WAR packaging, you get this out-of-the-box (sort of) by loading an application context from the EAR and then adding one in the WAR.
Not sure whether this is applicable in your situation.

A: Could lazy-initialization be an alternative for what you are trying to achieve?

A: Possible XmlBeanDefinitionReader can help you?

A: you can upcat the WebApplicatonContext to ConfigurableWebApplicationContext
then use the setConfigurations method.
dont forget refresh;

A: There was the same task and I created two contexts: startUpContext.xml and applicationContext.xml. In startUpContext.xml there is a bean, which triggers loading of appliationContext.xml. (application context location is configured in startUpContext.xml as a property of a trigger). And finally the trigger replaces locations of the current context and refreshes it:
applicationContext.setConfigLocations(locations);
applicationContext.refresh();

(startUpContext.xml is loaded with a standard spring context loader listener)


text:
Q: Phalcon does not receive GET URI with escaped html characters I have a GET URI
/phalcon-dash/change/action/get/c123h%23516466

In ChangeController, I only have this
$params = array('get', 'c123h')

It looks like Phalcon omits everything after # (%23 is the encoded of #)
Do I need to do anything to make Phalcon receives everything?


text:
Q: Shared shopping cart between subsites I'm trying to get a fully functionally Magento 1.6.1.0 installation with 3 sub-sites and a main site (configured each as store inside Magento), that share of course the clients information across the all the stores.
The problem is that I can't seems to be able to have a persistent shopping cart across the all stores, allowing the customers to get products from a sub-site then another and so on without having to pay each time the shipping fees for what is at the end only 1 order.
I've followed several different tutorials that claimed to be able to achieve that but none of them worked as expected, and also none of them specified to which version of Magento they where supposed to work.
Any tip is welcome, thanks to everyone.


text:
Q: Where is Sickbay on the Enterpise(s) If you know or have links to diagrams, I'd be interested knowing the answer to where on various Enterprises Sickbay is located. I've found some maps on the internet, but they focus on Engineering and kind of lame portrays of crew quarters, not where sickbay is. I would like to know where it is at least in terms of Primary or Secondary hull. Also not just TNG: bloody A...B..C....and D. Thanks if you can help!

A: Each starship would have the medical quarters in slightly differing locations depending on design and technology requirements.

*

*For the most part, given the need for defense and protection, medical facilities are located in the central region of the ship protected by the ventral and dorsal shields and multiple deck layers.

*On larger ships, there are often multiple sickbay facilities both in the primary hull and the secondary hull. There are also medical surgical and support facilities located through out the ship.
Enterprise NX-01
Medical is amidships likely one of the most protected regions of the ship in terms of shields and armor.

*

*The NX-class had a single sickbay ward on E Deck. The room contained a main operating table, as well as several side beds for recovery of patients and an imaging chamber. It was also easily capable of caring for non-humanoid patients.

*The facility was open-plan, with laboratory equipment in the main sickbay area. Aboard Enterprise NX-01, Dr. Phlox often kept various different species of animals in sickbay, which he would sometimes use in the treatment of injuries in lieu of more traditional treatments. One such animal was an osmotic eel. (ENT: "These Are the Voyages...", "Fight or Flight", "A Night in Sickbay", "Broken Bow")

USS Enterprise 1701 (Constitution Class Cruiser, unrefit)

*

*Due to its critical importance, the primary sickbay was usually located deep within the saucer section of most Federation starships.

*On Constitution-class starships, sickbay was located on Deck 7. (In TOS: "Mirror, Mirror" it was located on Deck 5.) It was maintained and operated by the Astro-Medicine Department. There were at least four wards. (TOS: "The Naked Time") In addition to this ward, there was an isolation ward. (TOS: "Turnabout Intruder")

Click here for much larger image.
USS Enterprise, NCC 1710-D (Galaxy Class Cruiser)

No official diagrams held a confirmed configuration of the deckplans of the Enterprise D placing the primary medical facility. Its location on this non-offical image corresponds with text entries and previous specifications for medical facilities. Official blueprint schematics list only military offensive and defensive assets. A larger look at this blueprint can be found at the link.

*

*Due to its critical importance, the primary sickbay was usually located deep within the saucer section of most Federation starships. Sickbays were well-protected, and generally had a phaser locker for defense of the facility in the event the ship was boarded. (TNG: "Starship Mine", "Timescape")

*Galaxy-class ships had at least three sickbay wards. (TNG: "Tapestry") Two sickbay wards were located on Deck 12 of the saucer module, with the primary facility on the starboard side of the ship and a backup on the port. (TNG: "A Matter of Perspective") Another sickbay was in the stardrive section. (TNG: "The Arsenal of Freedom"; Star Trek Generations)

*Galaxy-class ships had one of the largest medical care facilities in the fleet, taking up the majority of Deck 12. In an alternate timeline, Captain Rachel Garrett marveled at the size and advancement of the Enterprise-D sickbay, stating that she had "never seen anything like it before, even on a starbase." (TNG: "Yesterday's Enterprise", "Remember Me")

*Galaxy-class ships normally had several doctors on board and at least four medical personnel on duty at all times. (TNG: "Remember Me", "Genesis")

REF: Memory Alpha, Sickbay

A: You can find the schematics here" http://www.waxingmoondesign.com/DeckEPage.html
There's also another site with blueprints: http://www.cygnus-x1.net/links/lcars/blueprints-main2.php


text:
Q: Расширение для chrome: не работает jQuery Решил написать расширение для vk.com в chrome. Занятие - проще некуда. В "content_scripts" подключил свой vkc_script.js, который исправно работал на всех "*://vk.com/*".
Однако, потом я решил написать что-нибудь по-серьёзнее, захотел подключить jQuery и появилась проблема:
jQuery на странице есть:

.
но использовать его почему-то не получается:
Люди добрые, памагити!

manifest.json:
{
      "manifest_version": 2,
      "name": "VKColor",
      "description": "Color is important.",
      "version": "1.0",
      "content_scripts": [{
          "matches": ["*://vk.com/*"],
          "js": ["/script/vkc_script.js", "/script/jquery.js"],
          "css": ["/script/vkc_style.css"]
      }]
}

Если jQuery подключать динамически в vkc_script.js - все в порядке, но этот вариант меня не устраивает.

A: Скорее всего проблема в том, что jquery.js подхватывается после vkc_script.js
Поэтому, наиболее вероятно, надо просто поменять порядок:
"js": ["/script/jquery.js", "/script/vkc_script.js"]


text:
Q: Why some css font family does not work? I used those css code

.logo h2 {
  font-family: Pacifico, MyriadPro-Regular, AdobeInvisFont;
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}

But it does not work. What should I do?

A: It seems the font is not imported.
You have to import the font to use it.
You can import the font via Google CDN or download the font and have it in your server.
Code to use Google CDN Font
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">

Just include the above code in the  section of your HTML document.
Refer https://fonts.google.com/specimen/Pacifico?selection.family=Pacifico for more options to import the font.
Refer https://fonts.google.com for more info on Google fonts.
Follow the same for all the other fonts you use.

A: Please try this code. I have found Google Font for 'Pacifico'. Find for others if available. If they are not free and you have purchased those, add relative path of their location in @font-face rule.
@font-face {
    font-family: "Pacifico";
    src: url('https://fonts.googleapis.com/css?family=Pacifico');
}

.logo h2 {
  font-family: "Pacifico", "MyriadPro-Regular", "AdobeInvisFont";
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}


text:
Q: "sudo bash" ignoring read-only permission of .bash_history file This problem is in an up-to-date 12.04, and seems to have started recently.
I have my .bash_history file set to read only. Lately I've noticed that despite this the file is being modified !
Here's the scenario.
In a new terminal, here is the tail of the file:
$ tail -5 .bash_history
mkdir -p ttt ; gs -dNOPAUSE -sDEVICE=png16m -r180 -sOutputFile=ttt/p%03d.png *.pdf
rsync -av /home/u1204 /media/SEAGATE/u1204
gnote.late.reminders|GREP_COLOR='1;32' egrep -i "is overdue"
pvr_iplayer -x -HD /home/u1204/Documents/pvr/tv-hd ; pvr_iplayer -x -STD /home/u1204/Documents/pvr/tv-std
exit

open a shell with raised privileges
 $ sudo bash [sudo]
 password for u1204:

 # ls -l ~/.bash_history
 -r-------- 1 u1204 u1204 1266 Feb 23 19:52 /home/u1204/.bash_history

so .bash_history is still definitely read-only.
Do something, then exit the escalated shell:
# echo "written to history file"
written to history file

# exit
exit

And Voilà, the history file has been modified !
$ ls -l ~/.bash_history
-r-------- 1 u1204 u1204 1324 Feb 23 20:10 /home/u1204/.bash_history

Open another terminal to confirm:
$ tail -5 .bash_history
pvr_iplayer -x -HD /home/u1204/Documents/pvr/tv-hd ; pvr_iplayer -x -STD /home/u1204/Documents/pvr/tv-std
exit
ls -l ~/.bash_history
echo "written to history file"
exit

I'm pretty sure that it didn't used to do this (in 10.04 at least).
Anyway, this can't be correct behaviour, can it?

A: Root has universal read/write to everything.  Period.
Proponents of windows like to claim its authentication system is stronger because it doesn't have a "god" account and even local administrators can be explicitly denied.
You cannot deny root any access to any thing on the local system.
After some comments, it got me thinking you might be looking for a way to not write to bash history at all.  You could do that like this: http://www.commandlinefu.com/commands/view/7041/dont-save-commands-in-bash-history-only-for-current-session
Putting unset HISTFILE in your bashrc for those that don't want to follow the link.

A: Yes, you can ultimatively deny access.
chattr +i

A: @Thor

I'm pretty sure that it didn't used to do this (in 10.04 at least).

It actually does.
What I think happens is if you use sudo, you still get to keep your identity but with lifted privileges, if you used sudo su - on the other hand, you would have become the "real root". hence the difference.

A: RO is nothing a program cannot override, as long as you're root or owner of the file. So the correct way is not to set the file to r--, but to execute
unset HISTFILE
For "sudo -s" this should work (environment is copied, exactly the reason why your user's .bash_history is used), for "sudo -i" (like "su -") you're using /root/.bash_history anyway. If you do not want to do this, you need to unset HISTFILE in your root's .bashrc/.bash_profile.
btw: as already mentioned the correct way to get a root-shell is sudo -s / sudo -i. "sudo su" or "sudo bash" works, but its a rather unclean way to do so.


text:
Q: How to make rsync read SRC from STDIN? I want to dump my MySQL database and make daily backups with rsync.
First approach I came up with is something like mysqldump -ufoo -pbar baz > /var/tmp/baz.sql && rsync /var/tmp/baz.sql /backup/ && rm /var/tmp/baz.sql.
Then I started to wonder if it is possible not to use the temporary file /var/tmp/baz.sql, but instead to pipe the output of mysqldump directly to rsync.
To be more specific, what I want is quite similar to a command line which we use to update the GPG key for apt in Ubuntu: gpg --export --armor CE49EC21 | sudo apt-key add -, where the receiver of the pipe supports this '-' argument indicating it'll read from stdin. I suppose rsync doesn't have a similar argument. But I wanna know if there is a workaround.

A: This is right, it doesn't work this way. It is because rsync is made to transfer complete file trees from A to B.
Because of the way rsync works, it cannot work, because rsync calculates several checksums before choosing to transfer a particular file (or parts of it), and doing so in only 2 iterations (ping-pong-steps).
That means a file has to be read several times. That would not work with a (potentially large) SQL dump because it would have to be buffered somehow. And this buffering is up to the user.
Actually storing the file should be the best workaround, especially if it is a file which only gets gradual differences.


text:
Q: Is it bad practice to modify function input arguments? I've been solving problems on Leetcode.
I noticed that it's often easy to reduce the space complexity from O(n) to O(1) by solving the problem "in place" --- that is, by updating the input list instead of returning a new list.
However, I suspect that modifying the input may be a bad practice.
I found an example of someone saying as much (see comment at bottom): https://leetcode.com/problems/circular-array-loop/discuss/94183/simple-on-solution-with-o1-space-complexity
So, is it truly the case that modifying arguments is a bad practice? Why is that the case?
Thank you.


text:
Q: Equivalent of Euler's line in non-euclidean geometry I have very little experience in non-euclidean geometries, but I was wondering if there was some equivalent of the Euler line for some triangle in non-euclidean geometries.
Could we define a "right angle" to mean "an angle that is congruent to its supplementary angle", use geodesics instead of lines, to get the circumcenter, centroid, and orthocenter, and show there exists some geodesic that passes through all three points?
Thanks!


text:
Q: font face not workibg for IE8 ?? getting @font-face encountered unknown error. ? I am using font face to include a customised font named razing. The font is not working in IE8 but works well on IE9+ and other browsers. I checked the console in IE8 browser and i found " @font-face encountered unknown error." I tried using svg and fixes like ?#iefix but it ain't working. Please can u provide a healthy solution to overcome this, Thanks !!

A: Try something like this may helps
@font-face {
    font-family: 'dinpromedium';
    src: url('Fonts/Razing/razing.eot');
    src: url('Fonts/Razing/razing.eot?#iefix') format('embedded-opentype'),
         url('Fonts/Razing/razing.woff') format('woff'),
         url('Fonts/Razing/razing.ttf') format('truetype'),
         url('Fonts/Razing/razing.svg#dinpromedium') format('svg');
    font-weight: normal;
    font-style: normal;

}


text:
Q: What is the difference between Tfidftransformer and Tfidfvectorizer? I am bit confused about the use of Tfidftransformer & Tfidfvectorizer as they both look similar. One uses words to convert matrix (Tfidfvectorizer) and the other used already converted text (using CountVectorizer) to matrix.
Can any one explain the difference between these two?

A: CountVectorizer +  TfidfTransformer  = TfidfVectorizer  this is the simplicity pragmatic way to understand. TfidfVectorizer performs  CountVectorizer and TfidfTransformer in one step.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline

# transformer a
a = Pipeline(steps =[
        ('count_verctorizer',  CountVectorizer()),
        ('tfidf', TfidfTransformer()),
])

# transformer b
b = TfidfVectorizer()

a and b transformers will do the same transformation.
If the preprocess includes of only TFIDF before feeding features to the model, then b will be best choice. But there times where we would like to split the preprocesses. For examples we want to keep only best terms before doing the Inverses Document Frequency. In such times, we would opt for a. Because we can perform CountVectorizer then do additional preprocessing before IDF. E.g.

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import chi2
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline
from sklearn.linear_model import  LogisticRegressionCV

# do counter terms and allow max 150k terms with 1-2 Ngrams
# select the best 10K (reducing the size of our features)
# do the IDF and the pass to our model

hisia = Pipeline(steps =[
        ('count_verctorizer',  CountVectorizer(ngram_range=(1, 2),
                                 max_features=150000,

                                )
        ),
        ('feature_selector', SelectKBest(chi2, k=10000)),
        ('tfidf', TfidfTransformer(sublinear_tf=True)),
        ('logistic_regression', LogisticRegressionCV(cv=5,
                                                    solver='saga',
                                                    scoring='accuracy',
                                                    max_iter=200,
                                                    n_jobs=-1,
                                                    random_state=42,
                                                    verbose=0))
])

In the example, we performed a feature selection of terms before passing them toIDF. This is possible because we can split the TFIDF by first doing CountVectorizer and the TfidfTransformer


text:
Q: error: Too many positional arguments: 0 expected, but 3 found I am getting this error: Too many positional arguments: 0 expected, but 3 found. (extra_positional_arguments_could_be_named at itemBuilder...and can not figure out what could be causing it.
the error is appearing here ->
itemBuilder: (ctx, i) => ProductItem(
          loadedProducts[i].id,
          loadedProducts[i].title,
          loadedProducts[i].imageUrl,
        ),

class ProductListPage extends StatelessWidget {
  ProductListPage({this.context});

  final List<Product> loadedProducts = [
    Product(
      id: 'p1',
      title: "Michael Kora",
      description: 'this is cool',
      price: 699,
      imageUrl:
          "https://n1.sdlcdn.com/imgs/c/9/8/Lambency-Brown-Solid-Casual-Blazers-SDL781227769-1-1b660.jpg",
    ),
    Product(
      id: 'p1',
      title: "Michael Kora",
      description: 'this is cool',
      price: 699,
      imageUrl:
          "https://n1.sdlcdn.com/imgs/c/9/8/Lambency-Brown-Solid-Casual-Blazers-SDL781227769-1-1b660.jpg",
    ),

  ];

  final BuildContext context;

//  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: GridView.builder(
        padding: const EdgeInsets.all(10.0),
        itemCount: loadedProducts.length,
        itemBuilder: (ctx, i) => ProductItem(
          loadedProducts[i].id,
          loadedProducts[i].title,
          loadedProducts[i].imageUrl,
        ),

    );
  }
}

ProductItem is defined as follows:
class ProductItem extends StatelessWidget {
  ProductItem({this.id, this.imageUrl, this.title});

  final String id;
  final String title;
  final String imageUrl;

  @override
  Widget build(BuildContext context) {
    return GridTile(
      child: Image.network(imageUrl),
    );
  }
}

A: Short answer:
ProductItem expects named, not positional arguments. Initialize it like so:
ProductItem(
  id: loadedProducts[i].id,
  title: loadedProducts[i].title,
  imageUrl: loadedProducts[i].imageUrl,
)

Longer answer:
The error informs us:

Too many positional arguments: 0 expected, but 3 found.

Which suggests that ProductItem constructor did not expect positional arguments. It does not know what to do with them. Why? Let's inspect ProductItem class definition:
class ProductItem extends StatelessWidget {
  ProductItem({this.id, this.imageUrl, this.title});
  ...
}

The parameters are enclosed in {}. In Dart, this means that they are optional named parameters. That is, if you decide to pass them in, you must pass them in like so:
ProductItem(id: 'id', imageUrl: 'url', title: 'title')

Note that each argument is preceded by its name - hence it is called a named parameter. In contrast, positional arguments are differentiated only by the position they take in a call to a constructor.
Class definition informs us that constructor of ProductItem should not be called with positional arguments. Instead, named arguments should be used. ProductItem should be constructed this way:
ProductItem(
  id: loadedProducts[i].id,
  title: loadedProducts[i].title,
  imageUrl: loadedProducts[i].imageUrl,
)

To read more about types of parameters, refer to Dart documentation. Alternatively, explore the differences in DartPad.


text:
Q: How does radiation become black-body radiation? Textbooks treat black body radiation as radiation in thermal equilibrium with its environment (more specifically - with a black body): Planck's formula is essentially derived from the partition function.
\begin{align}
\hat{\rho}&=Z^{-1}e^{-\beta H_{ph}},&
 Z&=tr[e^{-\beta H_{ph}}]&
H_{ph}&=\sum_{\mathbf{k},\lambda}\hbar\omega_{\mathbf{k},\lambda} a_{\mathbf{k},\lambda}^\dagger a_{\mathbf{k},\lambda}
\end{align}
This is usually described as a cavity with a small opening, so that enough radiation escapes through the opening to be observable, but too little to significantly distort the thermal equilibrium.
In practice, this is rarely the case - most radiation described as black body radiation is in a strongly non-equilibrium state, being a flux flowing from a hot object (such as a lamp filament or a star) to much colder surroundings (as discussed in the comments to this question and the answers). Yet, such sources are rather well described by Planck's formula.
I see several possible explanations to this:

*

*the light source itself serves as a cavity, with the light making many trips back and forth before escaping (this does not sound very plausible to me)

*the light source is sufficiently thick that photons travelling through it are absorbed and reemitted multiple times before exiting the source, thus being in thermal quasi-equilibrium

*the radiation processes in the source are such that they approximate the Planck's curve: e.g., the thermal electrons in a lamp filament are themselves distributed according to Boltzmann's law; whereas in the case of a star, we have a complex composition of chemical elements, whose spectral lines form a nearly continuous spectrum, and whose excited states are occupied according to the Boltzmann law. While this sounds plausible, it significantly deviates from the reasoning that leads to Planck's formula.

Remarks:

*

*Another inconsistency in the Planck's formula, that is worth noting is that cavity radiation has discrete spectrum.

*A similar question, although less detailed, Relevant question on black-body aspects of solar radiation

*Another fine point that has surfaced in the answers here and those to a related question is whether black body radiation is radiation in thermal equilibrium OR whether it is the radiation emitted by the black body. In the former case, the bodies in which the radiation is in contact do not necessarily have to be black for the radiation to be described by the Planck's formula. In the latter case, the radiation does not have to be in equilibrium (although it would mean that neither is the black body, since it loses the energy via radiating). One could derive Planck's formula in both cases, which correspond to the second and third options proposed above (radiation comes to thermal equilibrium vs. the filament/star emits radiation that is already black.)

*Thread with discussion of how/whether/when discrete atomic spectrum in a gas gives rise to black body radiation: Difference in thermal radiation between condensed matter and gases

A: Of your possibilities it is the second one that means that the blackbody approximation can be used in some cases.
Ideal blackbodies are really hard to produce in nature because of the interface you identify that causes a lack of thermodynamic equilibrium. The best you can do is hope that the region where there is a transition from your "blackbody" to the "outside" is as isothermal as possible.
In practice what matters is how far photons can travel compared to the length scale for the temperature to change at the interface. An object will become more and more like a blackbody if there is a sudden increase in photon mean free path, such that almost all of the photons that escape from the surface were emitted from material at the same temperature.
Prior to that, the mean free path of the photons is small, so that they are indeed absorbed and re-emitted on length scales which are small compared with the length scale on which temperatures vary. In these conditions, the radiation field is close to isotropic and the matter and radiation are close to thermodynamic equilibrium.
The discussion above applies to any candidate source of "blackbody" radiation, not just stars.
Once near to the "surface", if the mean free path lengthens, then there is clearly an anisotropy, because the photons can escape in one direction, but not in the other. There will be a loss of thermodynamic equilibrium and a significant temperature gradient over the regions from which the photons can escape. This is basically what is happening in the photosphere of a star and is why stellar spectra can be very different to the Planck function.
Note: Your option 3 probably isn't going on in most cases. The intrinsic spectrum of a thermal emitter is not the Planck function and in general would contain emission lines, recombination edges etc., even if the population of energy states and particle velocity distribution was characterised by a Maxwell-Boltzmann distribution at some temperature. What one can say is that a smaller amount of material is needed to become opaque to its own radiation if it has strong emission/absorption at all frequencies.
Edit: In response to the commentary on the bounty. There is no doubt at all that thermal emission - the radiation emitted by a small quantity of material in isolation, but characterised by a temperature - is not blackbody radiation. Take the example of material in the interior of a star at say $10^6$ K. We know that this material emits thermal bremsstrahlung and recombination radiation. This is not the Planck function. The intrinsic emission spectrum of such material can be observed by looking at the corona of the Sun and it consists of a continuum with a cut-off that is characteristic of the temperature accompanied by a host of emission lines.
A picture of a piece of the distinctly non-Planckian EUV spectrum attributable to thermal emission from the solar corona, measured by HINODE. (From  http://prc.nao.ac.jp/extra/uos/en/no07/ )

This radiation must be processed in order to become similar to the Planck function and this requires the radiation field to come into equilibrium with the environment. This cannot happen in the solar corona, because it isn't dense enough to be "optically thick". Conversely, in the solar interior the mean free path of photons is a mm, or much less at the wavelength of some recombination line. If you put a piece of material in such an environment at $10^6$ K then the radiation field will be the Planck function. The populations of the various energy states and the transitions between them reach an equilibrium with the radiation and the solution to that equilibrium  is the Planck function.

A: "most radiation described as black body radiation is in strongly non-equilibrium state, being a flux flowing from a hot object (such as a lamp filament or a star) to much colder surroundings"
It doesn't matter if the emitting object is at a higher temperature than the surroundings.  The wavelength of the peak of the black body curve indicates the temperature.
What's required for black body spectrum is that no other radiation is reflected from the body, hence the original name 'black body'.
For a star for example, radiation landing on it is absorbed, any reflection, especially compared to the radiation being emitted due to the temperature, would be negligible.

A: There is no "real" black bodies in the first place, this is a gross simplification for the sake of the formula derivation.
Real bodies are modelled in regard to their thermal radiation by combining the idealized black body with whatever we know about the real body spectrum, using the widespread symmetry in the electromagnetic world, as well as in thermodynamics.
The small opening in the cavity is just a model for the "blackness".
The size of the cavity being finite is not implied in the derivation. On the other hand, a macroscopic cavity of any size is a good approximation when one deals with sub-micrometer waves.
The derivation contains quite a few implicit simplifications, e.g. that the whole body (or at least, surface) has single constant temperature that is never really the case. The real bodies feature a finite internal thermal gradients. That's how we get complex spectra even out of sufficiently black boides (e.g. the Sun).

A: Your third bullet point suggestion is the one closest to the mark I think. Thermal equilibrium is itself a strong statement, which has implications for all the distribution functions etc. concerning all the degrees of freedom of the source. A source of electromagnetic radiation which is not itself bathed in thermal radiation is not in complete thermal equilibrium, but if it is close to equilibrium (e.g. because the emitted flux only changes the internal energy etc. in a quasistatic manner) then the radiation it emits is close to black body radiation, and it must be because the internal configuration of the body is close to the one it would have if there were a complete equilibrium. So all those microscopic processes---molecules, currents, electrons, etc---all settle to whatever it is they have to do to maximise entropy, and, for a body which absorbs in the relevant frequency range, this is the very same state which also emits radiation with the Planck distribution.
Once the radiation is on its way away from a localized source then, as you say, its distribution over direction is no longer the thermal (isotropic) form, but the distribution over frequency is decoupled from that because light does not interact with itself. So that property, at least, remains of black body form.
(Final remark: the discreteness of cavity radiation is to do with the size of the cavity. When we refer to 'black body radiation' we have in mind the thermodynamic limit where the cavity is large compared to the relevant wavelengths.)

A: Stars can be approximated by a black body, because the star's atmosphere is in local thermodynamic equilibrium. This is because the mean free path length of a photon is shorter than the length scale on which the temperature varies.
Using some simplifying assumptions, like an opacity that is independent of the wavelength, one can derive
$$
T^4 = \frac{3}{4}T_\mathrm{eff}^4 \left(\tau_{\perp} + \frac{2}{3} \right)
$$
which means that the effective temperature (roughly $5700\,$K for our sun) is actually found at a depth where the perpendicular opacity is $2/3$, so not at the surface (what ever that might be). This is because photons at that depth have a mean free path length longer than the height below the surface.