text:
Q: It errors when I define variable in function

function addNumbers(x,y) {
    sum = x + y;
    var sum;
    return sum;
}

addNumbers(5,9);
alert(sum);

It says: Uncaught ReferenceError: sum is not defined
When I put "var sum" before the function it works. What is the reason?

A: sum is only defined within the function. To use the function's return value, you do that directly:

function addNumbers(x,y) {
    var sum;
    sum = x + y;
    return sum;
}

alert(addNumbers(5,9));

or

function addNumbers(x,y) {
    var sum;
    sum = x + y;
    return sum;
}

var outerSum = addNumbers(5,9);
alert(outerSum);

Also note that I moved the var sum; to the top of the function. It doesn't really matter with var (I wrote a blog post about that), but it's better form. (It does matter with let and const, which you should probably be using instead of var.)

A: A variable only exists inside of it's scope (rule of thumb: starts at the previous { ends at the matching }), which especially makes sense for functions, as the variables inside the function only exist as long as the function gets executed.
function addNumbers(x,y) { // sum can be used from here on
  var sum = x + y; // always declare variables where you ise them first, otherwide you get funny behaviour
  return sum; // <-
} // you cannot use sum from here on

Now that means that you cannot access sum outside of addNumbers. However as your function returns the value of sum, you can store that in another variable:
 var cool = addNumbers(1, 2);

Now you can use that cool variable and eventually log it.


text:
Q: I want to get all the user tagged posts. How to ignore if the post of same id repeated? I have these 5 tables Users, Tags, Posts, UserTag, PostTag. I want to retrieve all the tagged post of users . I am getting all the post by
In controller
$tags = Auth::user()->tags;

passing to the view.
In view.
@foreach($tags as $tag)
  @foreach($tag->posts as $post)
    {{$post->title}}...
    ....
  @endforeach
@endforeach

And than i realize by doing this, I am getting repeated post. while creating the post, the user add multiple tags, and which is all followed by the authenticated user. for example, what i want to do is.

*

*user1 added the post1 by following test1, test2 tags.

*the next user2 has followed test1 and test2 tags, he will see all the post which he had tagged.

*But if user1 had single post with two tag in point 1, than obviously while getting the post by tags, the one who followed both the tag (test1, test2) will get repeated post i.e post1.

how to ignore the repeated post? I hope what i am concerned is clear?

A: You could store a list of IDs that are already displayed and check against these IDs in the loop. If the ID is in the array then @continue to the next one otherwise display and store the ID. You can read more on loops in Laravel in the documentation
I would try to move this logic out of the view.

A: You can achieve this using different methods.
whereHas relation
Retrieving posts with a whereHas relation instead of first retrieving the tags will result in you only having to loop through one single unique array.
$posts = Posts::whereHas('tags', function (Builder $query) {
    $query->whereIn('id', Auth::user()->tags->pluck('id')->toArray());
});

Now you are only selecting the actual posts without receiving the unnecessary tags first.
You can read about querying relationships in the Laravel documentation.
"Through"-relations
Laravel also provides a convenient (yeah) way to query this by defining an additional relationship of the type has many through.
/**
 * Get all of the tagged posts for this user
 */
public function taggedPosts()
{
   return $this->hasManyThrough('App\Post', 'App\Tag');
}

You must define this in the User model (probably User.php).
Now you can simply loop through Auth::user()->taggedPosts, e.g.
@foreach (Auth::user()->taggedPosts as $post)
{{ $post->title }}
@endforeach

Read more in the Laravel documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSuserdefaults UISwitch I have some problems on save the position of switch,any help?
- (IBAction)SWitchActionAño:(id)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (switchAño.on) {
     [standardDefaults setBool:YES forKey:@"SwitchState"];
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MMM dd,yyyy HH:mm"];
    diadelasemanalabel.text=[formatter stringFromDate:[NSDate date]];
} else {
    [standardDefaults setBool:NO forKey:@"SwitchState"];
    Año.text=@"";
}

}

but i have the problem here! I dont know what is the property!
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
//the error here:property switchAño not found on object....
if ([standardDefaults objectForKey:@"SwitchState"])
    self.switchAño.on =[standardDefaults boolForKey:@"SwitchState"];

A: Try this in viewDidLoad
-(void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *standardDefaults = [[NSUserDefaults standardUserDefaults];
if ([standardDefaults boolForKey:@"SwitchState"] == YES) {
    self.switchAño.on = YES;
}
else {
    self.switchAño.on = NO
}


text:
Q: how to get the coordinate of cursor when setting PS1 variable for command line prompt? I'm using Mac. I want to set PS1 variable to get current time at the end of line in command line prompt. Like this:

or this:

But, unfortunately, I can't get what I want through following configuration:
CYAN="\[$(tput setaf 6)\]"
GREEN="\[$(tput setaf 2)\]"
BLUE="\[$(tput setaf 4)\]"
YELLOW="\[$(tput setaf 3)\]"
export PS1="$GREEN\u$BLUE@$CYAN\h $YELLOW\w\[$(tput cuf $(($(tput cols)-33)))\]$CYAN\[$(date +%H:%M)\]\n\\$ "

It seems that I need to get the current position of cursor and do some computations based on the coordinate of the position, but I don't know how to get it. Is anyone can help?

A: There are a few issues.  This chunk
$(tput cuf $(($(tput cols)-33)))

appears to be what you are asking about.  If you want to position the date at the end of the line, you might try using the hpa (horizontal position absolute) capability, e.g.,
$(tput hpa $(($(tput cols)-5)))

That way, you can move the cursor to a given absolute position on the line rather than moving relative to the current position.
The prompt as given occupies two lines.  If you use the sc and rc capabilities (save/restore cursor) before and after the part where you write the date, you can reduce that to a single line.  That might run into problems with line-editing clearing the date, but it is something to consider.

A: Thanks @Thomas for the good answer, it can truly solve the question I asked as a work-around solution. But it is not perfect, which means it still cannot get the command prompt that I want.
I found that there should be no solution for the prompt I want in bash. But, as @chepner said, there do exist methods to get the prompt in zsh.
How to get the prompt in zsh:
zsh is a very powerful shell which is built-in in mac, but it's a little complicate for the newbie to it. So there is a great tools to solve it named "oh-my-zsh" which make the use of zsh much easier.
"oh-my-zsh" include many themes for zsh. And, fortunately, the prompt I want is very similar with one of them(see the themes here), which named blink. So I just need to modify a little of the theme file located in ~/.oh-my-zsh/themes/blinks.zsh-theme and the change needed to do is:
change the last line of the file from:
RPROMPT='%{%B%F{cyan}%}%!%{%f%k%b%}
to
RPROMPT='%{%B%F{cyan}%}%@%{%f%k%b%}


text:
Q: Pandas dataframe interpolation on two variable for wind analysis with CFD I am working on a wind analysis for a new development. I would be able to predict the air flow pattern in the development for each hour of the year as a function of the wind speed and direction for that particular hour. Of course it would take too much time to run 8760 wind CFD simulations. My approach is to run only 16 simulations (8 wind directions and 2 wind speed) and interpolate the flow distribution from these results.
To give you an idea on how the data look like I have created a simplified case.
X = pd.Series([1,2,3,4,5])
Y = pd.Series([1,2,3,4,5])
Z = pd.Series([1,2,3,4,5])
v1 = pd.Series([2,6,1,7,8])
df1 = pd.DataFrame({'X':X,'Y':Y,'Z':Z,'v':v1})
df1['ws']=3
df1['wd']=180
v2 = pd.Series([3,1,4,2,2])
df2 = pd.DataFrame({'X':X,'Y':Y,'Z':Z,'v':v2})
df2['ws']=3
df2['wd']=0
v3 = pd.Series([2.5,2.3,1.3,7.2,1.4])
df3 = pd.DataFrame({'X':X,'Y':Y,'Z':Z,'v':v3})
df3['ws']=6
df3['wd']=180
v4 = pd.Series([2.4,5.6,6.1,2.3])
df4 = pd.DataFrame({'X':X,'Y':Y,'Z':Z,'v':v4})
df4['ws']=6
df4['wd']=0
df=pd.concat([df1,df2,df3,df4])

Please notice the last two columns contain the meteorological wind speed and direction for that particular simulation. The points (X,Y,Z) can be in the order of 100,000.
Now suppse that I want the flow distribution (X,Y,Z,v) for an intermediate value of wind speed (ws) and wind direction (wd). I would like to be able to aggregate the data and obtain a linear interpolation of the velocity field (v) at each point (X,Y,Z)
To put it in a formula: (X,Y,Z)=f(data,ws,wd)
I guess I need to use the groupby function, but couldn't figure out a way to do it with two variables.
Also, do you think a data panel would be more adequate data structure for this kind of data?

A: If you want to look at distributional features conditional on two variables, you can proceed as
In[10]: df.groupby(['ws', 'wd']).apply(lambda x: x.mean())
Out[10]:
        X  Y  Z     v  ws   wd
ws wd
3  0    3  3  3  2.40   3    0
   180  3  3  3  4.80   3  180
6  0    3  3  3  4.10   6    0
   180  3  3  3  2.94   6  180

With regards to panel data, it generally is rather a question of taste, right? Do you consider X,Y,Z dimensions that you want to generalize over, or not. I typically wouldn't do that, so then you're only left with time, and that gives you a time series rather than a panel.
Moreover, pandas' panel package used to lack many features that exist for standard dataframes. I believe that there has been some recovery lately, but don't know much as I don't really use it. Surely someone else can chip in here.


text:
Q: How can we implement Pagination for Mongodb Collection using mongoTemplate I'm a noob in mongoDb i need to implement Pagination for any specific Collection for instance say
I have a Collection Foo and i have a Fucntion that returns all the records from the Foo collection
public List<Foo> getFoo(){

}

But i need to fetch records from the Foo by implementing pagination how can i achieve this by using mongoTemplate Spring data mongodb?

A: For general pagination you can use the .skip() and .limit() modifiers on the Query object which you can pass in as arguments to your method:
    Query query = new Query();
    query.addCriteria(Criteria.where("a").is("b"));
    query.skip(10);
    query.limit(10);

    List<Foo> results = mongoOperation.find(query, Foo);

With .skip() being how may results to go past and .limit() being the page size to return.
So derive an instance of MongoOperations from MongoTemplate and use a standard .find() operation from there.
Skip and limit is not the most performant option though, try to store last seen values on a natural index like _id where possible and use range queries to avoid "skipping" through 1000's of results.
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").gt(lastSeen));
    query.limit(10);

A: You can provide skip and limit to the query you are using, and this should help doing pagination.
Take a look at method find in MongoTemplate class.
Your method should look like this:
public List<Foo> getFoo(int pageNumber, int pageSize) {...}


text:
Q: Application of Rolle's theorem? Establish existence of $c\in(a,b)$ such that $f(c)+f'(c)=f(c)f'(c)$ Following my question on Meta, I post this as a new question; it was originally asked by Gmgfg, and closed due to the lack of context, background, and shown  effort.

Let $f\colon[a,b]\to\mathbb{R}$ be a function continuous on $[a,b]$ and differentiable on $(a,b)$ with $f(a)=f(b)=0$. Show that there exists $c\in(a,b)$ such that $f'(c)+f(c)=f(c)f'(c)$.

Now, given the assumptions this looks like it should be a straightforward application of Rolle's theorem. However:

*

*as far as I can tell there is no simple auxiliary function $\Phi$ such that $\Phi'= f+f'-f\cdot f'$ to which one could apply Rolle's theorem. (If there is one, I failed to find it.)

*indeed, while the RHS could come from $\left(\frac{f^2}{2}\right)'$; it's mostly the LHS which looks difficult to handle (and there is no clear advantage I can see in introducing an antiderivative $F$ of $f$ to have it be $(F+f)'$).
I verified the statement for some functions I could think of, such as $x\mapsto x(1-x)$ and $x\mapsto \sin \pi x$ on $[a,b]=[0,1]$. So, in that regard, it seems to hold at least against basic sanity checks.
However, what bothers me is the lack of "homogeneity." Usually, in things like that I'm used to saying that "without loss of generality, one can assume $[a,b]=[0,1]$." It does not appear to be the case here: if, given $f$, one defines $g\colon[0,1]\to\mathbb{R}$ by $g(x) = f((b-a)x+a)$, finding $c\in(0,1)$ such that $g'(c)+g(c)=g(c)g'(c)$ does not directly yield $c'$ such that $f'(c')+f(c')=f(c')f'(c')$ (but rather would give $c'$ such that $f'(c')+(b-a)f(c')=f(c')f'(c')$, if I'm not mistaken).

So, in short: is it true? And how to prove or disprove it — I'm at a loss, and embarrassed about it.

A: Let
$$ g(x) = f(x)e^{x-f(x)}. $$
Then $g(a) = g(b) = 0$ since $f(a)=f(b)=0$, so $g'(c) = 0$ for some $c\in(a,b)$. However,
$$ g'(x) = f'(x)e^{x-f(x)} + f(x)e^{x-f(x)}(1-f'(x)) = e^{x-f(x)}(f'(x)+f(x)-f(x)f'(x)),$$
so $g'(c) = 0\implies f'(c)+f(c)-f(c)f'(c) = 0$, i.e. $f'(c)+f(c) = f(c)f'(c)$.


text:
Q: Show that if $f:X \to Y$ is injective and final, then $f$ is initial
Show that if $f:X \to Y$ is injective and final, then $f$ is initial.

So Im having kind of a hard time in incorporating the concepts of initial topology and final topology, and I think this exercise (which Im not being able to solve) is kind of crucial.
To prove that $f$ is initial, I take a topological space $Z$ and a function $h: Z \to X$ and I want to show that $h$ is continuous, if and only if $f \circ h:Z \to Y$ is continuous.
In one direction its easy: If $h$ is continuous, then, since $f$ is final, in particular, $f$ is continuous, and therefore the composition $f \circ h$ is continuous.
However, in the reverse direction, if $f \circ h$ is continuous, im not being able to show that $h$ is continuous:
Since $f$ is final, we have two equivalent conditions that are true:
1) Given $U \subset Y$ such that $f^{-1}(U)$ is open, then $U$ is open
2) For any given topological space $Z$ and for any function $g:Y \to Z$ then $g$ is continuous if and only if $g \circ f$ is continuous.
So I tried to solve the problem using both conditions, and got nowhere.
Can anyone give me a hint/explanation/suggestion?

A: Hint, since $f$ is injective, for each $U \subseteq X$ we have $U = f^{-1}[f[U]]$. Hence if $U$ is open, so is $f[U]$.

A: Suppose $f$ is injective and $f(X,\mathcal{T}_X) \to (Y, \mathcal{T}_Y)$ is final.
Let $\mathcal{T}$ be another topology on $X$ such that $f:(X,\mathcal{T}) \to (Y, \mathcal{T}_Y)$ is continuous.
Let $O$ be in $\mathcal{T}_X$. Then $f^{-1}[f[O]] = O$ (As $f$ is 1-1) and so by $f$ being final, $f[O] \in \mathcal{T}_Y$, and so by continuity of $f$, $O = f^{-1}[f[O]] \in \mathcal{T}$. So $\mathcal{T}_X \subseteq \mathcal{T}$ and so $\mathcal{T}_X$ is the coarsest topology that makes $f$ continuous (as a map to $(Y, \mathcal{T}_Y)$), and so $f$ is initial.


text:
Q: Selecting HTML tag once it has been added to the DOM? I am trying to get chatbox text, from facebook Chat, the text is encapsulated in the span tag
Some Text

However, this span tag doesn't exist in the DOM, when page loads. It is only added, once the user click on the chat bar.
Any ideas, how do I go about selecting this tag?


text:
Q: Will a C# console app wait for all task.runs to finish? I have a console app that runs a whole bunch of things via task.run. I need all of those things to complete before the app terminates. The main line code just runs off the end of main. Will the process shutdown wait for all my task.runs to complete or do I have to wire that up myself. If so does anybody have any suggestions.

A: If you have an array of tasks, you can wait for all of them to complete using the
Task.WaitAll(tasks_array);

A: On a console app, the process shutdown will not wait for your tasks to finish.  It calls ExitProcess, which effectively terminates all threads, including the thread pool that services the Tasks.
As @Ryan Pierce Willems wrote, you need to call Task.WaitAll to make sure you wait for all tasks to complete.


text:
Q: LinkedIn JavaScript SDK - Uncaught TypeError: Cannot read properties of null (reading 'credentials') I am trying to integrate custom linkedin share button using javascript sdk. I am getting error in console when clicking on share button.

I am using code snippet which I found from LinkedIn-Advanced-Share
Here is my code
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <button type="button" id="submit_button" class="userActions">Share</button>
    <script>
    $("#submit_button").click(function organizeinput(){
        var postcontent = new Array();
        postcontent = {"comment": "Testing", "content": {"title": "site tiel","description": "lorem ipsum","submitted-url": "https://my_website.com/","submitted-image_url": "http://my_website.com/wp-content/uploads/2022/06/Default-scaled.jpg"},"visibility": {"code": "anyone"} };
        postcontent = JSON.stringify(postcontent);
        shareContent(postcontent);
    });
    function onLinkedInLoad() {
    IN.Event.on(IN, "auth", organizeinput);
    }
    // Handle the successful return from the API call
    function onSuccess(data) {
        console.log(data);
        alert("Post Successful!");
    }
    // Handle an error response from the API call
    function onError(error) {
        console.log(error);
        alert("Oh no, something went wrong. Check the console for an error log.");
    }
    // Use the API call wrapper to share content on LinkedIn
    function shareContent(pcontent) {
        IN.API.Raw("/people/~/shares?format=json")
        .method("POST")
        .body(pcontent)
        .result(onSuccess)
        .error(onError);
    }
    function organizeinput(){
        var postcontent = new Array();
        postcontent = {"comment": "Testing", "content": {"title": "site tiel","description": "lorem ipsum","submitted-url": "https://my_website.com/","submitted-image_url": "http://my_website.com/wp-content/uploads/2022/06/Default-scaled.jpg"},"visibility": {"code": "anyone"} };
        postcontent = JSON.stringify(postcontent);
        IN.API.Raw("/people/~/shares?format=json")
        .method("POST")
        .body(postcontent)
        .result(onSuccess)
        .error(onError);
    }
    </script>
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">
    api_key: CLIENT_ID_OF_APP
    authorize: true
    scope: w_share
    //onLoad: onLinkedInLoad
    </script>

Can anyone suggest me what I am doing wrong.
Many Thanks.


text:
Q: How can I create a custom screen in the messaging section in Microsoft Teams add-on

I don't want to use bot framework in pop-up or chat window.
Can I use the web API I created myself.
When I do a call, I want the api to request it to list the returned data.
Can I select multiple data listed?

A: From your description you seem to want to create a Teams Message extention, specifically a search extention that will be used from the compose box.
this is indeed powered by a webservice that you will write and host,
however the communication channel between Teams and your webservice must use the bot framework for communication.
Note that you do not need to write a chatbot as such;
I like to think of it as the 'communication channel' between all the Teams clients that have your app installed , and your webservice.
High level steps:

*

*Create and deploy your web service (while developing use a tunneling
service like ngrok to run it locally)

*Register your web service with
the Bot Framework

*Create your Teams app package

*Install your App into Teams

More steps and details in the messaging extensions documentation


text:
Q: How to delete a given node from a linked list using Python I am trying to learn linked list in Using python,
Could someone please guide me how to delete a particular give node from a linked list?
#!/usr/bin/python

class Node(object):
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next
    def __str__(self):
        return str(self.data)

def print_list(node):
    while node:
        print node,
        node = node.next
    print

def delete_node(node, node_to_remove):
    if first_node == None:
        return
    pass

# way of creating linked list
def create_linked_list1(n):
    linked_list = Node(1)
    head = linked_list
    for i in range(1, n):
        head.next = Node(i)
        head = head.next
    return linked_list

node1 = create_linked_list1(10)

print_list(node1)

A: The obvious solution is this:
def delete_by_index(node, index):
    for _ in range(index):
        prev_node, node = node, node.next
    prev_node.next = node.next

However, this won't be able to delete the first node. In order to do that, you need to make it return the new list head, which will normally be the old list head, but will instead be the old second node in the case where you deleted the head. So:
def delete_by_index(node, index):
    if not index:
        return node.next
    head = node
    for _ in range(index):
        prev_node, node = node, node.next
    prev_node.next = node.next
    return head

It should be obvious how to simplify this, and you should do so.
Another option is to factor out the "searching" and "deleting" parts. Write an nth function (this should be easy), then you can do this:
def delete_by_index(node, index):
    if not index:
        return node.next
    prev_node = nth(node, index-1)
    prev_node.next = prev_node.next.next
    return node

If you know about recursive functions, you might also want to figure out how to write either delete_by_index or nth recursively (it's one of the easiest recursive functions to write).
You may also want to trap the error caused by deleting, say, the 15th node of a 10-node list and make it something nicer. Figure out what error you would get in that case (or, if you can't figure it out, just run it and see), then try/except that, and raise an IndexError instead.
While you're at it, you may want to add a delete_by_data(node, data) function and maybe a delete_by_identity(node, child_node) for further practice.

A: Assume the following singly linked list with a pointer, head, to the first node
head ⇢ n0 → n1 →  … → n i - 1 → n i → n i + 1 → … → n N-1 → None
def delete(i):
    if i == 0:                      # there is no prev node, increment head
        head = head.next
    else:
        prev = get_node(i-1)        # find prev node, node[i-1]
        prev.next = prev.next.next  # remove node i

Because this is a singly linked list get_node(i-1) will have to start at head and increment i-1 times to find the node.
NOTE: If this was a doubly linked list, given node[i] you can find node[i-1] using node[i].prev.

A: v-> w-> x->y> z and if we want to delete x so that new Linked List is v -> w-> y-> z and we have access to only x
position of the next node to x i.e. position of the Node Y
next_node = x.next
swapping the Y to X and then deleting Y `x.data = next_node.data
x.next = next_data.next

A: Deletion of a node using python in single linked list.
def delete(self,data):
    if self.head.data==data:

        temp=self.head.next
        del self.head
        self.head=temp

    else:

      p=self.head
      while p.next.data!=data:
          p=p.next

      temp=p.next.next
      del p.next
      p.next=temp

A: Delete by value:
def delete(head, val):

     if head is None:
       return None

     prev = head
     temp = head.next

     while temp is not None:

         if temp.val == val:
             prev.next = temp.next
             return val

         else:
             prev = temp
             temp = temp.next

     return None


text:
Q: Java Applet does not start properly when Max Heap Size is set I have been struggling with developing an applet recently. I have been trying to launch it with JNLP and the "deployJava.js" script. The issue is that this is a memory intensive applet I am developing and will definitely require more than the basic memory allocation that the JVM is usually given.
I attempted to set this using the max-heap-size attribute of the j2se element in the JNLP. This does in fact work, but the problem is that it seems the applet restarts somehow because I get two "java console" windows that open. One receives no output from the applet while the other shows the logging info that I am outputting. Also, the applet does not appear to run. However, if I, without closing the browser, clear the classloader cache and reload the page, the applet works with the correctly adjusted max heap size and everything.
I have no idea what is causing this strange behavior, but I desperately need a solution here. If I do not set a max heap size, the applet behaves fine (except for running out of memory.) Also, if I use the applet tag in the HTML setting the max heap size via <param name="java_arguments" value="-Xmx1g"> it works fine. However, I understand that the applet tag is deprecated and may not work for all browsers so I do not want to stick with it. I hope someone can provide some insight into what I'm missing here.
The bottom line: When I add max-heap-size the applet does not work properly. I need help figuring out why.
Here's the HTML/JavaScript/PHP:
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
    var attributes = {
        code: 'floodsim.SimApplet.class', archive: 'SimApplet.jar',
        width: 500, height: <?php echo "$height"; ?>};
    var parameters = {
        <?php
            echo "imgwidth: $imgwidth, imgheight: $imgheight, imgcount: $imgcount, key: '$key',";
        ?> jnlp_href: 'simApplet.jnlp'};
    deployJava.runApplet(attributes, parameters, '1.6');
</script>

Here's the JNLP (I also used JaNeLa to check it):
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8888/floodsim/simulation/" href="simApplet.jnlp">
    <information>
        <title>Simulation Viewer</title>
        <vendor>Seth Gunnells</vendor>
        <offline-allowed />
    </information>
    <resources>
        <!-- Application Resources -->
        <j2se version="1.6+" max-heap-size="1024m" />
        <jar href="SimApplet.jar" main="true" />
    </resources>
    <applet-desc
        name="Simulation Viewer"
        main-class="edu.tntech.floodsim.SimApplet"
        width="500"
        height="600">
    </applet-desc>
</jnlp>

A: Setting heap size in an applet
Nowhere in the JNLP does it specify max-heap-size.  The example given is:
<j2se version="1.3" initial-heap-size="64m" max-heap-size="128m"/>

Nowhere in the applet element does it specify Java arguments.  The example given is:
<PARAM name="java_arguments" value="-Xmx128m">


text:
Q: Given a date column, get the preceding Sunday for grouping purposes with LINQ Given a table like this:
UserID,DateOfEntry,TimeWorked,Status
user1,2013-04-23,5,Submitted
user1,2013-04-22,7,Submitted
user1,2013-04-29,11,Submitted
user1,2013-04-24,3,Approved
user2,2013-04-22,9,Submitted

How would I go about getting this result set:
UserID,WeekStart,SumTimeWorked
user1, 2013-04-21, 12
user1, 2013-04-28, 11
user2, 2013-04-21, 9

Where the grouping is based on the userID, and the Sunday preceding the date in "DateOfEntry"?
I would prefer Lambda syntax if possible.
EDIT
Here's the working query, based on Thomas' answer. This is the actual query for the actual table I'm querying, so it might not match the above example exactly.
var entries = _db.TimeEntries.GroupBy(g => new {
weekstart = g.DateOfEntry.AddDays(-(int)g.DateOfEntry.DayOfWeek),
userID = g.UserID
})
.OrderBy(c => c.Key.userID)
.Select(c => new {
userID = c.Key.userID,
weekStart = c.Key.weekstart,
Duration = c.Sum(sub => sub.Duration)
});

EDIT 2
The above Query worked in LINQPad and the actual code it is used in wasn't ready to be tested until today - unfortunately in LINQPad I was using LINQ to SQL and in code we're using LINQ to Entities. I receive this error now, if anyone has any ideas...
LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)'
method, and this method cannot be translated into a store expression.

EDIT 3
Ok, I think I've got this one figured out. I had to add two Using statements:
using System.Data.Objects;
using System.Data.Objects.SqlClient;

and then change the query to:
var entries = _db.TimeEntries.GroupBy(g => new {
weekstart = EntityFunctions.AddDays(g.DateOfEntry, -SqlFunctions.DatePart("weekday", g.DateOfEntry)),
userID = g.UserID
})
.OrderBy(c => c.Key.userID)
.Select(c => new {
userID = c.Key.userID,
weekStart = c.Key.weekstart,
Duration = c.Sum(sub => sub.Duration)
});

Sources: Linq to EntityFramework DateTime and LINQ to Entities Join on DateTime.DayOfWeek

A: The linq query is quite simple actually:
var q = from s in submissions
        group s by GetKey(s) into g
        select new
        {
            UserId = g.Key.Key,
            WeekStart = g.Key.Value,
            SumTimeWorked = g.Sum(sub => sub.TimeWorked)
        };

The trick is to define an appropriate grouping method. This one uses KeyValuePairs just because I didn't want to throw in a class definition in this answer:
private KeyValuePair<string, DateTime> GetKey(Submission s)
{
    return new KeyValuePair<string, DateTime>
            (s.UserID, s.DateOfEntry.AddDays(-(int)s.DateOfEntry.DayOfWeek));
}

By the way, after running it I noticed that one of your rows has the wrong value in the SumTimeWorked column. It should be:
user1, 2013-04-21, 15


text:
Q: Desktop won't boot to Windows 10 (including safe mode & recovery media USB) but will boot to Ubuntu My desktop (all AMD parts) fails to boot to Windows 10 normally, safe mode, or using Microsoft's media creation tool on a USB. In all case, the Windows logo will pop up and the loading circle will appear, but within a few seconds the screen will go full black and the computer will restart. When trying to boot normally, it attempts to go to 'Automatic Repair' but fails.
I do have Ubuntu on another partition which I am able to boot to and use normally. I tried tools to repair my Windows from within Ubuntu and I believe Windows is stuck in a 'hibernation' state.
I have tried updating the BIOS to the latest version, as well as changing secure boot, boot mode, and CSM inside the BIOS. I believe my issue was caused by taking out the power cable too early during shutdown.


text:
Q: Why doesn't this error instead: systemctl show 'random text here'.device Sample:
[ctor@dom0 ~]$ cat nonsense
#!/bin/bash

set -vex
systemctl show "sys-devices-virtual-block-dm\x2d0.device"
echo
systemctl show sys-devices-virtual-block-dm\x2d0.device
echo
systemctl show 'random text here'.device
echo

The following output is good when \x2d is not interpreted by the shell (because it's quoted):
[ctor@dom0 ~]$ ./nonsense
systemctl show "sys-devices-virtual-block-dm\x2d0.device"
+ systemctl show 'sys-devices-virtual-block-dm\x2d0.device'
SysFSPath=/sys/devices/virtual/block/dm-0
Id=sys-devices-virtual-block-dm\x5cx2d0.device
Names=sys-devices-virtual-block-dm\x5cx2d0.device
Wants=lvm2-pvscan@253:0.service
Description=/sys/devices/virtual/block/dm-0
LoadState=loaded
ActiveState=active
SubState=plugged
StateChangeTimestamp=Sun 2018-09-09 15:49:14 CEST
StateChangeTimestampMonotonic=10072227
InactiveExitTimestamp=Sun 2018-09-09 15:49:14 CEST
InactiveExitTimestampMonotonic=10072227
ActiveEnterTimestamp=Sun 2018-09-09 15:49:14 CEST
ActiveEnterTimestampMonotonic=10072227
ActiveExitTimestampMonotonic=0
InactiveEnterTimestampMonotonic=0
CanStart=no
CanStop=no
CanReload=no
CanIsolate=no
StopWhenUnneeded=no
RefuseManualStart=no
RefuseManualStop=no
AllowIsolate=no
DefaultDependencies=yes
OnFailureJobMode=replace
IgnoreOnIsolate=yes
NeedDaemonReload=no
JobTimeoutUSec=30s
JobTimeoutAction=none
ConditionResult=no
AssertResult=no
ConditionTimestampMonotonic=0
AssertTimestampMonotonic=0
Transient=no
StartLimitIntervalSec=10000000
StartLimitBurst=5
StartLimitAction=none
echo
+ echo

The following output is bad because the sys-devices-virtual-block-dmx2d0.device doesn't exist (note how the shell removed the \):
systemctl show sys-devices-virtual-block-dm\x2d0.device
+ systemctl show sys-devices-virtual-block-dmx2d0.device
Id=sys-devices-virtual-block-dmx2d0.device
Names=sys-devices-virtual-block-dmx2d0.device
Description=sys-devices-virtual-block-dmx2d0.device
LoadState=loaded
ActiveState=inactive
SubState=dead
StateChangeTimestampMonotonic=0
InactiveExitTimestampMonotonic=0
ActiveEnterTimestampMonotonic=0
ActiveExitTimestampMonotonic=0
InactiveEnterTimestampMonotonic=0
CanStart=no
CanStop=no
CanReload=no
CanIsolate=no
StopWhenUnneeded=no
RefuseManualStart=no
RefuseManualStop=no
AllowIsolate=no
DefaultDependencies=yes
OnFailureJobMode=replace
IgnoreOnIsolate=yes
NeedDaemonReload=no
JobTimeoutUSec=30s
JobTimeoutAction=none
ConditionResult=no
AssertResult=no
ConditionTimestampMonotonic=0
AssertTimestampMonotonic=0
Transient=no
StartLimitIntervalSec=10000000
StartLimitBurst=5
StartLimitAction=none
echo
+ echo

The following output is bad because random text here.device doesn't exist:
systemctl show 'random text here'.device
+ systemctl show 'random text here.device'
Id=random\x5cx20text\x5cx20here.device
Names=random\x5cx20text\x5cx20here.device
Description=random\x5cx20text\x5cx20here.device
LoadState=loaded
ActiveState=inactive
SubState=dead
StateChangeTimestampMonotonic=0
InactiveExitTimestampMonotonic=0
ActiveEnterTimestampMonotonic=0
ActiveExitTimestampMonotonic=0
InactiveEnterTimestampMonotonic=0
CanStart=no
CanStop=no
CanReload=no
CanIsolate=no
StopWhenUnneeded=no
RefuseManualStart=no
RefuseManualStop=no
AllowIsolate=no
DefaultDependencies=yes
OnFailureJobMode=replace
IgnoreOnIsolate=yes
NeedDaemonReload=no
JobTimeoutUSec=30s
JobTimeoutAction=none
ConditionResult=no
AssertResult=no
ConditionTimestampMonotonic=0
AssertTimestampMonotonic=0
Transient=no
StartLimitIntervalSec=10000000
StartLimitBurst=5
StartLimitAction=none
echo
+ echo

So the above two nonexistent .device are showing similar generic output, not really indicating that they don't exist(Substate=dead ?).  It's easy to forget to quote the device name and you get no error, thus thinking that's the real info for the specific .device that you wanted to see.
Systemd version 231 from Fedora 25 used, in dom0 of Qubes OS 4.0:
[ctor@dom0 ~]$ systemctl --version
systemd 231
+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN

Why doesn't systemctl give an error (and exit code != 0) instead?

A: The show command is meant to be parsed by a computer (not an user), use the equivalent (but defined for humans) command status:
$ systemctl status 'random-text-here'.device; echo "Exit Status :$?"
● random-text-here.device
   Loaded: loaded
   Active: inactive (dead)
Exit Status :3


text:
Q: Make a gameObject follow another gameObject's behavior? I am controlling a text GameObject. I am performing operations such as SetActive() and changing the text of the gameObject. Now I am duplicating the same object and I want the duplicated object to follow the behaviors of its main gameObject. That is ObjA is parent and ObjB is a clone. If I change the text UI through code of objA, I want objB to automatically change its component. How do I achieve this behavior?

A: There are multiple ways to do that, but it will always be by code, there is no "authomatism" to do that.
So by code you can make a relation child to parent or parent to child.
One way could be that one:
public class Parent : MonoBehaviour
{
    public Child child = null;

    public void DoSomething()
    {
        this.gameObject.SetActive(true);
        child.DoSomething();
    }
}

public class Child : MonoBehaviour
{
    public void DoSomething()
    {
        this.gameObject.SetActive(true);
    }
}

Another fancy way to do that is using delegates, or Actions:
public class Parent : MonoBehaviour
{
    public Action OnDoSomething = null;
    public Action OnDoSomethingElse = null;

    public void DoSomething()
    {
        this.gameObject.SetActive(false);
        OnDoSomething();
    }

    public void DoSomethingElse()
    {
        this.gameObject.SetActive(true);
        OnDoSomethingElse();
    }
}

public class Child : MonoBehaviour
{
    public Parent parent = null;

    public void Awake()
    {
        parent.OnDoSomething += ChildDoSometing;
        parent.OnDoSomethingElse += ChildDoSometingElse;
    }
    public void OnDestroy()
    {
        parent.OnDoSomething -= ChildDoSometing;
        parent.OnDoSomethingElse -= ChildDoSometingElse;
    }

    public void ChildDoSometing()
    {
        this.gameObject.SetActive(false);
    }

    public void ChildDoSometingElse()
    {
        this.gameObject.SetActive(false);
    }
}

You can be tempted to pass your own method as Action parameter like Action<Action> but remember that child will call parent method, won't operate on his own. So in this case if you do something like:
public class Parent : MonoBehaviour
{
    public Action<Action> OnDoSomething = null;

    [ContextMenu("A")]
    public void DoSomething()
    {
        this.gameObject.SetActive(true);
        OnDoSomething(this.DoSomething);
    }

    public void DoSomethingElse()
    {
        print("Hello");
    }
}

public class Child : MonoBehaviour
{
    public Parent parent = null;

    public void Awake()
    {
        parent.OnDoSomething += RepeatedAction;
    }
    public void OnDestroy()
    {
        parent.OnDoSomething -= RepeatedAction;
    }

    public void RepeatedAction(Action actionToRepeat)
    {
        actionToRepeat?.Invoke();
    }
}

Will result on StackOverflow exception, cause child will call parent, who calls child, who calls again parent...you can see the problem.
Anyway would be nice to declare an abstract base class that have all the methods, and let both classes inherit from that class, and implement those methods.


text:
Q: git clone issue: repo too large? (50m) Been having an issue with being unable to clone a git repo. It starts to run and then cancels half way through.
My current git repo size is 53.7 MB
Git version is 1.7.12.4 on server and on my remote.
Error below:
MacBook-Pro:htdocs macbook$ git clone myrepo@mysite.com:~/opt/git/myrepo.git
Cloning into 'myrepo'...
zcardepo@zcardepot.com's password:
remote: Counting objects: 8888, done.
remote: Compressing objects: 100% (7185/7185), done.
Write failed: Broken pipe267/8888), 1.03 MiB | 1001.00 KiB/s
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

I created a fresh new repo, clones just fine. Once I add my site files to it and push them to the remote though. I can no longer clone from it. But I can pull from it just fine.
I added this with no luck:
[core]
    compression = -1
[pack]
    windowMemory = 10m
    packSizeLimit = 20m

I tried upping these both to way higher values. No luck
I also tried running git gc --aggressive and git gc --prune on the remote repo.
I've seen this post, but mine is no where as large (1g+)
Also see a people having issues with the git versions not matching, but this isn't the case ether.

A: I think the problem you are having is your clone breaks off in the middle every time.
So, instead of cloning a repo again and again from scratch everytime, I would suggest you instead do a fetch on a freshly created repo.
Basically, initialize an empty repository
cd repo_name && git init

Add the original repo as a remote in this repo
git remote add origin url/to/repo

And now do a git fetch.
This way, even if your clone breaks in the middle, fetch will take care to bring in unfetched objects only in next run.

Alternatively, you can check the solutions here and here.

A: Also try increasing your postBuffer
git config --global http.postBuffer 1048576000


text:
Q: When a point particle moves with a certain vector instantenous velocity along a curve, does it have a vector instanteneous acceleration? I'm sorry I'm just getting started with Physics, I'm not an expert. I've been stuck with this question.
When a point particle moves with a certain vector instantenous velocity along a curve, does it have a vector instanteneous acceleration? My professor said that it depends on the vector instanteneous acceleration. Though I don't understand why.
When I look at the graph I always see that the acceleration is the slope of the graph. Any hints?

A: Yes, if a particle is changing direction it is accelerating. Example is a weight on a string that is being spun in a circle at a constant rate , there is a force (of the string) which is constantly accelerating the weight towards the centre and changing the weights direction of travel (velocity includes direction).

A: When the particle moves along a "curve" and not a straight line then it does have an acceleration.
For a particle moving along a straight line, the magnitude of it's instantaneous velocity (or the speed) should change for it to have some acceleration.

A: Yes, a particle always has an acceleration (but this may be zero). Looking at a graph of position probably won't be very useful to gain an intuitive understanding of acceleration, but a graph of velocity will be.
First let's lay out the mathematics:
The time-dependent position of a particle in n-dimensions can be written as
$$\mathbf{x}(t) =
\begin{pmatrix}
x_1(t) \\
x_2(t) \\
\vdots \\
x_n(t)
\end{pmatrix}
$$
The velocity and acceleration of the particle are simply defined as the derivatives of this vector with respect to time, i.e.
$$\mathbf{v}(t) = \frac{\partial}{\partial t}\mathbf{x}(t) =
\begin{pmatrix}
\frac{\partial x_1(t)}{\partial t} \\
\frac{\partial x_2(t)}{\partial t}  \\
\vdots \\
\frac{\partial x_2(t)}{\partial t}
\end{pmatrix}\\
\mathbf{a}(t) = \frac{\partial}{\partial t}\mathbf{v}(t)= \frac{\partial^2}{\partial t^2}\mathbf{x}(t)=
\begin{pmatrix}
\frac{\partial^2 x_1(t)}{\partial t^2} \\
\frac{\partial^2 x_2(t)}{\partial t^2}  \\
\vdots \\
\frac{\partial^2 x_2(t)}{\partial t^2}
\end{pmatrix}
$$
in any (non-contrived) problem encountered in physics, both of these will exist. These are the definitions of velocity and acceleration, and as long as the derivatives are well-defined, these will exist.
The velocity is always tangent to the trajectory, and the acceleration is always tangent to the velocity. This does not imply that the acceleration is tangent to the trajectory.
Taking for example a 2D problem of a particle constrained to a circle, we see that the acceleration always points to the center of the circle, but the trajectory lies along the circle. Thus the acceleration is not tangent to the trajectory (but the velocity is!).


text:
Q: Rspec test failing with capybara even though save_and_open_page is correct Here's the relevant test:
#spec/requests/posts_spec.rb
require 'spec_helper'
describe "Posts pages" do
  subject { page }
  describe "edit" do
    let (:post) { Post.order('release_date desc').first }
    before do
        visit posts_path
        within(:css, "div#post_#{post.id}") { click_link "Edit" }
        save_and_open_page # has correct title
    end

    it { should have_selector('title', "Editing #{post.title}" ) } # fails
  end
end

The failure message:
1) Posts pages edit
 Failure/Error: it { should have_selector('title', "Editing #{post.title}" ) }
   expected css "Editing unde inventore illo accusamus" to return something

However, when the page opens in my browser via save_and_open_page, the title is correct and it has opened the correct edit page.  I double-checked for any typos in the template vs. the test, and it matches up.
So what am I missing?

A: Your syntax for have_selector is wrong. Try this:
it { should have_selector('title', :text => "Editing #{post.title}" ) }


text:
Q: Comma use with "Oh" phrases The most famous quotation, one I often use for humorous effect, is "Oh joy! Rapture!"
"Oh no!" is common. "Oh wow!" "Oh boy," appear less so in my writings. "Oh woe is me," well, never. As I write this, only the last phrase was underlined by my Grammarly app as requiring the comma. But, Grammarly is not always correct.
What can I do to remember the rules?
I'm hoping for an inclusive list because although I read the rules somewhere not too long ago, they were too complicated for my feeble brain.

A: "Oh no!", "Oh wow!", "Oh boy!" and a few others are idiomatic exclamations.  And "Oh" is an exclamation by itself.  When an exclamation precedes a sentence such as "I forgot to turn off the water" or "woe is me" or "that is fantastic" then it is generally separated by a comma.

A: A comma is traditionally used at the end of direct speech where a full stop (or period) would have been used if the end of the quotation had coincided with the end of the written sentence (i.e. where "he said" etc. is omitted).
If the direct speech ends with an exclamation-mark or a question-mark, these punctuation-marks are retained even if the quotation is followed by "he said" etc.  The reason for this difference is that exclamation-marks and question-marks do not necessarily mark the end of a sentence.  That is why the word "he" does not need to be capitalized in the following sentence: "Ouch!" he cried.
An exclamation-mark is traditionally used to mark any exclamation, which would usually include expressions such as "Oh" or "Wow," but punctuation is applied less rigidly nowadays so that it is often a matter of style whether or not an author chooses to use an exclamation-mark after any exclamation.


text:
Q: How to filter a conditional statement with a conditional condition in postgresql The idea is to filter the classes_offered that are equal to 1
    SELECT
        to_char("startDate", 'HH24:MI') as Hour,
        dow as "Weekdays",
        fitness_experience as Class_Type,
        name as Training_Ground,
        oic_name as OIC,
        count(*) AS total_bookings,
        count(distinct "startDate") AS classes_offered,
        (count(*)::numeric / count(distinct "startDate")::numeric) AS avg_bookings
    FROM (
        SELECT start_date as "startDate",
               name, oic_name, dow, fitness_experience
        FROM clean.dim_bookings
        WHERE 1=1
          and status = 'ACTIVE'
          and fitness_experience = 'OPEN'
         [[AND venue_name={{Units}}]]
         [[AND name={{training_ground}}]]
         [[AND start_date >= {{from_date}}]]
         [[AND start_date <= {{to_date}}]]
         [[AND oic_name={{OIC}}]]
         [[AND {{workout_category}}]]
       ) t
    GROUP BY
        1, 2, 3, name, oic_name
    ORDER BY
        1, 2, 3, name, oic_name

A: You're almost there. Add a HAVING clause to filter by an aggregation result.
SELECT
    to_char("startDate", 'HH24:MI') as Hour,
    dow as "Weekdays",
    fitness_experience as Class_Type,
    name as Training_Ground,
    oic_name as OIC,
    count(*) AS total_bookings,
    count(distinct "startDate") AS classes_offered,
    (count(*)::numeric / count(distinct "startDate")::numeric) AS avg_bookings
FROM (
    SELECT start_date as "startDate", name, oic_name, dow, fitness_experience
    FROM clean.dim_bookings
    WHERE 1=1
    and status = 'ACTIVE'
    and fitness_experience = 'OPEN' [[AND venue_name={{Units}}]] [[AND name={{training_ground}}]] [[AND start_date >= {{from_date}}]] [[AND start_date <= {{to_date}}]] [[AND oic_name={{OIC}}]] [[AND {{workout_category}}]]) t
GROUP BY
    1, 2, 3, name, oic_name
HAVING
    count(distinct "startDate") = 1
ORDER BY
    1, 2, 3, name, oic_name


text:
Q: Does CAS conflict with volatile Now that cas has volatile read and write semantics, why should volatile be combined to implement synchronized code blocks?
For example, the shared variables of all classes under the java.util.concurrent.atomic package will be modified with volatile.
public class AtomicInteger extends Number implements java.io.Serializable { private volatile int value; }


text:
Q: How to change the text on active state jQuery I've this lil piece of code, I have done what I wanted, just one thing is that am not able to chane the word when the div is expanded, I want to make text Less - and when is it not expanded More +
Fiddle
$(document).ready(function () {
     var visible=true;
    $("#more_details").on('click', function() {
    $('.more_details').animate({width: visible ? 300 : 0}, "slow");
         visible=!visible;
     });
});

A: $(document).ready(function () {
  var visible=true;
  $("#more_details").on('click', function() {
    $('.more_details').animate({width: visible ? 300 : 0}, "slow");
    visible=!visible;
    $(this).text(visible ? 'More +' : 'Less -');
  });
});

DEMO


text:
Q: Render partial when a new object is created via API I want to render a partial with the data that were created via the API:
1 - A POST is send to the API
2 - The API creates the object in the database
3 - A partial is rendered to specific user with the object data
I tryied use Action Cable, But nothing happens in the browser when i create a call via Rails Console.
See my code
models/call.rb
class Call < ApplicationRecord
    after_create_commit { CallBroadcastJob.perform_later self }
end

controllers/seller_controller.rb
class SellerController < ApplicationController
  def index
    @calls = Call.where(status: true).last
  end
end

jobs/call_broadcast.rb
class CallBroadcastJob < ApplicationJob
  queue_as :default

  def perform(call)
    ActionCable.server.broadcast 'new_call_channel', call: render_call(call)
  end

  private
  def render_call(call)
    ApplicationController.render(partial: 'seller/call', locals: {call: call})
  end
end

channels/new_call_channel.rb
class NewCallChannel < ApplicationCable::Channel
  def subscribed
    stream_from "new_call_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

javascrips/channels/new_call.coffee
App.new_call = App.cable.subscriptions.create "NewCallChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    $('#call_partial').html data

views/seller/index.html.erb

<%= render partial: 'seller/call', locals: {call: @calls} if @calls.present? %>

views/seller/_call.html.erb

Telefone: <%= call.from_number %>

Campanha: ---

Agente: <%= call.agent %>

RAILS CONSOLE
2.4.2 :001 > Call.create!(call_id: "321", from_number: "(21) 9999-9999", agent: 001)
   (0.3ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "calls" ("call_id", "from_number", "agent", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["call_id", "321"], ["from_number", "(21) 9999-9999"], ["agent", "1"], ["created_at", "2018-04-18 21:12:18.010119"], ["updated_at", "2018-04-18 21:12:18.010119"]]
   (13.2ms)  COMMIT
Enqueued CallBroadcastJob (Job ID: 9049b86f-1a91-4e3a-a46a-e3ba55ccb6b8) to Async(default) with arguments: #<GlobalID:0x00007f622c37fa38 @uri=#<URI::GID gid://inteligente/Call/10>>
 => #<Call id: 10, call_id: "321", from_number: "(21) 9999-9999", agent: "1", created_at: "2018-04-18 21:12:18", updated_at: "2018-04-18 21:12:18", status: true>
2.4.2 :002 >   Call Load (0.5ms)  SELECT  "calls".* FROM "calls" WHERE "calls"."id" = $1 LIMIT $2  [["id", 10], ["LIMIT", 1]]
Performing CallBroadcastJob from Async(default) with arguments: #<GlobalID:0x00007f622c1f4240 @uri=#<URI::GID gid://inteligente/Call/10>>
  Rendered seller/_call.html.erb (2.5ms)
[ActionCable] Broadcasting to new_call_channel: {:call=>"
\n\t
\n\t\t
Telefone: (21) 9999-9999
\n\t\t
Campanha: ---
\n\t\t
Agente: 001
\n\t
\n"}
Performed CallBroadcastJob from Async(default) in 115.72ms

A: In your controller you can just render a view partial back, like:
render layout: false, template: "path/to/view/partial", locals: {var_used_in_partial: response_data, some_other_var: other_var_value, some_arbitrary_string: "hello world"}

So, if you made an ajax call to that API endpoint and wanted to get back a response that was a template filled out with all the data, this would let you do it. Then, you just append that response to the DOM wherever you want it.
Did I understand your question correctly?


text:
Q: "element does not exist in cache" error upon radio button select using mechanize::phantomjs I'm trying to automate a webpage that includes a lot of javascript functions in Perl. So far I've been successful by using the headless mechanize::phantomjs toolkit, but I can't get past this, probably, trivial error. I see a page with a menu of radio buttons and when I try to select any one of those using
$mech->set_fields('booking_choice' => "$i");

where $i is my iterator and 'booking_choice' is the name of the button, I get the error listed below. This is how it looks on the page:

      <input type="radio" name="booking_choice" value="1">

      Friday, January 16, 2015

      08:45 a.m.

      45 minutes

There are two other radio buttons with values 0 and 2, and that's what the iterator is for. However, within any one iteration upon selection of the button I get the following error:
Error while executing command: An element command failed because the referenced element is no longer attached to the DOM.: {"errorMessage":"Element does not exist in cache","request".....

I can locate the button on the page fine by using xpath and it always returns success:
if ($mech->xpath('//*[@name="booking_choice"]', one => 1)) {
      say "Success";
}

What I don't understand is:

*

*Why the element is no longer accessible even when I can see it listed on the html source page.

*How can I keep the Element intact so that it is available for selection.

I'm very new to webscraping, web automation and I found some similar question to mine on this forum but they are either written for ruby or use some other webdriver than phantomjs. I don't know how to implement any of the given solutions using mechanize::phantomjs. I'll appreciate any help I can get. Thanks!
I've placed the source HTML file here: http://www.datafilehost.com/d/948c5371

A: mechanize requires you to select the form before you can set the form fields. This can be done with a variety of functions such as

*

*$mech->form_name( $name [, %options] )

*$mech->form_id( $id [, %options] )

*$mech->form_number( $number [, %options] )

*$mech->form_with_fields( [$options], @fields )
Taken from here.

If this doesn't work, you can always run some custom code in the page context to change the fields. For radio boxes this would look like this:
$mech->eval(<<'JS', $i);
    document.querySelectorAll("[name='formName'] [name='radioButtonName']")[arguments[0]].checked = true;
JS

Although, this only changes the property of the radio button and in most cases this is enough. But sometimes there are event handlers on the DOM elements which will not be triggered in this case.
An alternative would be to actually use $mech->click( $name [,$x ,$y] ) to click on the radio button and trigger all necessary events.


text:
Q: Return exclusive elements from two lists that comes more than twice using linq I have two lists:
    int[] List1 = { 10, 10029, 30, 30, 10030 };
    int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };

and the following statement,
var NewList = List1.Except(List2);

returns
10
30

but I want the output to include the exclusive elements that have been duplicated. So,
10
30
30

A: LINQ with the semantics you're looking for:
var newList = List1.Where(x => !List2.Contains(x));

Note that this is quadratic in the size of the lists. If the lists are large then this might take a long time. To alleviate that, you can turn the other list to a set first, for fast lookup:
var list2AsSet = List2.ToHashSet();
var newList = List1.Where(x => !list2AsSet.Contains(x));

A: Use the Contains method to determine if the element exist in the second list
int[] List1 = { 10, 10029, 30, 30, 10030 };
int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };
var exclusive = List1.Where(x => !List2.Contains(x));

foreach (var el in exclusive){
    Console.WriteLine(el);
}

More about Contains - https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=net-6.0


text:
Q: Match the Level of Variables from Two Dataset I am working on a forecasting model and need to match the levels of each variable from training data and testing data using the code shown as below:
levels(test$MSSubClass) <- levels(train$MSSubClass)

There are 87 variables in total. Instead of doing it one by one. I am looking for an approach to match them all at one time. Currently, my code is like this:
levels(test$MSSubClass) <- levels(train$MSSubClass)
levels(test$MSZoning) <- levels(train$MSZoning)
levels(test$LotFrontage) <- levels(train$LotFrontage)
levels(test$LotArea) <- levels(train$LotArea)
levels(test$Street) <- levels(train$Street)
....

A: If the levels in test are a subset of the levels in train:
# Get the column names that are factors
factor_names <- names(train)[sapply(train, class) == "factor"]

# Set the factor levels in test to be same as train
for (name in factor_names) {levels(test[,name]) <- levels(train[,name])}


text:
Q: Tpm2 not listing sha1 PCR banks My hp-15 notebook laptop has Ubuntu 20.04 and I installed tpm2-tools and  when I list tpm2_pcrread it does not show sha1 PCR banks only sha256 is listing kindly help on this

A: Run the following command to check which algorithms are supported on your device:
tpm2_getcap pcrs

Maybe your version takes sha256 as default, try running
tpm2_pcrread sha1

to explicitly get the sha1 values.
One more thing, this question is not directly related to programming, superuser.com is better suited for such questions.


text:
Q: Cast web server object to other (identical) web server object I have two web services referenced in my project. One is called EmailService and the other TicketService.
Both have a property called Email. And I have to do the following in my code now:
var mail = new EmailService.Email();
mail.from = "something";
mail.to = "someone";
mail.subject = "subject";
mailService.Save(mail);

ticketService.Send(mail);

The problem is that the TicketService.Send() expects an Email object from the TicketService namespace. So it fails at that point.
Casting also won't work in this case:
ticketService.Send( (TicketService.Email)mail );

That gives me the error that it is unable to cast expression from EmailService.Email to TicketService.Email.
I know I can use something like AutoMapper and simply map it from one object to the other. But I rather don't add another dependency to the solution.
Maybe it's not even necessary to add something like AutoMapper, since both Email objects are identical. So perhaps there is an easy way to do this?
In any way, how can I solve this issue?

A: Look, if you want to cast stuff to other stuff willy nilly or go duck-typing everywhere, then you are using the wrong language.  C# is a statically typed language (with a little dynamic mixed in now) and it will not let you cast any old type to any other type.
Automapper is a solution, but a bit of overkill, yes.  You can, however, do the same thing it would--create a method that will convert an instance of one to an instance of the other.  It will seriously take you less time than you spent writing this question.
Alternatively, if you can, refactor the code to use the same instance of an Email object.  But either way, seriously, just dooo eeet.


text:
Q: Protecting drop down fields values from being altered Am using drop down field to show user country in the front end,and i want to know if is possible for hackers or user to change or alter the values i set in the drop down list?
Secondly, is their any known tools or script that a user can use to edit a read only fields?

A: It's actually pretty simple to change values using your chrome developer tools. You can just right click --> inspect --> change any value you want. You can't stop people editing what they get to see.
So this means that if you send a dropdown with items:

*

*Belgium

*France

*Netherlands

It is very easy for a user to change those values to 3 different countries and submit these values. There is nothing you can do about that.
What you should do is check the submitted values. Your server can 'remember' the values that he has send and should check if the submitted values are one of the send values. If not you know that the client has changed his values.


text:
Q: Markov Chains- Show state is recurrent Q's: I suspect this is true: if two states in a markov chain communicate and one is recurrent, then the other is recurrent.
My approach is, lets say i and j are two states that communicate and as i is recurrent, this means you are guaranteed to revisit i everytime you reach it, so you have infinite points in discrete time which you reach i and as i communicates with j, this implies j is recurrent as we are always guaranteed to revisit j after reaching it.
My problem with this proof is it involves alot of words, so an alt.proof would be great. Thanks

A: You are decribing what's called a Regular Markov Chain. Every location has visitors and from every location you can visit another location. No visitor can leave the Chain and no outsider cen enter. This means that the transition matrix (there are different names for such a matrix) has columns that add up to 1. The fact is that the dominant eigenvalue of such a matrix is 1. That ought to be the first part of your proof. Then any particular distribution vector can be expressed as a Linear Combination of the eigenvectors of the matrix. In the long run (i.e. taking high powers of the matrix), Linear Algebra slhows us that the dominant eigenvalue prevails as the others "die out" for high powers. Thus, the entries of the corresponding eigenvector gives the ratio of the equilibrium. This is the proof in "words"


text:
Q: aws s3 bucket policy without public access I am hosting few api containers in aws ecs. one of the api (api.example.com) needs to upload images to the aws s3 bucket. Now the developers are using swagger after authenticating it via some token (not sure what they are exactly doing)
I have created a bucket policy but image uploading only works when the "Principal" is set to "*" .     when we use " * " at "Principal" the bucket is open to any aws account and the aws is showing a warning message.
is there any way we can make the bucket more secure? at the same time it is able to upload images via api.example.com through browser.
My bucket policy is pasted below
"Version": "2012-10-17",
"Id": "xxxxx",
"Statement": [
    {
        "Sid": "xxxxx",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "s3:DeleteObject",
            "s3:GetObject",
            "s3:PutObject"
        ],
        "Resource": "arn:aws:s3:::mys3bucket/*"
    }
]


text:
Q: Count number of duplicates in a data.table by two columns in R I'm trying to count the number of duplicates of each unique string value in the column z by two other columns (x,y) in a data.table (using the data.table package or something equivalently fast, I have millions of actual rows to run this on):
I have data like this:
dt <- data.table(x=c("aa","aa","aa","bb","cc","cc","cc","cc","cc","cc"), y=c(2,2,1,1,1,1,2,2,2,3),z=c("d","d","a","d","a","a","e","e","b", "a"))

     x y z
 1: aa 2 d
 2: aa 2 d
 3: aa 1 a
 4: bb 1 d
 5: cc 1 a
 6: cc 1 a
 7: cc 2 e
 8: cc 2 e
 9: cc 2 b
10: cc 3 a

I'd like to have it like this:
dt.desired <- data.table(x=c("aa","aa", "bb","cc", "cc","cc", "cc"), y=c(1,2,1,1,2,2,3), z=c("a","d","d","a","b","e","a"), n=c(1,2,1,2,1,2,1))

    x y z n
1: aa 1 a 1
2: aa 2 d 2
3: bb 1 d 1
4: cc 1 a 2
5: cc 2 b 1
6: cc 2 e 2
7: cc 3 a 1

A: You can do this with dplyr and magrittr in tidyverse:
library(data.table)
library(tidyverse)

> dt %>% count(x,y,z)
# A tibble: 7 x 4
  x         y z         n
  <chr> <dbl> <chr> <int>
1 aa       1. a         1
2 aa       2. d         2
3 bb       1. d         1
4 cc       1. a         2
5 cc       2. b         1
6 cc       2. e         2
7 cc       3. a         1

If you want to create a new data frame, just assign to a variable like
z <- dt %>% count(x,y,z)


text:
Q: Why am i getting an ActiveRecord::AssociationTypeMismatch error while trying to create a form I'm building a pageantry application form
here are the neccessary codes
the new form

<%= link_to "Home", { controller: "welcome" } %>

<%= link_to "About us", about_index_path %>

          <button id="showLeftPush"></button>

        <%= javascript_include_tag 'classie', 'data-turbolinks-track' => true %>

MISS CRYSTAL NIGERIA

    <%= stylesheet_link_tag  'popuo-box', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'jquery.magnific-popup', 'data-turbolinks-track' => true %>

        <input type="submit" value="">
        <input type="text" value="Search.." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search..';}">

Education

 Miss Crystal Nigeria / Registration Form

  <%= form_for @form, html: { multipart: true } do |f| %>

  <% if @form and @form.errors and @form.errors.count > 0 %>

     ×
     <%= pluralize(@form.errors.count,"error") %> found. Please fill the Important field denoted by the asteriks (*)

   <% end %>

Contact Information

            First Name*

              <%= f.text_field :first_name, :class => "form-control", :placeholder => "First Name" %>

            Last Name*

              <%= f.text_field :last_name, :class => "form-control", :placeholder => "Last Name" %>

            Other Names

              <%= f.text_field :other_names, :class => "form-control", :placeholder => "Other Names" %>

            Email*

              <%= f.text_field :email_address, :class => "form-control", :placeholder => "Email Address" %>

            Backup Email*

              <%= f.text_field :backup_email_address, :class => "form-control", :placeholder => "Backup Email Address" %>

            Address(1)*

              <%= f.text_area :first_street_address, :class => "form-control", :placeholder => "First Address" %>

            Address(2)

              <%= f.text_area :second_street_address, :class => "form-control", :placeholder => "Second Address" %>

            Address(3)

              <%= f.text_area :third_street_address, :class => "form-control", :placeholder => "Third Address" %>

            City/State/Island*

              <%= f.text_field :city, :class => "form-control", :placeholder => "City/State/Island of Residence" %>

            Zip/Postal Code*

              <%= f.text_field :postal_code, :class => "form-control", :placeholder => "Zip Code / Postal Code" %>

            Country*

              <%= f.country_select :country, priority_countries: ["NG"], :class => "form-control country" %>

            Settlement Area

              <%= f.text_field :settlement, :class => "form-control", :placeholder => "Settlement Area of Residence" %>

            Phone(Home)*

              <%= f.text_field :phone_home, :class => "form-control", :placeholder => "Home Line" %>

            Phone(Mobile)*

              <%= f.text_field :phone_mobile, :class => "form-control", :placeholder => "Mobile Line" %>

            Phone(Work)

              <%= f.text_field :phone_work, :class => "form-control", :placeholder => "Work Line" %>

Photos of You

        Photo (1)

          <%= f.file_field :image, :class => "submit" %>

        Photo (2)

          <%= f.file_field :imaget, :class => "submit" %>

Personal Background and vital Statistics

        How old are you?*

          <%= f.number_field :age, :class => "form-control", :placeholder => "Your Age" %>

        Date of birth?*

          <%= f.date_select :dob, :class => "form-control", :placeholder => "" %>

        Place of birth?*

          <%= f.text_field :place_of_birth, :class => "form-control", :placeholder => "Where were you born?" %>

        State*

          <%= f.text_field :stateoo, :class => "form-control", :placeholder => "What's your state of origin?" %>

        L. G. A.*

          <%= f.text_field :localgovt, :class => "form-control", :placeholder => "What's your Local Government Area" %>

        Height(ft/")*

          <%= f.number_field :height, :class => "form-control", :placeholder => "to the nearest whole" %>

        Weight(lbs)*

          <%= f.number_field :weight, :class => "form-control", :placeholder => "What do you weigh?" %>

        Swimsuit Size*

          <%= f.text_field :swimsuit_size, :class => "form-control", :placeholder => "What's your Swim suit size?" %>

        Dress size*

          <%= f.text_field :dress_size, :class => "form-control", :placeholder => "What's your Dress Size?" %>

        Shoe Size*

          <%= f.text_field :shoe_size, :class => "form-control", :placeholder => "What's your Shoe Size?" %>

        Employment/School*

          <%= f.text_field :employment_school, :class => "form-control", :placeholder => "What's Your Place of Employment or School You Attend?" %>

        Degrees*

          <%= f.text_field :degrees, :class => "form-control", :placeholder => "Please list Any Degrees Attained, Scholarships and or Achievements" %>

        Other Awards*

          <%= f.text_field :other_awards, :class => "form-control", :placeholder => "List Any Other Awards or Achievements(NON-SCHOLASTIC)" %>

        Family Bio*

          <%= f.text_field :family_bio, :class => "form-control", :placeholder => "Tell Us of Any Interesting Fact About Your Family or Their Achievements" %>

More About You

        Facebook Url*

          <%= f.text_field :facebook_url, :class => "form-control", :placeholder => "Are You On Facebook? If so, please provide the URL's(links)" %>

        Twitter Url*

          <%= f.text_field :twitter_url, :class => "form-control", :placeholder => "Do You Have a Twitter Account? If so, please provide the URL's(links) to your page" %>

        Favourite Color*

          <%= f.text_field :fav_color, :class => "form-control", :placeholder => "What's your Favourite Color?" %>

        Favourite Food*

          <%= f.text_field :fav_food, :class => "form-control", :placeholder => "What's your Favourite Food?" %>

        Favourite Sport*

          <%= f.text_field :fav_sport, :class => "form-control", :placeholder => "What's your Favourite Sport?" %>

        Have you always lived in Nigeria*

          <%= f.check_box :always_naija %>

        If No

          <%= f.text_field :nalways_naija, :class => "form-control", :placeholder => "Where else have you lived?" %>

Personal Outlook

        Hobbies*

          <%= f.text_field :hoobies, :class => "form-control", :placeholder => "What are your Hobbies?" %>

        Sports*

          <%= f.text_field :sports, :class => "form-control", :placeholder => "What Sports or Activities Do you Participate in?" %>

        Life Ambition*

          <%= f.text_area :life_ambition, :class => "form-control", :placeholder => "What's your Life Ambition?" %>

        Talent

          <%= f.text_field :performable_talent, :class => "form-control", :placeholder => "Do you Have any Performable Talent? If yes, List them" %>

        Training

          <%= f.text_area :special_training, :class => "form-control", :placeholder => "Do you have any special training in Music, Dance, Arts, Etc?" %>

        Languages*

          <%= f.text_area :languages, :class => "form-control", :placeholder => "Please list the languages you speak" %>

        Unusual Thing*

          <%= f.text_area :most_unusual_thing, :class => "form-control", :placeholder => "Whats's the most thing you have ever done?" %>

        Proud Moment*

          <%= f.text_field :most_proud_moment, :class => "form-control", :placeholder => "Briefly Describe the moment in your life you are most proud of" %>

        Countries Visited

          <%= f.text_field :countries_visited, :class => "form-control", :placeholder => "List all the countries you have travelled to" %>

Personal Statement

        Self Bio*

          <%= f.text_area :intresting_selfbio, :class => "form-control", :placeholder => "Tell us something interesting About you." %>

Verification

        Verify True Information*

          <%= f.check_box :true_information %>

        Verify True Age*

          <%= f.check_box :true_age %>

        Terms and Condition*

          <%= f.check_box :true_tandc %>

        Date*

          <%= f.date_select :date %>

        Who referred you?*

          <%= f.collection_select :referee_id, @referee, :id, :name, :class => "form-control", :prompt => "Who referred you?" %>

          <%= f.text_field :referee, :class => "form-control", :placeholder => "Someone else? What's his/her name" %>

        Bank Teller Number*

          <%= f.text_field :bank_teller_number, :class => "form-control", :placeholder => "Please input Bank Teller Number or reference or leave blank if free" %>

          <%= f.submit :class => "submit" %>

<% end %>

Location

Audition Venues are regional

PH / LAGOS / ABUJA / CALABAR / ENUGU

+234 803 229 7343

Follow Us

Contact us

misscrystalnigeriapageant@gmail.com

<%= link_to "Home", { controller: "welcome" } %>

About us

Admin

© 2016 MissCrystalNigeria. All rights reserved | Design by DicedOrange

the form model
class Form < ActiveRecord::Base
    mount_uploader :image, ImageUploader
    mount_uploader :imaget, ImageUploader

    has_one :referee

end

the form controller
class FormsController < ApplicationController
  before_action :set_form, only: [:show, :edit, :update, :destroy]

  layout 'aware'

  # GET /forms
  # GET /forms.json
  def index
    flash[:notice] = "Access Denied"
    redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
    @forms = Form.all
  end

  # GET /forms/1
  # GET /forms/1.json
  def show
    flash[:notice] = "Access Denied"
    redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
  end

  # GET /forms/new
  def new
    @form = Form.new
    referees = Referee.all
    @referee = referees.order(:name)
  end

  # GET /forms/1/edit
  def edit
    flash[:notice] = "Access Denied"
    redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
  end

  # POST /forms
  # POST /forms.json
  def create
    @form = Form.new(form_params)

    respond_to do |format|
      if @form.save
        flash[:notice] = 'Successfully Submitted Form'
        format.html { redirect_to :controller => 'welcome', :action => 'index', notice: 'Form was successfully created.' }
        format.json { render :show, status: :created, location: @form }
      else
        format.html { render :new }
        format.json { render json: @form.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /forms/1
  # PATCH/PUT /forms/1.json
  def update
    respond_to do |format|
      if @form.update(form_params)
        format.html { redirect_to @form, notice: 'Form was successfully updated.' }
        format.json { render :show, status: :ok, location: @form }
      else
        format.html { render :edit }
        format.json { render json: @form.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /forms/1
  # DELETE /forms/1.json
  def destroy
    @form.destroy
    respond_to do |format|
      format.html { redirect_to forms_url, notice: 'Form was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_form
      @form = Form.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def form_params
      params.require(:form).permit(:first_name, :valide, :image, :referee, :localgovt, :stateoo, :imaget, :referee_id, :event_id, :last_name, :other_names, :email_address, :backup_email_address, :first_street_address, :second_street_address, :third_street_address, :city, :postal_code, :country, :settlement, :phone_home, :phone_mobile, :phone_work, :age, :dob, :place_of_birth, :height, :weight, :swimsuit_size, :dress_size, :shoe_size, :employment_school, :degrees, :other_awards, :family_bio, :facebook_url, :twitter_url, :fav_color, :fav_food, :fav_sport, :always_naija, :nalways_naija, :hoobies, :sports, :life_ambition, :performable_talent, :special_training, :languages, :like_to_meet, :most_unusual_thing, :most_proud_moment, :countries_visited, :intresting_selfbio, :true_information, :true_age, :true_tandc, :date)
    end
end

the referee model
class Referee < ActiveRecord::Base
    has_many :forms
end

the referee controller
class RefereesController < InheritedResources::Base

    def index
        flash[:notice] = "Access Denied"
        redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
    end

    def show
        flash[:notice] = "Access Denied"
        redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
    end

    def edit
        flash[:notice] = "Access Denied"
        redirect_to :controller => 'welcome', :action => 'index', notice: 'Access Denied'
    end

  private

    def referee_params
      params.require(:referee).permit(:name, :post)
    end
end

anytime i try to create a form, i get this annoying error

ActiveRecord::AssociationTypeMismatch in FormsController#create
Referee(#69872442153920) expected, got String(#69872584329080)
Extracted source (around line #38):

36 # POST /forms.json
37     def create

38    @form = Form.new(form_params)

39
40    respond_to do |format|
41      if @form.save

A: It looks like you've got two options for inputting a referee: a collection select and text field. So in your form params, you're either submitting a referee ID or just a string of the referee's name. So your Form model is expecting a Referee object, but it's just getting passed a String.
You have a couple options - if an ID is selected, you need to do a Referee.find(params[:referee_id] and pass it to the Form model, along with the other params. Or, if you're submitting the name, you need to create a new Referee and then associate it.
Or you can use a nested form and submit the necessary referee parameters. You'd do something like this within your form:
<%= fields_for :referee do |ff| %>
  <%= ff.collection_select :id, @referee, :id, :name, :class => "form-control", :prompt => "Who referred you?" %>

  <%= ff.text_field :name, :class => "form-control", :placeholder => "Someone else? What's his/her name" %>


text:
Q: Extract current fiscal week for current year in PostgreSQL I have a table with fields fiscal week and date in PostgreSQL.
For eg: for date 2015-10-10, it has fiscal week values as 1,2,3..39,40,41,42,etc and similarly for other dates 2014-10-10 it has fiscal week values as 1,2,3..39,40,41,42,etc and same for the year 2013-10-10 and so on... I want to extract the current fiscal week for the current year. As there are multiple fiscal week values for different year and dates , it should extract only for the current fiscal week.


text:
Q: Parallelizing calls in PL/SQL I have a package with a proc that will execute a number of other procedures, like so:
CREATE PACKAGE BODY pkg IS
    CREATE PROCEDURE do
    IS
    BEGIN
        other_pkg.other_proc;
        other_pkg2.other_proc2;
        other_pkg3.other_proc3;
    END;
END;

Is there any way to have the procedures execute in parallel rather than serially?
EDIT:
Is this the proper way to use DBMS_SCHEDULER in this instance:
CREATE PACKAGE BODY pkg IS
    CREATE PROCEDURE do
    IS
    BEGIN
        DBMS_SCHEDULER.CREATE_JOB('job_other_pkg.other_proc', 'STORED_PROCEDURE', 'other_pkg.other_proc;');
        DBMS_SCHEDULER.RUN_JOB('job_other_pkg.other_proc', FALSE);
        -- ...
    END;
END;

A: You can use the dbms_job (or dbms_scheduler) package to submit jobs that will run in parallel.  If you are using dbms_job, submitting the jobs will be part of the transaction so the jobs will start once the transaction completes.
CREATE PACKAGE BODY pkg IS
    CREATE PROCEDURE do
    IS
      l_jobno pls_integer;
    BEGIN
        dbms_job.submit(l_jobno, 'begin other_pkg.other_proc; end;' );
        dbms_job.submit(l_jobno, 'begin other_pkg2.other_proc2; end;' );
        dbms_job.submit(l_jobno, 'begin other_pkg3.other_proc3; end;' );
    END;
END;

If you are using dbms_scheduler, creating a new job is not transactional (i.e. there would be implicit commits each time you created a new job) which may cause problems with transactional integrity if there is other work being done in the transaction where this procedure is called.  On the other hand, if you are using dbms_scheduler, it may be easier to create the jobs in advance and simply run them from the procedure (or to use dbms_scheduler to create a chain that runs the job in response to some other action or event such as putting a message on a queue).
Of course, with either solution, you'd need to then build the infrastructure to monitor the progress of these three jobs assuming that you care when and whether they succeed (and whether they generate errors).
If you are going to use DBMS_SCHEDULER

*

*There is no need to use dynamic SQL.  You can ditch the EXECUTE IMMEDIATE and just call the DBMS_SCHEDULER package's procedures directly just like you would any other procedure.

*When you call RUN_JOB, you need to pass in a second parameter.  The use_current_session parameter controls whether the job runs in the current session (and blocks) or whether it runs in a separate session (in which case the current session can continue on and do other things).  Since you want to run multiple jobs in parallel, you would need to pass in a value of false.

*Although it is not required, it would be more conventional to create the jobs once (with auto_drop set to false) and then just run them from your procedure.

So you would probably want to create the jobs outside the package and then your procedure would just become
CREATE PACKAGE BODY pkg IS
    CREATE PROCEDURE do
    IS
    BEGIN
        DBMS_SCHEDULER.RUN_JOB('job_other_pkg.other_proc', false);
        DBMS_SCHEDULER.RUN_JOB('job_other_pkg2.other_proc2', false);
        DBMS_SCHEDULER.RUN_JOB('job_other_pkg3.other_proc3', false);
    END;
END;

A: Another solution is to hack Oracle's SQL parallelism mechanism. See answer to  How to execute a stored procedure in a different session in same time in pl/sql .
It uses William Robertson's great solution Parallel PL/SQL launcher.
(tested with Oracle 10g)


text:
Q: get health checks automatically using API calls in Foundry Slate Is there a way to get health checks automatically using API calls and show it in Foundry Slate application. I am trying to get the available data sets info such as health checks and show them in the dashboard automatically using API calls based on RID as a param or any other way

A: Within slate, if you open queries you should have an endpoint to hit the data health service api. Open the source dropdown and search for data-health SERVICE API (blue arrow on the image).
Afterwards a new dropdown should show up with the available services that you can query data health with (green arrow). Depending on your stack it is also possible that this is a JSON API instead of a SERVICE API, in that case it can look slightly different from the screenshot.


text:
Q: ExtJs Store no record found, but saved one recently Im working on a project with Sencha Touch and the sqLite proxy you can find here. This website is in a phonegap environment, but it's not used when i run it from the browser.
I have this WorkShift model which is used by WorkShifts store.
Model:
Ext.define('KCS.model.WorkShift', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            { name: 'id', type: 'int' },
            { name: 'WorkShiftID', type: 'int' },
            { name: 'StartDate', type: 'date' },
            { name: 'ClosureDate', type: 'date' },
        ],
        proxy: {
            type: 'sqlitestorage',
            dbConfig: {
                tablename: 'tbl_WorkShift',
                dbConn: KCS.util.InitSQLite.getConnection()
            }
        }
    }
});

And the Store:
Ext.define('KCS.store.WorkShifts', {
    extend: 'Ext.data.Store',
    requires: ['KCS.model.WorkShift'],
    config: {
        model: 'KCS.model.WorkShift',
        autoLoad: true,
        storeId: 'WorkShifts',
        pageSize: 1000
    }
});

Now, in my Controller, i want to see if there is an opened WorkShift (if the app crashed or was closed without closing the last Workshift.) So i use the launch callback like this:
launch : function(){
    var workShifts = Ext.getStore('WorkShifts');
    workShifts.clearFilter(true);
    var openedWS = workShifts.findBy( function( record ){
        return (record.get("StartDate") != null) &&
            (record.get("ClosureDate") == null);
    });
    if( openedWS != -1 ){
        // do stuff when an opened WS is found
    }
    else{
        // do normal stuff
    }
},

I did a bunch of tests, First, there is a bunch of valid entries in sqLite, and i can create WS from the store and model. There is also an entry that meets the findBy bool test. I've tried workShifts.getCount() and even workShifts.getAllCount() but both functions return 0. What have i done wrong?
EDIT:
I have also searched for things like the launch func running before the store can load data from the proxy or even cordova not firing the deviceReady callback. I have tried to apply a filter on the store and check with getFirst() if one survived to the test, but i think there is not even a single record to test in the first place even tho they show up in the SqLite overview from the Resources tab (in chrome webTools).

A: I used the manual load function of the store and used the callback to do what i needed. The autoload parameter in the store creation is also asynchronous. That was my problem.
http://docs.sencha.com/touch/2.2.1/#!/api/Ext.data.Store-method-load
like so:
launch : function(){
    var workShifts = Ext.getStore('WorkShifts');
    workShifts.load({
        callback: function(records, operation, success) {
            workShifts.clearFilter(true);
            var openedWS = workShifts.findBy( function( record ){
                return (record.get("StartDate") != null) &&
                    (record.get("ClosureDate") == null);
            });
            if( openedWS != -1 ){
                // do stuff when an opened WS is found
            }
            else{
                // do normal stuff
            }
        },
        scope: this
    });
},