text:
Q: Sub-Menu Not Showing (Appearing Under Header) Project: lightertaste.com
The top menu has sub-menus under About, Nutrition & Fitness, and Resources, but it is not appearing correctly. Seems to be hidden under the menu.
Hoping someone can help me correct. Thanks!

Home

About

About

Philosophy

FAQ

Work With Me

Contact

Recipe Index

Nutrition & Fitness

Meal Plans

Meal Prep

Workouts

Resources

Start a Blog

My Blogroll

Thank Yous

Shop

<form class="search-top-form" method="get" action="http://www.lightertaste.com/">

<input class="search-top-input" type="text" name="s" id="s" value="" placeholder="Search" />

<input class="search-top-submit" type="submit" name="submit" id="searchsubmit" value=" " />
</form>

.before-header {
 background: #3d4646 !important;
 clear: both;
 padding: 5px !important;
 text-align: center;

 font-family: 'dosis-regular' !important;
 font-size: 14px;
 letter-spacing: 1px;
 text-transform: lowercase;
}

.before-header .widget {
 margin: 0 auto;
 max-width: 1000px !important;
}

/* Top Navigation
--------------------------------------------- */

#top-navigation ul {
 list-style: none;
 position: relative;
}

#top-navigation ul a {
 display: block;
 color: #ffffff !important;
 font-weight: normal !important;
 text-decoration: none;
}

#top-navigation ul a:hover {
 color: #68a29c !important;
}

#top-navigation ul li {
 position: relative;
 float: left;
 margin: 0px 10px;
}

#top-navigation ul li:first-child {
 margin-left: 0px;
}

#top-navigation ul li:hover {
 color: #79a7a5;
}

#top-navigation ul ul:before {
 content: '';
 display: block;
 margin: auto;
 width: 0;
 height: 0;
 border-left: 11px solid transparent;
 border-right: 11px solid transparent;
 border-bottom: 11px solid #68a29c;
}

#top-navigation ul ul {
 display: none;
 position: absolute;
 margin-top: -2px;
 left: 50%;
 transform: translateX(-50%);
 width: 150px;
}

#top-navigation ul ul li {
 float: none;
 margin: 0px;
}

#top-navigation ul ul a {
 display: block;
 background: #68a29c;
 padding: 10px;
 font-size: 12px;
}

#top-navigation ul ul a:hover {
 background: #3d4646;
 color: #ffffff;
}

#top-navigation ul ul ul {
 top: 0;
 left: 100%;
}

#top-navigation ul li:hover > ul {
 display: block;
}

A: Solved. Noticed this code in another area:

/*
Top Ad
---------------------------------------------------------------------------------------------------- */

.before-header {
 background: #f5f5f5;
 clear: both;
 overflow: hidden;
 padding: 10px 0;
 text-align: center;
}

.before-header img,
.before-header iframe {
 display: block;
 margin: 0 auto;
}

.before-header .widget {
 margin: 0 auto;
 max-width: 1100px;
}


text:
Q: javascript onchange query issue I have the following javascript at the head of my file.
<?php
echo "<script language='JavaScript'>\n";
echo "var times = new Array();\n";
echo "times[0] = 0;\n";
foreach($times as $time)
{
echo "times[". $time->DESC ."] = " . $time->FEE . ";\n";
}
echo "</script>\n";
?>

i then have a dropdown, where the options are the same $time->DESC,
i have an onchange, and i want to set another text box value to equal the PBT_FEE according to the PBT_DESC
i have
onchange="document.getElementById('Price').value = times[this.value];"

i presume that times[this.value] should call for the fee according to the matching descriptions, but i get no output

A: I just tried this playing with the w3schools example, and it works, so I'm guessing your problem is somewhere in the html elements.
<html>
<head>
<script type="text/javascript">

var times = new Array();
times[0] = 0;
times[1] = 1;
times[2] = 4;
times[3] = 7;
</script>
</head>
<body>

<select onchange="document.getElementById('finalPrice').value = times[this.value];">
  <option value="0">Volvo</option>
  <option value="1">Saab</option>
  <option value="2">Mercedes</option>
  <option value="3">Audi</option>
</select>

<input type="text" name="fname" id="finalPrice" /><br />

</body>
</html>

A: I think you should be getting the value of the dropdown box, instead of the times[this.value]...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript exec returning null
My problem is when I try and use exec on my string, console throws this error:
Uncaught TypeError: Cannot read property '1' of null
Here's my code:
var regexes = {
    "bold": [/\[bold\](.*)\[\/bold\]/g,"",""],
    /*"italics": [[/\[italics\]/g,""],[/\[\/italics\]/g,""]],
    "underline": [[/\[underline\]/g,""],[/\[\/underline\]/g,""]],
    "spoiler": [[/\[spoiler\]/g,"
"],[/\[\/spoiler\]/g,"
"]],
    "strikethrough": [[/\[strikethrough\]/g,""],[/\[\/strikethrough\]/g,""]],*/
}
var functioners = {
    "zalgo": [/(\[zalgo\].*\[\/zalgo\])/g],
    "flip": [/(\[flip\].*\[\/flip\])/g],
    "superscript": /[a-zA-Z0-9]\^([a-zA-Z0-9]*)/g,
    "triforce": /(%triforce)/g,
    "list": /(^\*\ .*)/g
}

var replies = document.getElementsByClassName("postMessage");
var x = 0
function memes(x,z) {
    window.setTimeout(function() {
        var theNew = "";
        theNew = replies[x].innerHTML;
        for (key in regexes) {
            if (regexes[key][0].exec(replies[x].innerHTML) !== null) {
                theNew = regexes[key][1] + regexes[key][0].exec(replies[x].innerHTML)[1] + regexes[key][2];
            }
        }
        if (x < z) {
            memes(x+1,z);
        }
    },5);
}
memes(x,replies.length-1);

This code is supposed to go through elements with the class name "postMessage" and replace certain text with the exec, however. The error is thrown. A similar problem is over at RegExp.exec() returns NULL sporadically. I can't work out how to do it with my current situation. It'd be great if someone could help me with this problem.
Please note: this code is in a Google Chrome extension script!!

A: Please could you try as in the following:
for (key in regexes) {
        var m = regexes[key][0].exec(replies[x].innerHTML);
        if (m !== null) {
            theNew = regexes[key][1] + m[1] + regexes[key][2];
       }
}

Please, let me know


text:
Q: How do I set my rails 3 app to development mode? I need to set my rails 3 app on DreamHost to development mode.
In rails 2.3, I used to set it at environment.rb.
How and where do I do that for rails 3?
Thanks.
Sam

A: Like Ikahtz says, but:
# in config/environment.rb
ENV['RAILS_ENV'] = 'development'

A: add this to your environment.rb:
ENV['RAILS_ENV'] ||= 'development'

A: As far as I know setting your Rails environment via RAILS_ENV wouldn't help you on a DreamHost shared server because they are running their Passenger strictly with the production environment.


text:
Q: When are Symfony 2.3 form events fired? There is a similar question but it might be outdated since it says it applies to Symfony 2.0. Description of Symfony2 form events?
The following events are supported in Symfony2 2.3:
const PRE_SUBMIT = 'form.pre_bind';
const SUBMIT = 'form.bind';
const POST_SUBMIT = 'form.post_bind';
const PRE_SET_DATA = 'form.pre_set_data';
const POST_SET_DATA = 'form.post_set_data';

When are these events fired in the example shown below from Symfony's book?
public function newAction(Request $request)
{
    // just setup a fresh $task object (remove the dummy data)
    $task = new Task();

    $form = $this->createFormBuilder($task)
        ->add('task', 'text')
        ->add('dueDate', 'date')
        ->add('save', 'submit')
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        // perform some action, such as saving the task to the database

        return $this->redirect($this->generateUrl('task_success'));
    }

    // ...
}

A: The events are triggered when you call $form->submit($data) or in your case when you call $form->handleRequest($request) which will call (by default) the submit() method if the request is a GET or POST. The order of events is:
PRE_SET_DATA
POST_SET_DATA
PRE_SUBMIT
SUBMIT
POST_SUBMIT
If you look in Symfony\Component\Form\Form and examine the submit() method, you will see where the events are triggered.


text:
Q: Emacs: Finding function definition in etags Syntax check in js2-mode is awesome.
But sometimes I just want to define a function named "delete" or "new" even thought that's not a good idea. Js2-mode seems to treat this as an error.
How can I use build-in keywords as function name in js2-mode? I need your help.
================================================
I am sorry for my stupid question...
I'm using etags.
but writing someting like:
exports.new = function() {
};

seems etags will treat this as the definition of 'exports.new', not 'new'.
TAGS
};exports.new248,8614

So I'm trying to write something like:
function new() {
}
exports.new = new;

How stupid I am !!!
So my questiong turn back to how to make etags find the definition of 'new', not 'exports.new' ?
Thanks. :)

A:
"Js2-mode seems to treat this as an error"

It is an error, isn't it?
I really don't understand why you'd want to do it, but the following works:
someObject["new"] = function() {
   alert("This is the 'new' function.");
}

someObject["new"]();

Assuming someObject already exists as an object. Or:
var someObject = {
       "new" : function() {},
       "delete" : function() {}
};

someObject["new"]();
someObject["delete"]();

In the browser you can say window["new"] = function() {}, but you can't call the resulting function with new(), you have to say window["new"]().
In node.js I believe the equivalent would be global["new"] = function() {}. I don't use node, but I assume this would create a global function called "new", but you wouldn't be able to call it with the new() syntax, you'd have to say global["new"]().
I do not recommend doing this.


text:
Q: Why PyCUDA is faster than C CUDA in this example I am exploring to move from OpenCL to CUDA, and did a few tests to benchmark the speed of CUDA in various implementations. To my surprise, in the examples below, the PyCUDA implementation is about 20% faster than the C CUDA example.
I read many posts talking about "release build" of C CUDA code. I did try having -Xptxas -O3 in the makefile and that really did not make a difference. I also tried to adjust the block size, with which the kernel was executed. Unfortunately, it did not help improve the speed, either.
My questions here are:

*

*What could be the reasons leading to the speed difference between C CUDA and PYCUDA?

*If the "advanced" (lack of a better word) compiling in PYCUDA is one of reasons, how can I optimize the compiling of my C CUDA code?

*Are there any other ways to improve the speed of C CUDA in this case?

While I appreciate general comments, I am looking for actionable suggestions that I can validate on my machine. Thanks!
import pycuda.autoinit
import pycuda.driver as drv
import numpy as np

from pycuda.compiler import SourceModule
import time

mod = SourceModule(
    """
__global__ void saxpy(int n, const float a, float *x, float *y)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n){
        y[i] = a * x[i] + y[i];
    }
}
"""
)

saxpy = mod.get_function("saxpy")

N = 1 << 25
time_elapse = 0.0

for i in range(100):
    # print(i)
    # print(N)

    x = np.ones(N).astype(np.float32)
    y = 2 * np.ones(N).astype(np.float32)
    start = time.time()
    saxpy(
        np.int32(N),
        np.float32(2.0),
        drv.In(x),
        drv.InOut(y),
        block=(512, 1, 1),
        grid=(int(N / 512) + 1, 1),
    )
    time_elapse += (time.time() - start)

print(time_elapse )
print(y[-100:-1])
print(y.sum())
print(N * 4.0)

#include <stdio.h>
#include <time.h>
#define DIM 512

__global__ void saxpy(int n, float a, float *x, float *y)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n)
        y[i] = a * x[i] + y[i];
}

int main(int num_iterations)
{
    double start;
    double cputime;
    int N = 1 << 25;
    float *x, *y, *d_x, *d_y;
    int i, j;
    for (j = 0; j < num_iterations; j++)
    {
        x = (float *)malloc(N * sizeof(float));
        y = (float *)malloc(N * sizeof(float));

        cudaMalloc(&d_x, N * sizeof(float));
        cudaMalloc(&d_y, N * sizeof(float));

        for (i = 0; i < N; i++)
        {
            x[i] = 1.0f;
            y[i] = 2.0f;
        }

        cudaMemcpy(d_x, x, N * sizeof(float), cudaMemcpyHostToDevice);
        cudaMemcpy(d_y, y, N * sizeof(float), cudaMemcpyHostToDevice);

        // Perform SAXPY on 1M elements
        start = clock();
        saxpy<<<(N + DIM) / DIM, DIM>>>(N, 2.0f, d_x, d_y);
        cputime += ((double)(clock() - start) / CLOCKS_PER_SEC);
        cudaMemcpy(y, d_y, N * sizeof(float), cudaMemcpyDeviceToHost);

        // float maxError = 0.0f;
        // for (int i = 0; i < N; i++){
        //     maxError = max(maxError, abs(y[i] - 4.0f));
        //     //printf("y[%d]: %f\n", i,y[i]);
        // }
        // printf("Max error: %f\n", maxError);

        cudaFree(d_x);
        cudaFree(d_y);
        free(x);
        free(y);
    }

    printf("cpu time is %f\n", cputime);
    return 0;
}

I saved the above file as cuda_example.cu and compile it with the following commands in a makefile:
nvcc -arch=sm_61 -Xptxas -O3,-v -o main cuda_example.cu

A: If I execute your CUDA-C code as is, and set num_iterations to 300 like this:
int num_iterations =300;

then the execution of your program takes about 60s on a Geforce GTX 1650. Your code is extremely inefficient, as you copy data back and forth between GPU and device at every iteration.
So, lets restrict the loop to just the kernel execution:
#include <stdio.h>
#include <time.h>
#define DIM 512

__global__ void saxpy(int n, float a, float *x, float *y)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n)
    y[i] = a * x[i] + y[i];
}

int main()
{
double start = clock();
int N = 1 << 25;
float *x, *y, *d_x, *d_y;
int i, j;

int num_iterations = 300;
x = (float *)malloc(N * sizeof(float));
y = (float *)malloc(N * sizeof(float));

cudaMalloc(&d_x, N * sizeof(float));
cudaMalloc(&d_y, N * sizeof(float));

for (i = 0; i < N; i++)
{
   x[i] = 1.0f;
   y[i] = 2.0f;
}
cudaMemcpy(d_x, x, N * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_y, y, N * sizeof(float), cudaMemcpyHostToDevice);

for (j = 0; j < num_iterations; j++){
    saxpy<<<(N + DIM) / DIM, DIM>>>(N, 2.0f, d_x, d_y);
    cudaDeviceSynchronize();
}
cudaMemcpy(y, d_y, N * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(d_x);
cudaFree(d_y);
free(x);
free(y);

double cputime = ((double)(clock() - start) / CLOCKS_PER_SEC);
printf("cpu time is %f\n", cputime);
return 0;
}

If I do that, then the execution time becomes 1.36 seconds. Doing sth similar to the PyCUDA code I got about 19s of execution time.


text:
Q: Iphone Objective C - resignFirstResponder upon tapping out of my UITableViewCell Hihi all,
My requirement is to hide the keyboard or picker when user tap out of my UITableViewCell (but still within the UITableView).
I have found some post about overriding hitTest by subclassing UIView, but my class is subclass of UIViewController, and I need the dismissModalViewControllerAnimated method, which makes me can't change the subclass to UIView, thus not able to override the hitTest.
Is there other alternative to achieve the above requirement? Please advice. Thanks in advance.
:)

A: You may be able to create an IBAction that sends the (id)sender and resignsFirstResponder add it to TouchUpOutside UITableViewCell in IB or you may be able to code it like:
 UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
 [self.tableView addGestureRecognizer:gestureRecognizer];

and add [specificfield resignFirstResponder]; to your dismissKeyboard field and make it into a void method.
That's what Dismiss keyboard by touching background of UITableView article says anyhow, and it seems similar to your problem.


text:
Q: Django rejecting urlencoded parameters in POST request? Using Postman https://www.getpostman.com/ send POST requests in url encoded format. They pass when no variables included, otherwise meet with errors, for example:

*

*for an integer parameter: Type error: int() argument must be a string or a number, not 'list'

*for a decimal parameter: ValueError: Invalid tuple size in creation of Decimal from list or tuple. The list or tuple should have exactly three elements.
For a django model with variables:
grams = models.IntegerField(default=0)
amount_payable = models.DecimalField(max_digits = 5, decimal_places = 2)

and with CRSF off. A Post that could generate above errors would be:
POST /mypath/ HTTP/1.1
Host: 127.0.0.1:8000
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cache-Control: no-cache
Postman-Token: 36eac051-d7e9-b106-effa-aa1fd557a42f

amount_payable=25.22&grams=450

In the debug pages in Django then find:
<django.db.models.manager.Manager object at 0x10c6d2110>
args   ()
name   'create'
kwargs   {u'amount_payable': [u'25.22'], u'grams': [u'450']}

It all looks well formatted, is Django having problems parsing? Have tried using other Models & variable types. Is there a problem with the format/content of the POST?
View code like this:
def create_transaction(request):
    this_transaction = Transaction.objects.create(**request.POST)
    return HttpResponse('AOK')

A: request.POST is not a normal dictionary, it is actually a QueryDict object. You need to convert it to a traditional dict, before you can use it as such:
Transaction.objects.create(**request.POST.dict())

I must say, the above is not something I would put in production - there are no checks as to the contents of the dictionary - any malicious/junk can be used to create objects.
You should use forms to validate the input, and then create objects, like this:
class TransactionForm(forms.ModelForm):
   class Meta:
       model = Transaction

user_input = TransactionForm(request.POST())
if user_input.is_valid():
   user_input.save()


text:
Q: C# Web API call return a 401.1 only when it's long-running I have a Web API method that is secured by Windows Authentication.  Here's the client code:
var uri = new Uri(@"https://myapi.mysite.com/api/method");
var request = HttpWebRequest.Create(uri);
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "application/json";
request.Timeout = 30 * 60 * 1000;

request.Credentials = new NetworkCredential("userName", "password", "domain");

using (var response = request.GetResponse())
{
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
        Console.WriteLine(responseStream.ReadToEnd());
    }
}

When https://myapi.mysite.com/api/method takes less than about 5 minutes to return, all is well.  As soon as it takes 5 minutes or longer (5 minutes seems to be a magic number), I start getting a 401 back.  I'm using the same credentials both times.  Everything is the same except the amount of data the server is processing (obviously more data leading to longer processing time).
The specific 401 I'm getting is the '401 - Unauthorized: Access is denied due to invalid credentials.' message.
I've experimented with KeepAlive, CredentialCache, setting a server timeout and many other options/approaches and can't get anything to work.
The server is IIS 7.5 running under a service account whose password never expires.
Any help would be appreciated.


text:
Q: Product on Tensor Products I'm trying to understand how products on tensor products work. For instance, in quantum mechanics, you have ($x$ tensor $y$) times ($z$ tensor $a$), where $x$, $y$, $z$, $a$ are all operators acting on a Hilbert space. I want to believe that it's just $xz$ tensor $ya$, but I'm looking online and that only applies for von Neumann algebras (http://en.wikipedia.org/wiki/Von_Neumann_algebra), but I'm not sure if the operators in quantum mechanics forms a ring.

A: If you are a mathematician that just wants to prove results you can try to make up definition of products of "operators" and try to make a $W^*$ or a $C^*$ algebra out of them (and make them a ring or not or whatever you want).  But you are being concrete and saying that these are operators on a Hilbert Space, so you can answer your own question by looking at how the operators act on the Hilbert Space.
For instance if you take a tensor product of Hilbert Spaces, with elements $v\otimes w$ and your operator $V\otimes W$ is defined by $(V\otimes W)(v\otimes w)= (Vv)\otimes (Ww)$, then since you've said how your operators act, then we can deduce that:
$$(V_2\otimes W_2)\circ (V_1\otimes W_1)=(V_2\circ V_1)\otimes (W_2\circ W_1).$$
Since both obviously send $v\otimes w$ to $V_2(V_1(v)) \otimes W_2(W_1(w))$.


text:
Q: Integral calculus exercise I have an exercise that reads; You jump from a 10-meter-high tower, calculate the time needed and the velocity just before I touch the ground, regardless of the mass of the body falling.
I've already solved it, but I need help. In the class we learn about calculus, therefore I tried to use it in order to calculate the time and velocity. The thing I don't understand is why calculus and not using the first method written below?
My solution without calculus:
$$ g = v / t = 10 m/s^2$$
$$v = d / t$$
$$ => g = d / t^2 $$
$$ t^2 = d / g $$
$$ t^2 = 10/10 $$
$$ => t = 1 s $$
$$ v = d / t = 10 / 1 = 10 m/s $$
With calculus:
$$ v = Δd / Δt $$
$$ g = v / t => g = Δd / Δt * t $$
$$ Δd = g * t * Δt $$
$$ Δd = \int_{0}^{t}  10 × t × Δt => 10  \int_{0}^{t}  t × Δt$$
$$10 × ½ t² => t = √2 $$
thanks in advance

A: Your work doesn't really make sense to me the formula $d/t$ does not apply for changing velocity.
When something is falling off a tower, it's  velocity changes of course.
It made sense to define velocity as displacement  over time when something was moving at constant velocity. So we did.
But now something is not moving at constant velocity, what do we do.
We say that for a time period say $t$ in $t_f-\Delta t$ to $t_f$ if $\Delta t \to 0$ we approach constant velocity.
Surely in the matter of $.0001$ seconds the object cannot significantly change velocity, so then the definition of velocity for the constant case just about applies. But we can do better, we can let $\Delta t \to 0$. And that is when calculus comes in.
The quantity $d/t$ is only defined to be velocity when we have constant velocity, rather it is always defined as average velocity.
The same applies to acceleration, $\Delta v/t$ only a makes sense for the constant acceleration case, which we do have here.
We have then that $\lim_{t \to 0} \frac{\Delta v}{\Delta t}=a=-g$ from which we find $V=V_0+gt$ below:
For $\Delta t \to 0$:
$$\frac{\Delta v}{\Delta t}=-g$$
$$\Delta v=-g \Delta t$$
$$\int dv=\int -g dt$$
$$V=C-gt$$
Let $t=0$.
$$V=V_0-gt$$
This could have just been easily derived by $\Delta v/t=-g$ because here we have constant acceleration.
But because now we don't have constant velocity to derive the displacement formula we should use calculus, or in this case it is sufficient to use geometry. In any case as $g \approx 10$ we get,
$$t \approx \sqrt{2}$$
$$V \approx 0-g\sqrt{2}$$


text:
Q: Override DbSet.Remove() or Restore Entity values within DbContext ChangeTracker.DetectChanges() The current issue that I am facing is that I am implementing a Soft Delete on all objects, but .Remove() on an Entity will remove foreign keys during it's process.
MyObject (ie):

Id = 1
Name = Blah
PageID = null (was 10 before .Remove() was called, I want to preserve this during SoftDelete)

Is is possible to override public virtual TEntity Remove(TEntity entity)? or modify my ChangeTracker.DetectChanges(); section?
Like I briefly mentioned, I am using ChangeTracker.DetectChanges(); to set the Entity (ObjectStateEntry) back to Modified (entry.ChangeState(EntityState.Modified);) and setting another Property IsActive to false, however the "stripping" of other fields has already been done when .Remove() was called.
MVC creates Controllers for all my objects and within the DeleteConfirm is db.entityObject.Remove(entity).
... or is there a different approach I should be looking into?
I can provide more details, please let me know what you may need.
Example within a Controller:
// POST: MyObject/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(Guid id)
{
    MyObject myObject = db.MyObject.Find(id);
    db.MyObject.Remove(myObject);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Subset of my DbContext code:
public class AppDbContext : DbContext
{
    public override int SaveChanges()
    {
        ChangeTracker.DetectChanges();

        objectContext.ObjectStateManager.GetObjectStateEntries(
            EntityState.Added |
            EntityState.Modified |
            EntityState.Deleted);

        foreach (ObjectStateEntry entry in objectStateEntryList)
        {
            if (!entry.IsRelationship)
            {
                switch (entry.State)
                {
                    case EntityState.Deleted:
                        entry.ChangeState(EntityState.Modified);
                        ((BaseObject)entry.Entity).IsActive = false;

                        //Update #1
                        this.Entry(entry.Entity).Reload();

                        //Is is possible to "restore" the original object?
                        //or override .Remove()?

                        break;
                }
            }
        }

        return base.SaveChanges();
    }
}

Thank you in advance.
Update 1:
Is it as simple as calling the following?
this.Entry(entry.Entity).Reload();

I think this worked, I understand this might be another database call, but resolves for now.  Further testing needed.

A: Let me suggest to @Derek the:
Update 2:
public class AppDbContext : DbContext
{
    public override int SaveChanges()
    {
        ChangeTracker.DetectChanges();

        objectContext.ObjectStateManager.GetObjectStateEntries(
            EntityState.Added |
            EntityState.Modified |
            EntityState.Deleted);

        foreach (ObjectStateEntry entry in objectStateEntryList)
        {
            if (!entry.IsRelationship)
            {
                switch (entry.State)
                {
                    case EntityState.Deleted:
                        // Update #2
                        // ---------
                        // Set the state to 'Unchanged'.
                        // Only updated fields will be sent to the Db.
                        entry.ChangeState(EntityState.Unchanged);
                        ((BaseObject)entry.Entity).IsActive = false;
                        break;
                }
            }
        }

        return base.SaveChanges();
    }
}

Thanks to Entity Framework Core: Soft Delete blog post from Ryan Southgate.


text:
Q: Joining SQL queries with where clause I have 2 tables in a MYSQL database wich look like this:
Klant:
ID  Naam           Email    Soort  Status
6   test           test     test2
7   status test    test     test    20
8   soort test     test     test
9   soort test 2   test2    Museum

Mail:
ID  Content                 Datum       Titel
1   (lots of encoded HTML)  18-03-13    test
2   (lots of encoded HTML)  18-03-13    test2
4   (lots of encoded HTML)  18-03-13    alles weer testen

(yes, I'm still testing alot^^)
Now I have a SQL query that selects all from 'Klant' with a where clause which gets the ID from a previous page:
$strSQL = "SELECT * FROM Klant WHERE ID =  '".$_GET["ID"]."' ";

What I want is to JOIN this query with the following query:
SELECT ID, Titel FROM Mail;

EDIT:
From all your answers and comments I think I begin to think my question maybe is totally wrong.. I'll explain where I need it for and I might not even need JOIN? I currently have a table wich includes the data from 'Klant' which looks like this:

The meaning is that I add another table which includes all the ID's and Title's from 'Mail'. I am sorry for the confusion I may have caused with you since I wasn't that clear with my question. I hope that this may clear up what I want and you guys can maybe tell me if I even need to JOIN this or can I do something else?
I am still a student and this is the first time I've had to use JOIN and I can't figure this out. If anyone can show me how to do this or push me in the right direction it would be great!

A: SELECT * FROM Klant t1
JOIN
SELECT ID, Titel FROM Mail t2
ON t1.ID = t2.ID
WHERE t1.Name  = 'test'

To have the desired result do the following:
SELECT * FROM Klant t1
JOIN
SELECT ID, Titel FROM Mail t2
ON t1.ID = t2.ID

And if you want to have a specific row than just add the where clause:
WHERE t1.ID = 6

or
WHERE t1.Naam = 'test'

and so on

A: I'm guess that you want to join on the ID field which is common between the tables.
select * from Klant, Mail where Klant.ID = '".$_GET["ID"]."' and Klant.ID = Mail.ID

You can also do
select * from Klant
  join Mail on  Mail.ID = Klant.ID
  where Klant.ID = '".$_GET["ID"]."'

A: You can do this directly by using the following query :
select k.ID,k.Naam, k.Email,k.Soort,k.Status, m.ID,m.Titel from Klant k, Mail m where k.ID = m.ID and k.ID = '".$_GET["ID"]."'

A: It is difficult to see how a JOIN is applicable in the example in your question.
A JOIN let's you pull information from more than one table based on a relationship. As far as I can see, your table's don't have any way to link a row in one with a row in the other, unless SteveP is correct and your id's provide that relationship.
For example, if your klant table had a mail_id column then you could do
SELECT *
FROM klant
JOIN mail ON klant.mail_id = mail.id

and this would return a row for every matching pair of rows in the two tables. Alternatively you could use a LEFT OUTER JOIN to pull back all rows from the table on the left of the JOIN and optionally data from a matching row on the right.
If there is nothing joining the table, you can use a CROSS JOIN which will return you a full cartesian of each row in table1 with every row in table2.
Something people often confuse with a JOIN is a UNION which allows you to write 2 SELECT statements and return the result set of both combined/joined together, but these should return the same columns in each query (e.g. selecting NULL in place of the column in a query if the query doesn't pull data for that column)


text:
Q: Is there a cable that is 2.5" (44-pin) IDE on both ends, or an alternative to plug a SATA drive into an IDE laptop? I want to plug a 2.5" SATA HDD into a laptop with an internal IDE connector.
They could use this SATA-IDE adapter board pictured below.
The SATA HDD with the adapter won't fit into the bay, but let's say that's fine.
It's largely an aesthetic issue; it doesn't matter if there's an "extension" cable.
When using that SATA-IDE adapter attached to the HDD, they could attach a 2.5" cable F-F, then use a gender changer at the other end so it looks like the connector of an IDE hard drive.  That 2.5" male end end of the cable could then be plugged into the laptop's IDE port
But I don't know whether such a cable that is 2.5" at both ends exists.
Or are there alternative ways of plugging a 2.5" SATA drive into a 2.5" IDE connector?

A: Here is a cable that would work. So if aesthetics are truly no big deal, here you go.
Added by barlop - This is 2.5" IDE both ends, despite the "Micro SATA Cables" brand name.  And it has 2 reviews, both by people that know what they're talking about, both lowest rating,  pointing out issues with it that they think are serious. One review mentions that the red painted side (denoting pin1) is on the wrong side (though i'd wonder how that makes a difference - and how one would determine what is the wrong side. Either side could be deemed pin1 and the painted strip ensures that it's not twisted). A criticism in a review is that pin 20 on it has not been removed so would have to be removed/bent, but that's doable , the procedure is " You clip the pin by using a small set of wire cutters or grabbing the pin with needle nose pliers and bend it back and forth until it breaks off preferably flush with the plastic so there is no way for it to make contact." as described in a post here  +1 for the principle though!
The cable is this product on amazon Micro-SATA-Cables-44-Pin-Converter
You won't have to bother with further gender changers.

EDIT: by Carl B added information

There is a descriptive set up of pin 1 on the below diagram and a link to a potentialy better suited product here at cablesOnline.com 6" 44-Pin Female to Male IDE True Extension

Specifications:
•This Cable is used to extend 2.00mm, 44 pin Laptop Hard Drive cable
•(1) 44 Pin 2.5" IDE Female 2.0mm Laptop Connector
•(1) 44 Pin 2.5" IDE Male 2.0mm Laptop Connector
•Length: 6 inches

Note the interweave of the ribbon on the female end. So a stright cable like the first example may not be proper and thus the poor reviews and performance of the product to include incorrect pin 1 and pin 2 along with pins 43 and 44 orientation. This possibly cased the drive damage the reviewers were talking about.

Edit: added pin out of 2.5 IDE ribbon (a google images classic) - original source apparently from http://www.unitechelectronics.com/whyisitso.htm

A: I haven't tried this much, but this might help. It's a SATA-IDE connector, but i think it goes 2 ways. SATA->IDE and IDE->SATA,  I don't know if one ever needs a gender changer for this.  The power connector on it is not to power the drive, it's to power the circuitry on the board.
You may need a 2.5"-3.5" cable WITH a gender changer, as 2.5-3.5" cables that i've seen are female both end and you need the end of the cable that goes into the laptop motherboard to be male. Also you'd be plugging the 3.5" end into an adapter and then from there using a sata cable to a hard drive.  That is different to the normal usage where the 3.5" goes to a MBRD, and the 2.5" to a drive. In this context, I'm not sure if you also have to be careful with which side is pin1 and whether pin1 is pin1 on both ends. (A good technical review of a 2.5" both sides cable in the other answer suggests the red stripe denoting pin1 might only apply to one end, but i'm not sure if that particular point is correct).

This guy demonstrating one, is plugging it into a 3.5" drive. So i'd expect devices that look like that to be 3.5" IDE, but adapting between 2.5" to 3.5" is a common thing, though I haven't done it in this context.
and bear in mind you'd be going the other way completely, with the IDE side towards the motherboard, and with a SATA hard drive connected to this adapter with a SATA cable.  (I only point to that picture to demonstrate that it's a 3.5" adapter and how it is powered and what the power is and isn't for)

Added

added-
any sata hdd or whatever hdd has to be powered itself e.g. from a computer's psu. the power supply going into the board just powers a chip on the board.


text:
Q: Getting '${Token[TOKEN.72]} is not valid' error on cdk synth, when assigning ec2.Vpc.cidr value from cfnParameter.valueAsString Trying to use the AWS CDK CfnParameter to parameter-ise the cidr value of ec2.Vpc. The intent is to re-use the stack for VPC creation with the CIDR for the VPC as a "plugabble" value.
"${Token[TOKEN.72]} is not valid" error is generated when the stack is synthesized ($cdk synth ) for the following code snippet:
        // Parameter
        const vpcCidr = new cdk.CfnParameter(this, 'vpcCidr', {
            type: 'String',
            default: "10.0.0.0/16",
            minLength: 10,
            maxLength: 18,
            allowedPattern: '(\\d{1,3})\.(\\d{1,3})\.(\\d{1,3})\.(\\d{1,3})/(\\d{1,2})'
        });

        // VPC Congfiguration
        const vpc = new ec2.Vpc(this, "vpcName", {
            cidr: vpcCidr.valueAsString,
            maxAzs: 2,
            vpnGateway: true, // VPC can accept VPN connections
            subnetConfiguration: [
                {
                    cidrMask: 19,
                    name: "Private",
                    subnetType: SubnetType.PRIVATE,
                },
                {
                    cidrMask: 20,
                    name: "Public",
                    subnetType: SubnetType.PUBLIC,
                },
                {
                    cidrMask: 21,
                    name: "Protected",
                    subnetType: SubnetType.ISOLATED,
                },
            ],
        });

I have tried passing the cidr block as a static string and it works:
        // VPC Congfiguration
        const vpc = new ec2.Vpc(this, "vpcName", {
            cidr: "10.0.0.0/16",
            maxAzs: 2,
            vpnGateway: true, // VPC can accept VPN connections
            subnetConfiguration: [
                {
                    cidrMask: 19,
                    name: "Private",
                    subnetType: SubnetType.PRIVATE,
                },
                {
                    cidrMask: 20,
                    name: "Public",
                    subnetType: SubnetType.PUBLIC,
                },
                {
                    cidrMask: 21,
                    name: "Protected",
                    subnetType: SubnetType.ISOLATED,
                },
            ],
        });

Expected: vpcCidr.valueAsString passed to the cidr property of the ec2.Vpc construct should be the same as setting cidr: "cidr ip/netmask", as in the example above.
Actual: ${Token[TOKEN.72]} is not valid.
Looks like the following function in network-util.js is throwing the error
    /**
     * Converts a string IPv4 to a number
     *
     * takes an IP Address (e.g. 174.66.173.168) and converts to a number
     * (e.g 2923605416); currently only supports IPv4
     *
     * Uses the formula:
     * (first octet * 256³) + (second octet * 256²) + (third octet * 256) +
     * (fourth octet)
     *
     * @param  {string} the IP address (e.g. 174.66.173.168)
     * @returns {number} the integer value of the IP address (e.g 2923605416)
     */
    static ipToNum(ipAddress) {
        if (!this.validIp(ipAddress)) {
            throw new Error(`${ipAddress} is not valid`);
        }
        return ipAddress
            .split('.')
            .reduce((p, c, i) => p + parseInt(c, 10) * 256 ** (3 - i), 0);
    }

Environment:

*

*AWS CDK CLI Version: 1.3.0

  "dependencies": {
    "@aws-cdk/assert": "^1.2.0",
    "@aws-cdk/aws-ec2": "^1.2.0",
    "@aws-cdk/aws-ram": "^1.2.0",
    "@aws-cdk/core": "^1.2.0"
}

*

*OS: OSX Mojave

*Language: Typescript

A: Unfortunately, it seems like the ipToNum function needs to do some parsing and math on the CIDR to turn it into a number, so you it has to be a static (know at synth time) value. Sorry.


text: Q: Присвоение нескольких значений одному полю таблицы Я пытаюсь сделать учёбную базу данных аптеки в phpMyAdmin. У меня есть таблица Product, в нёй есть поле sctucture (varchar), которое отвечает за состав продукта. Так-же у меня есть таблица ингрединтов, которая состоит из двух полей: id(int) и имя ингредиента(varchar). Мне нужно, чтобы в поле structure можно было указать сразу несолько ингредиентов. Я прбовал соединить structure и name через внешний ключ, но тогда получалось указать лишь один ингредиент. Каким образом мне надо связать таблицы, чтобы всё работало так, как я хочу. Буду очень благодарен за подробный ответ.


text:
Q: Count of raster cells as variable in ArcGIS ModelBuilder? I want to use a cell count of an integer raster as a variable in Arcgis 10 ModelBuilder (and later in a python script), but can't seem to find how to access this information.
Is there a (python) function that will return a cell count for a particular value?
eg. something like
count([raster], value)?

Or how do I access the count column for a particular value in the raster table?

A: You could try to access it by reading the attribute table (assuming you have one; if you don't there is also a python function to create one).
# loop through attribute table
Rows = ARCPY.SearchCursor( shapefile )

SomeValue = 'Count' # or some other column header name
for row in Rows:
    val = row.getValue( SomeValue )
    print val


text:
Q: Perpage footmisc footref workaround Does anyone knows a way to have the same footref in different pages and always showing up per every new page? I am using footmisc package and I have tried it with the perpage option, but nothing seems to work.
\documentclass{scrbook}

\usepackage[paperwidth=100mm, paperheight=30mm]{geometry}

\usepackage{footmisc}

\begin{document}

Ab omni peccato,\footnote{libera nos, Jesu.\label{libera}}

Ab ira tua,\footref{libera}

\newpage

Ab insidiis diaboli,\footref{libera}

\end{document}


text:
Q: Can dark matter explain the unusual orbit of transnettunian objects? While we are struggling to find an hypothetical planet 9 to explain the unusual orbit of transnettunian objects, I was wondering if it could be just dark matter.
We know that the universe is mostly made of dark matter, since it interacts only with gravitational force and there is no evidence of another planet in our solar system, can't we just assume as more probable that these effects are caused by a cluster of dark matter?

A: Here is a link to an article from "News from Science" that conjectures that planet nine may actually be a small black hole with a large dark matter halo:  https://www.sciencemag.org/news/2019/09/planet-nine-may-actually-be-black-hole?utm_campaign=news_daily_2019-09-27&et_rid=17519419&et_cid=3006922
So, yes that is a possibility.  The link goes on to describe experimental searches underway for such an objct.


text:
Q: how to return to main activity? i have 4 activitys,and i want to move from the 4 activity to the main activity(the first one) when buttoon clicked.
i tried this code:
        Intent intent = new Intent(this, Menu.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

but it doesnt work,in the Logcat Appears to me the problem:"have you declared this activity in your AndroidManifest.xml?"
if i call other activity it works.
please help!
(sorry about the bad english ^_^)
the manifest:
 <activity
        android:name=".Menu"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="com.tooti.fast.MAINACTIVITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TimeMode_Choose"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="com.tooti.fast.TIMEMODE_CHOOSE" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TimeMode"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="com.tooti.fast.TIMEMODE" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

A: Change the name of Activity - Menu.class , as  android has already view named  Menu  android.view.Menu
So Give some other name to your activity and try.

A: There's a level of ambiguity there and you're probably confusing yourself, and Java.
Assuming that your Menu class is in fact declared in your manifest (Can you post that?), then ensure that your imports are accurate.
You'll be looking for:
import com.yourpackage.Menu
and not
android.R.Menu or android.View.Menu
EDIT: So now that you've posted your manifest, your code is wrong. You need:
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

A: Change the name of Activity - Menu.class with Other name and Register in Androidmanifest.xml
and try like
        Intent intent = new Intent(this, OthernewName.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);


text:
Q: Apache Phoenix - Count query returns more than 100k rows, but SELECT query does not return any row Using Apache Spark 3, I manipulated some CSV data, stored in a dataframe, with the intention of sending it to HBase.
The data is successfully sent using JavaHBaseContext's bulkPut() method.
However, in Apache Phoenix, using a plain SELECT query, I get the message 'No rows selected'.

When I run SELECT count(*) query, I get:

Meanwhile, HBase's shell allows to ensure the availability of data as expected.
What could be the problem?


text:
Q: FirebaseJob Dispatcher: How to specify the number of retries in job with RETRY_POLICY_EXPONENTIAL How to specify the number of retries in job with retry type RETRY_POLICY_EXPONENTIAL, below is my code
    val job: Job =dispatcher.newJobBuilder()
            .setTag("mytesttag")
            .setService(MyJobService::class.java)
            .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
            .build()

A: Got it, it can be done using FirebaseJobDispatcher instance, Like this
        var job = dispatcher.newJobBuilder()
                .setTag("mytesttag")
                .setService(MyJobService::class.java)
                .setRetryStrategy(dispatcher.newRetryStrategy(
                 RetryStrategy.RETRY_POLICY_EXPONENTIAL,30,300))
                .build()


text:
Q: renderIcon is not a function when using react-navigation v5 I want to add custom icons in my bottom tab navigator. However, whenever I try to use tabBarIcon, I have this error: renderIcon is not a function (in TabBarIcon.tsx line 40). Any ideas how I can resolve this error?
Here are my dependencies:
    "@react-navigation/bottom-tabs": "^5.8.0",
    "@react-navigation/material-bottom-tabs": "^5.2.16",
    "@react-navigation/material-top-tabs": "^5.2.16",
    "@react-navigation/native": "^5.7.3",
    "@react-navigation/stack": "^5.9.0",
    "expo": "~38.0.8",
    "expo-status-bar": "^1.0.2",
    "react": "~16.11.0",
    "react-dom": "~16.11.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",

And below is my code to make it:
const Tab = createBottomTabNavigator();

const TabBarIcon = (img_src) => {
  return (
    <Image
      style={{
        width: 22,
        height: 26.4,
      }}
      source={img_src}
    />
  );
};

const BottomTabNavigator = () => {
  return (
    <Tab.Navigator initialRouteName="MyNotes">
      <Tab.Screen
        name="MyNotes"
        component={MyNotes}
        options={{
          tabBarLabel: "Notes",
          tabBarIcon: TabBarIcon("../assets/notes.png"),
        }}
      />
      <Tab.Screen name="Feed" component={Feed} />
      <Tab.Screen name="Discover" component={Discover} />
      <Tab.Screen name="MyProfile" component={MyProfile} />
    </Tab.Navigator>
  );
};

export default BottomTabNavigator;

I also tried to replace TabBarIcon("../assets/notes.png") by  but had the same error.

A: render tabBarIcon like this..
import asset icons
import home_icon from './assets/images/home-icon.png';
import notification_icon from './assets/images/notification-icon.png';
import favourites_icon from './assets/images/favourites-icon.png';

for tabBarActive and inActive color
const tabActiveColor = '#030303';
const tabInActiveColor = '#666666';

rest of the tab implementation would be like this.
<Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let tabIcon = home_icon

if (route.name === 'Home') {
              tabIcon = home_icon;
            } else if (route.name === 'Notification') {
              tabIcon = notification_icon;
            } else if (route.name === 'Favourite') {
              tabIcon = favourites_icon;
            }
            // You can return any component that you like here!
            return (
              <Image
                source={tabIcon}
                resizeMode='contain'
                style={{
                  height: 30,
                  width: 30,
                  tintColor: focused ? tabActiveColor : tabInActiveColor,
                }}
              />
            );
          },
        })}
        tabBarOptions={{
          showLabel: false,
          style: { zIndex: 110 },
          safeAreaInset: { bottom: 'never' },
        }}
      >
        <Tab.Screen
          name='Home'
          component={this.HomeStackScreen}
          options={({ route }) => ({
            tabBarVisible: this.getTabBarVisible(route),
          })}
        />
<Tab.Screen name='Notification' component={NotificationModule} />

        <Tab.Screen name='Favourite' component={FavouriteModule} />

      </Tab.Navigator>


text:
Q: Control key auto pressed when using vim over SSH through cygwin I'm using cygwin and sometimes, when I am typing in vim on a file over ssh and I switch to a different window and minimize cygwin and then come back to cygwin sometime later, I get a problem.
The problem is that for some reason, my keyboard doesn't work normally anymore, and it appears that for some reason, it thinks that my Control key on my keyboard is always being pressed. I know this because when I press just the 'V' key on my keyboard, vim says it's in Visual Block mode, and when I just press the 'R' key, it tries to Redo any changes.
The bad thing is that this also means that I can't actually exit from vim because I can press the : key, but then pressing wq doesn't actually enter in the normal wq symbols because it's interpreting it as ctrl w, ctrl q.
The only way I can fix it is by closing the entire window and restarting cygwin, but this means I lose any unsaved work, which is annoying.
Note: This doesn't happen when I use vim locally in cygwin (not over SSH)
What is causing this problem?


text:
Q: uniform convergence and convergence of inverse function Let $f_n$ be a sequence of continuous function such that $f_n \rightarrow f$ uniformly on compact sets. In addition both $f_n$ and $f$ are continuous.
Then do we have $f^{-1}_n \rightarrow f^{-1}$ pointwise?
If so do we have uniform convergence?


text:
Q: How to do list expansion in sql.functions.struct? I want to be able to pass a n length list of column names to struct, but I don't want to have to hardcode every column into struct. List expansion doesn't seem to work with struct. Is there a way to do this?
I am on Spark 2.3.x, and I cannot upgrade (if this is a version issue) since this is a work cluster.
import org.apache.spark.sql.functions._
import org.apache.spark.sql.Column

def randomInt = scala.util.Random.nextInt(100)

val zipData = sc.parallelize(
  Seq.fill(10){(randomInt, randomInt, randomInt)}
).toDF("x", "y", "z")

val cols = Seq("x", "y", "z")
val mappedCols = cols.foldLeft(Seq[Column]())((x, c) => x :+ col(c).alias(c))

// this doesn't work
zipData.withColumn("zipped", struct(mappedCols.head, mappedCols.tail: _*)).show

// it seems only hard coding work
zipData.withColumn("zipped", struct(mappedCols(0), mappedCols(1)).show
zipData.withColumn("zipped", struct(col("x"), col("y")).show

A: Using .withColumn
zipData.withColumn("zipped",struct(mappedCols: _*)).show()
+---+---+---+------------+
|  x|  y|  z|      zipped|
+---+---+---+------------+
| 56| 46| 12|[56, 46, 12]|
| 80| 20| 20|[80, 20, 20]|
| 27| 82| 85|[27, 82, 85]|
| 89| 42| 45|[89, 42, 45]|
|  0| 75| 58| [0, 75, 58]|
| 97| 77| 54|[97, 77, 54]|
| 55| 32|  0| [55, 32, 0]|
| 82| 12| 97|[82, 12, 97]|
| 66| 82| 42|[66, 82, 42]|
| 61| 70| 95|[61, 70, 95]|
+---+---+---+------------+

Using .selectExpr
val mappedCols=zipData.columns.mkString("struct(",",",") as zipped")
zipData.selectExpr("*",mappedCols).show()
+---+---+---+------------+
|  x|  y|  z|      zipped|
+---+---+---+------------+
| 41| 41| 51|[41, 41, 51]|
| 41| 54| 19|[41, 54, 19]|
| 54| 48| 13|[54, 48, 13]|
| 12| 90| 95|[12, 90, 95]|
| 76| 21| 44|[76, 21, 44]|
|  7| 29| 33| [7, 29, 33]|
| 66| 10| 92|[66, 10, 92]|
| 82|  4| 19| [82, 4, 19]|
|  8| 38| 97| [8, 38, 97]|
| 71| 51| 18|[71, 51, 18]|
+---+---+---+------------+

Using .select
zipData.select(zipData.col("*"),struct(mappedCols: _*).alias("zipped")).show()
+---+---+---+------------+
|  x|  y|  z|      zipped|
+---+---+---+------------+
| 41| 41| 51|[41, 41, 51]|
| 41| 54| 19|[41, 54, 19]|
| 54| 48| 13|[54, 48, 13]|
| 12| 90| 95|[12, 90, 95]|
| 76| 21| 44|[76, 21, 44]|
|  7| 29| 33| [7, 29, 33]|
| 66| 10| 92|[66, 10, 92]|
| 82|  4| 19| [82, 4, 19]|
|  8| 38| 97| [8, 38, 97]|
| 71| 51| 18|[71, 51, 18]|
+---+---+---+------------+

A: From looking at the implementation on github, we can only expand the string names; that is, the following works
sql.functions
zipData.withColumn("zipped", struct(cols.head, cols.tail: _*)).show


text:
Q: Robinson arithmetic and its incompleteness Wikipedia in Italian has a sketch-of-proof that Robinson arithmetic is not complete, since commutativity of addition is undecidable. The sketch of proof creates a model that adds two elements, $a$ and $b$, to the usual natural numbers: then it goes on by defining
$\mathsf{S(a)=b}$
  $\mathsf{S(b)=a}$
  $\mathsf{\forall n\in N \; (a+n = a)}$
  $\mathsf{\forall n\in N \; (b+n = b)}$
  $\mathsf{\forall n\in N \; (n+a = b)}$
  $\mathsf{\forall n\in N \; (n+b = a)}$
  $\mathsf{a+a=b}$
  $\mathsf{b+b=a}$
  $\mathsf{a+b=a}$
  $\mathsf{b+a=b}$
and saying "we could also define multiplication, but it is useless, since we already have that  $\mathsf{b+a} \ne \mathsf{a+b}$". But I am not sure that the model may actually be extended to multiplication. I tried with
$\mathsf{a\times b=b}$
  $\mathsf{b\times b=a}$
  $\mathsf{b\times a=a}$
  $\mathsf{a\times a=b}$
  $\mathsf{\forall n\in N \; a\times n=b}$
  $\mathsf{\forall n\in N \; b\times n=a}$
[EDIT]: of course $\mathsf{ a\times 0 = b\times 0 =0}$
but I am stuck with $\mathsf{n\times a}$ and $\mathsf{n\times b}$; it seems to me that setting all of them to $\mathsf{a}$ should work, but I am not sure about it. Could someone help me?
P.S.: I read this question, and I understand that just a single element $\mathsf{a}$ may be added. But I'd prefer to have the implicit axiom that $\mathsf{\forall x  \; (S(x) \ne x)}$.

A: Long comment ...
See Peter Smith, An Introduction to Gödel's Theorems (1st ed 2007), page 56 :

Ch.8.4 $\mathsf Q$ [Robinson Arithmetic] is not complete

The counterexample assume two "rogue" elements $a,b$ such that :

$Sa = a$ and $Sb = b$.

In this way, Axioms 1 to 3 are satisfied.
Then :

re-interpret $\mathsf Q$'s function '+'. Suppose we take this to pick out addition*, where

$m+^∗ n = m+ n$ for any natural numbers $m, n$ in the domain, while

$a +^∗ n = a$ and $b +^∗ n = b$.

Further, for any $x$ (whether number or rogue element),

$x +^∗ a = b$ and $x +^∗ b = a$.

It is easily checked that interpreting '+' as addition* still makes Axioms 4 and 5 true. But by construction,

$0 +^∗ a \ne a$,

so this interpretation makes $∀x(0 + x = x)$ false.

Added
See John Burgess, Fixing Frege (2005), page 56 :

None of the usual associative, commutative, or distributive laws for addition and multiplication can be proved in $\mathsf Q$ nor can even the law $Sx \ne x$. As to this last point, a natural model of $\mathsf Q$ is provided (as Saul Kripke pointed out to the author) by the cardinal numbers, with $S(x)$ defined as $x+1$. For infinite cardinals we then have $Sx=x$.

A: As a footnote to Mauro's answer, the question is set in one of the exercise sheets for the Gödel book, and you'll find the answer spelt out in the solution sheet (for Qn2) here:
http://www.logicmatters.net/resources/pdfs/godelexercises/ArithWoInd_solutions.pdf

A: It looks like that ought to work -- all you need to check is whether the recursion equations for $\times$ are satisfied by your definitions when one or both free variables are instantiated to $\mathsf a$ or $\mathsf b$.
You could also choose to set $n\times \mathsf a = n\times \mathsf b = \mathsf b$; either choice will work.


text:
Q: How to get the name of the class from which a method call originates How do you get the name of the class from which a method call originates.
eg
Class Someclass{
 AnotherClass/methodname();
}

Class AnotherClass{
    function getNameOfOriginatingClass{
     //how do u achieve this?
      }
}

This question will help me solve this problem
How to get the class from which a request originates in codeignitor please check it and help me solve it
how do i let AnotherClass know that the request is coming from Someclass?

A: This will depend on your url but u can do something like this..
 function getNameOfOriginatingClass{
     $this->load->library('user_agent');
     $previous_url = $this->agent->referrer();
     $url_segments = explode($previous_url,'/');
     echo '
';print_r($url_segments);
 }

after printing this result u can see your link broken into parts in an array..
Normally the $url_segments[3] or $url_segments[4] will contain your previous function name  and previous one will contain previous class name depending upon your url.

A: Do you mean to get the parent class name ? Use
http://pl1.php.net/manual/en/function.get-parent-class.php
But the parent class has to be extended by child.

A: I don't know if this will be useful in case of CodeIgnitor as well, but in php there is a function called debug_backtrace() which can accomplish the task as follows:
class Animal {
    public function eat($food) {
        echo "Animal is eating : " . $food;
        $tree = new Tree();
        $tree->grow();
    }
}

class Tree {
    public function grow() {
        $bt = debug_backtrace();
        //var_dump($bt);
        echo "
";
        if (isset($bt[1]['object']))
            echo get_class($bt[1]['object']);
        echo "
Tree is growing";
    }
}

$animal = new Animal();
$animal->eat("Food");

Output:
Animal is eating : Food
Tree
Animal
Tree is growing

A: You could also pass the caller as an argument
<?php

Class AnotherClass{

    public function getNameOfOriginatingClass($object){
        echo get_class($object);
    }
}

Class Someclass{

    public function __construct(){
        $A = new AnotherClass();
        $A->getNameOfOriginatingClass($this);
    }

}

$C = new Someclass();


text:
Q: android login sqlite with username and password i'm working sqlite.i successfully create database and table.and also i can  register some new user.and also i wrote login function with username only
this is a part my code
public String getSinlgeEntry(String username) {
    Cursor cursor = db.query(usm_Users, null, " UserName=?",
            new String[] { username }, null, null, null);
    if (cursor.getCount() < 1) // UserName Not Exist
    {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String customername = cursor.getString(cursor
            .getColumnIndex("UserName"));

    cursor.close();
    return customername;
}

String username=namefild.getText().toString();

            String password=passwordfild.getText().toString();

            String storedusername=loginDataBaseAdapter.getSinlgeEntry(username);

            if(username.equals(storedusername))
            {
                Toast.makeText(MainActivity.this, "Congrats: Login Successfully", Toast.LENGTH_LONG).show();
                Intent ii=new Intent(MainActivity.this,Home.class);
                startActivity(ii);
            }
            else
                if(username.equals("")){
                    Toast.makeText(MainActivity.this, "Please Enter Your Password", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(MainActivity.this, "Password Incorrect", Toast.LENGTH_LONG).show();
                }
        }

i can check login only username.how i can write two parameters function witch would can check username and password together?
public String getSinlgeEntry(String username,String password) {
    Cursor cursor = db.query(usm_Users, null, " UserName=?",
            new String[] { username }, null, null, null);
    if (cursor.getCount() < 1) // UserName Not Exist
    {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String customername = cursor.getString(cursor
            .getColumnIndex("UserName"));

    cursor.close();
    return customername;
}

i must change something my Cursor .if anyone knows solution please help me

A: use double ? and send two parameter in array.
like:
Cursor cursor = db.query(usm_Users, null, " UserName=? and Password=?",
            new String[] { username,password }, null, null, null);

A: You can use the below function, this is more generic
public Boolean check_User_Pin_Number(String username, String password)
{
    SQLiteDatabase sql_Db = this.getReadableDatabase();

    // Setting up the cursor which points to the desired table
    Cursor cursor = sql_Db.rawQuery("SELECT * FROM " + usm_Users, null);

    Boolean records_Exist = false;

    // Checking if the table has values other than the header using the cursor
    if(cursor != null && cursor.getCount() > 0)
    {
        // Moving the cursor to the first row in the table
        cursor.moveToFirst();

        do
        {
            // Checking if the user name provided by the user exists in the database
            if(cursor.getString(cursor.getColumnIndex(NAME)).equals(username))
            {
                if(password.equals(cursor.getColumnIndex(PASSWORD))
                {
                      records_Exist = true;
                      break;
                }
            }

       }while(cursor.moveToNext()); // Moves to the next row
   };

    // Closing the cursor
    cursor.close();

    // Closing the database
    sql_Db.close();

   return records_Exist;
}


text:
Q: How to query firebase to retrieve the unique ID I'm querying data from Firebase using the following code :
var firebaseObj = new Firebase("https://example.firebaseio.com/Articles");

var sync = $firebase(firebaseObj);

$scope.articles = sync.$asArray();

which return the following data :
    [{
    "emailId": "ty@ty.com",
    "post": "fgh",
    "title": "hfgh"
}, {
    "emailId": "kj@hjgfh.com",
    "post": "HHHHHH",
    "title": "Hello"
}, {
    "emailId": "hkj@gmail.com",
    "post": "Big news",
    "title": "Today's news"
}]

Each of the returned entry under https://example.firebaseio.com/Articles has a unique ID which is missing from the returned result.
How to retrieve the unique ID.

A: Try the special $id property, the relative unique firebase key.


text:
Q: How to remove a cecil instruction I have this method:
public int Test()
{
    ExternalClass cls = new ExternalClass();
    return cls.ExternalMethod();
}

I need to change it using IL Injection so I can pass the type as parameter and remove the direct object creation, like this:
public int Test(ExternalClass cls)
{

    return cls.ExternalMethod();
}

I am able to add the additional parametr using <>.Parameters.Add(____) and generate the new Assembly.
The issue is that I am not able to remove the instruction for the new object creation. Below are the lines I used to remove that.
ILProcessor ilProcessor = <<MethodDefinition>>.Body.GetILProcessor();
ilProcessor.Remove(<<newobj instruction>>);

Once I tried to call the modified assembly method like below, it's throwing the error "Common Language Runtime detected an invalid program."
ExternalClass ext = new ExternalClass();
int i = prg1.Test(ext);

I know I may need to handle memory allocation related stuff, too. I would appreciate if anybody is able to provide additional steps to be implemented here.

A: You can't just remove the newobj instruction; you're left with an invalid program, as the runtime told you.  Here's roughly how the original method translates to IL:
public Int32 Test()
{
    .local ExternalClass 0;

    // ExternalClass cls = new ExternalClass();
    newobj class ExternalClass();
    stloc.0;

    // return cls.ExternalMethod();
    ldloc.0;
    callvirt Int32 class ExternalClass:ExternalMethod();
    ret;
}

If you remove only the newobj instruction then the stloc instruction will have nothing on the stack to store in the local.  You need to turn the method into this:
public Int32 Test(ExternalClass cls)
{
    // return cls.ExternalMethod();
    ldarg.1;
    callvirt Int32 class ExternalClass:ExternalMethod();
    ret;
}

So you need to do three things:

*

*Add the argument to the method signature,

*Remove everything up to and including the ldloc instruction.

*Insert a ldarg.1 instruction at the beginning of the method.

Optionally, you may also remove the ExternalClass local.  (This will be optimized away by the JIT-compiler, but will bloat the IL image.)


text:
Q: С первого не обрабатывается действие у UIDatePicker.countDownTimer Столкнулся с такой проблемой и ни на stackoverflow, ни в гугле не нашёл решения.
Я программно создаю UIDatePicker и задаю ему тип countDownTimer.
Так же вешаю ему действие на valueChanged. И проблема в том, что он воспроизводит это действие только со второго раза. Нашёл, что надо ему выставлять дату (setDate), но не помогло. Видел ещё извращения по типу размещения в viewDidLoad диспатчей, но это показалось странным.
Может кто-нибудь знает как это лечится, а то голову уже несколько часов ломаю и никак не могу найти решения :(
        var dateComp : DateComponents = DateComponents()
        dateComp.hour = 0
        dateComp.minute = 5
        let calendar : Calendar = Calendar(identifier: .gregorian)
        let date = calendar.date(from: dateComp)!

        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.countDownTimer
        datePickerView.minuteInterval = 5

        datePickerView.addTarget(self, action: #selector(ATLOneTaskVC.datePickerLogWorkValueChanged(_:)), for: UIControlEvents.valueChanged)
        datePickerView.setDate(date, animated: true)

        textField.inputView = datePickerView

Про такое составление даты прочитал на каком-то из советов и попробовал, но тоже не помогло :(

A: Как оказалось, это существующий баг. Есть радары. Широкая общественность предлагает такой воркэраунд: обернуть setDate в диспатч
class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

        var textField = UITextField(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
        self.view.addSubview(textField)

        var dateComp : DateComponents = DateComponents()
        dateComp.hour = 0
        dateComp.minute = 5
        let calendar : Calendar = Calendar(identifier: .gregorian)
        let date = calendar.date(from: dateComp)!

        let datePickerView:UIDatePicker = UIDatePicker()
        textField.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(process), for: UIControlEvents.valueChanged)
        datePickerView.datePickerMode = UIDatePickerMode.countDownTimer
        datePickerView.minuteInterval = 5
        let deadlineTime = DispatchTime.now() + .seconds(1)
        DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
            datePickerView.setDate(date, animated: true)
        }

    }

    func process() {
        print("process")
    }

}

A: Необходимо выставлять дату пикеру после его показа. Например, в случае с inputView для UITextField подпишитесь делегатом и обновляйте дату в методе
func textFieldDidBeginEditing(_ textField: UITextField)

Если же реализуете свой UIResponder, то обновляйте после вызова becomeFirstResponder()
Выставление даты в другой итерации RunLoop хак, фу :)


text:
Q: Why value_counts in one column of the dataset adds everything except one specific category (DDoS)? I have a dataset using three csv, and I need to know the unique values and their quantity in one specific column (Label), to plot later. It works perfectly until DDoS. I already check the raw data and everything is fine. How can I solve this issue?
dataset['Label'].value_counts()
Probe         98129
DDoS          73529
Normal        68424
DoS           53616
DDoS          48413
BFA            1405
Web-Attack      192
BOTNET          164
U2R              17
Name: Label, dtype: int64

A: It seems that they are different in way invisble to you, consider following snippet
import pandas as pd
labels = pd.Series(['DDoS','DDoS','DDoS','DDoS '])
print(labels.value_counts())

output
DDoS     3
DDoS     1
dtype: int64

It does look similar to your case, however when you do
print(labels.value_counts().index)

output
Index(['DDoS', 'DDoS '], dtype='object')

Situation is explained - there is DDoS and DDoS  (i.e. DDoS followed by space) which are different strings. If this is case you might use .str.strip as follows
dataset['Label'].str.strip().value_counts()

Note that it will remove any leading/trailing whitespaces (like \t), not only spaces.

A: Maybe the two DDoS values are not the same (a whitespace character somewhere?)
You can try to
dataset['Label'].str.strip().value_counts()


text:
Q: "Error loading plugin manager: TomcatGrailsPlugin" on Grails 2.3 Database Migration I use Grails 2.3 and the Grails database migration plugin (1.3.6).
When I do grails dbm-update I get the following error. How can I solve this error?
 Error Error loading plugin manager: TomcatGrailsPlugin (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
java.lang.ClassNotFoundException: TomcatGrailsPlugin
    at _GrailsBootstrap_groovy$_run_closure2.doCall(_GrailsBootstrap_groovy:40)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90)
    at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
    at _GrailsBootstrap_groovy$_run_closure6.doCall(_GrailsBootstrap_groovy:64)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90)
    at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantMetaClass.processClosure(GantMetaClass.java:81)
    at org.codehaus.gant.GantMetaClass.processArgument(GantMetaClass.java:95)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:128)
    at _DatabaseMigrationCommon_groovy$_run_closure1.doCall(_DatabaseMigrationCommon_groovy:25)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90)
    at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantMetaClass.processClosure(GantMetaClass.java:81)
    at org.codehaus.gant.GantMetaClass.processArgument(GantMetaClass.java:95)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:128)
    at DbmUpdate$_run_closure1.doCall(DbmUpdate:23)
    at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy)
    at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90)
    at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy:185)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:591)
    at gant.Gant.executeTargets(Gant.groovy:590)
| Error Error loading plugin manager: TomcatGrailsPlugin

A: Try change the tomcat build type in buildConfig.groovy to compile instead of build:
compile ':tomcat:7.0.42'

A: So if you are finding this because your scripts are broken by 2.3.x here is what I discovered about the problem in general.  I still can't use run-script because it always fails with the dreaded TomcatPlugin missing problem (I suspect this means run-script is always trying to bootstrap grails irregardless).  However, I can get the scripts to compile and run as tasks.  My scripts would always fail because I had bootstrapped grails using the following method:
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsClasspath")

target(main: "Generate a secret key to be used with HMAC and AES algorithms") {
   depends(bootstrap)  // this is problem
}

All of that is from the docs that say to do that.  However, depends(bootstrap) is broken badly in 2.3.x which is apart of the whole fork feature debacle (yes it was not well thought out).
Since I got so lucky and my scripts don't really have to fully bootstrap grails I could do the following and it worked just as well:
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsClasspath")

target(main: "Generate a secret key to be used with HMAC and AES algorithms") {
   depends(parseArguments)  // this is not problem
}

And viola it started working again.  Well working-ish.  Here is what works vs doesn't work:
$ grails GenerateSecretKey              // yay works
$ grails run-script GenerateSecretKey   // doesn't work

Here are some Jira issues about this problem(s) so you'll know when all of this is wrong ;-)

*

*http://jira.grails.org/browse/GRAILS-11216

*http://jira.grails.org/browse/GRAILS-11219

A: This is a super annoying bug.  My application depends on running scripts with run-script and I get the same behavior.  Here's what I did as a workaround:
plugins {
    ...
    // grails 2.3.2 and tomcat 7.0.42 cause scripts to not work :( Pass -DnoTomcat=true in the script args to fix this
    if (System.getProperty("noTomcat") == null) {
        build ":tomcat:7.0.42"
    }
}

Then when running your script:
 grails -DnoTomcat=true run-script scripts/MyScript.groovy

Annoying for sure, but at least you can use all the other latest features while awaiting a fix.

A: I'm on Grails 2.3.4, but here's how I fixed this problem:

*

*Upgraded to database migration 1.3.8

*Cleared my scriptCache folder

*Executed refresh-dependencies

Retried the database migration script, and the problem was resolved.

A: I had the same issue when upgrading to 2.3.2
I tried the above with the flag -DnoTomcat
It was still not working. Then I realised having some inplace plugins referencing tomcat as well. This seems to be legacy in some way, because freshly created plugins with grails 2.3.2 dont have references to tomcat. So I just removed all references from the plugins and kept the flag switch in my main application.

A: Just a slight clarification, which was mentioned aboveby chubbsondubs, but which I missed on first read...
Usually the simple answer to this is instead of doing:
grails run-script scripts/DoSomething

just do this:
grails do-something


text:
Q: Android Studio - Automotive emulator not found I would like to have possibility to launch automotive emulator via my AS. What should I do ?
Currently I have no such option.
My AVD manager, see categories.

Expected view

I can create the device tho, but it does not appear in the device definition list.

A: You have to enable automotive features in Android Studio.
Please follow the instructions from https://developer.android.com/training/cars/start, paragraph "Enable automotive features in Android Studio"

A: Follow the instructions here.
All you need is that line:
<entry key="npw.templates.automotive" value="true" />


text:
Q: iPhone app like Twitter design structure I'm new to iOS development and am working on this app that has a similar interface to the official Twitter app. However, I'm not sure how to organize the view controllers and the hierarchy, especially for UITabBar and UINavigationBar (which one is the parent controller?).
Can you guys point me to the right direction? I started from a blank window-based application project. A list of view controllers in the order of the hierarchy would be really helpful. Thank you.

A: Make the TabBar Controller your root controller. Then, in every tab where you need navigation, use Navigation Controller. It will add Navigation Bars, which you can then modify either in IB (where it applies), or programmatically.


text:
Q: Run server project in debug mode while testing client project Let's say I have Client and Server projects in one solution. I wrote Unit Test project to test Client but to execute tests I need to run Server in debug mode from Unit Test project. How to do that?

A: Unit tests usually test just one component (be that a class or a method) at one time. Seems like you are trying to do integration testing. In my opinion you should abstract the server away from the client so that you can focus on the client only. Or vice versa. With the direction you are currently going you'll probably end up with way too complicated tests that will fail for server and client errors.
If you do want to do the integration test then you could just spin up a server in a separate AppDomain and interact with it from your unit test code as you usually do. But like I said these kinds of tests are usually too complicated to be of any use and are very hard to maintain.
But you should provide more details on both the client and the server to get better answers. How do they interact, what are their roles?


text:
Q: How can I see the order of accuracy of an ODE method? Let's say I have solved an ODE with Euler's forward method, and also solved it using RK4, in both cases for varying decreasing step sizes $h$. Is there any way to look at the graphs and "see" the order of accuracy of the methods?

A: Yes, graph the differences of the results for stepsizes $h$ and $2h$ as double-logarithmic plot. The graph should be of lines, and the slopes correspond to the order of the method.

More precisely, the numerical result for step size $h$ is in first order of approximation
$$
y_h=y_*+C·h^p+D/h
$$
where $C$ accumulates the derivative factors for the method error and $D$ accounts for the floating point errors in the evaluation of every single step.
Thus the mentioned difference gives
$$
y_{2h}-y_h=(2^p-1)·C·h^p-D/(2h)
$$
so that for moderately small $h\gg \sqrt[p+1]{D/C}$ one gets
$$
\log(y_{2h}-y_h)\approx\log((2^p-1)·C)+p·\log(h)
$$


text:
Q: Examples of Struts2 applications I am working on a static analysis for detecting security vulnerabilities in web applications, and I am looking for some web applications to run my analysis on.
More specifically I am right now looking for open-source web applications that use the Struts2 framework, but I have a hard time finding such applications.
Does anyone know of some more or less complete and open-source web applications written using Struts2 (or possibly just plain JSP)?

A: Projects Using WebWork or Struts2
https://cwiki.apache.org/S2WIKI/projects-using-webwork-or-struts2.html

Others

*

*http://api.cnn.com/

*http://www.allhomes.com.au/

A: The very complete and stable Struts2 application i use for log file analysis is KonaKart. The advantage is that you can set it up on your server, including demo data and configure it and use it as you wish.
In terms of openness:
"Only the customizable parts of KonaKart are open source. These include the Struts action classes and
forms, the JSPs, the payment modules, order total modules, shipping modules and the GWT One Page
Checkout code. They are shipped under the GNU Lesser General Public License."
If you need 100% open source it is not for you.

A: Check these tutorials. there downloads are available. link1, link2


text:
Q: Cloudflare HTTP 502 every X clicks I wanted to give Laravel Vapor a try and deployed a simple project on a staging environment. Now I'm getting a HTTP 502 error every second or third request. With some URLs it seems to occur more often than with others but I can't find any problem with the app. It responds quickly and when I reload the URL the error is gone. It's reproducable though if I reload it another time or maybe a second time.
We are using the exact same app live on a "traditional" AWS setup and for dev/staging and VPS servers without ever getting any errors.
What I also don't get is why it's using Cloudflare with US IP addresses even though from the documentation I thought Amazon's CloudFront would be used. For various reasons we need the app to run on eu-central-1 with an IP address from that. Can I just get rid of Cloudflare somehow?
I'm using the vanity URL (something like https://snowy-cliff-XXXXXXX.vapor-farm-a1.com) provided by vapor, if that helps.
Thanks!


text:
Q: Xpath lxml obtain id of repeated subelement This is my abbreviated source for example.
<meeting>
    <race id="204091" number="1" nomnumber="4" division="0" name="FAIRFIELD RSL CLUB HANDICAP" mediumname="BM90" shortname="BM90" stage="Results" distance="1200" minweight="54" raisedweight="0" class="BM90      " age="3U        " grade="0" weightcondition="HCP       " trophy="0" owner="0" trainer="0" jockey="0" strapper="0" totalprize="85000" first="48750" second="16750" third="8350" fourth="4150" fifth="2000" time="2015-08-15T12:35:00" bonustype="BOB7      " nomsfee="0" acceptfee="0" trackcondition="Good 3    " timingmethod="Electronic" fastesttime="1-09.89   " sectionaltime="600/33.95 " formavailable="0" racebookprize="Of $85000. First $48750, second $16750, third $8350, fourth $4150, fifth $2000, sixth $1000, seventh $1000, eighth $1000, ninth $1000, tenth $1000">
    <race id="204092" number="2" nomnumber="5" division="0" name="DOOLEYS HANDICAP" mediumname="BM80" shortname="BM80" stage="Results" distance="1500" minweight="54" raisedweight="0" class="BM80      " age="3U        " grade="0" weightcondition="HCP       " trophy="0" owner="0" trainer="0" jockey="0" strapper="0" totalprize="85000" first="48750" second="16750" third="8350" fourth="4150" fifth="2000" time="2015-08-15T13:15:00" bonustype="BOB7      " nomsfee="0" acceptfee="0" trackcondition="Good 3    " timingmethod="Electronic" fastesttime="1-30.01   " sectionaltime="600/34.27 " formavailable="0" racebookprize="Of $85000. First $48750, second $16750, third $8350, fourth $4150, fifth $2000, sixth $1000, seventh $1000, eighth $1000, ninth $1000, tenth $1000">
    <race id="204093" number="3" nomnumber="2" division="0" name="CANTERBURY HURLSTONE PARK RSL CLUB SPRING PREVIEW" mediumname="SPRINGPREV" shortname="SPRINGPREV" stage="Results" distance="1400" minweight="54" raisedweight="0" class="~         " age="3U        " grade="0" weightcondition="HCP       " trophy="0" owner="0" trainer="0" jockey="0" strapper="0" totalprize="85000" first="48750" second="16750" third="8350" fourth="4150" fifth="2000" time="2015-08-15T13:50:00" bonustype="BOB7      " nomsfee="0" acceptfee="0" trackcondition="Good 3    " timingmethod="Electronic" fastesttime="1-24.61   " sectionaltime="600/33.06 " formavailable="0" racebookprize="Of $85000. First $48750, second $16750, third $8350, fourth $4150, fifth $2000, sixth $1000, seventh $1000, eighth $1000, ninth $1000, tenth $1000">
</meeting>

My code loops the correct number of times for each race element however it doesn't move the retrieval of the id to the next element. How I move the tree in relation to the loop?
from lxml import objectify, etree
from builtins import len

with open('20150815RHIL0.xml', 'r') as f:
    xml = f.read()
    root = objectify.fromstring(xml)

    #===========================================================================
    # print(root.tag)
    # print(root.attrib['date'], root.attrib['weather'])
    # print(root.race.attrib['id'])
    #===========================================================================

    for races in root.race.iter():
        print(root.race.attrib['id'])

A: You need to use the loop variable inside the loop. Replace:
for races in root.race.iter():
    print(root.race.attrib['id'])

with:
for race in root.race.iter():
    print(race.attrib['id'])

A: Just because you aren't getting the current object element being iterated, it should be:
root = objectify.fromstring(xml)

for race in root.meeting.iter('race'):
    print(race.get('id'))

Also, based on your xml fragment, root.race is not a valid path, it should be root.meeting.race. Since you want grab all race elements, thus: root.meeting.iter('race')


text:
Q: Salesforce - multiple pre production environments I am pretty new to Salesforce, just learning. My background is custom applications using Java. So I have two questions:
1) How can I have multiple pre-production environments in Salesforce - like dev, QA and UAT?
2) How can I apply the same configuration/code changes I applied in dev to QA and UAT (or how can I promote my changes from dev to QA and UAT)?

A: This is your staring point Application Lifecycle and Development Models which will help you to understand more about this topic in Salesforce. As for your questions, below are pointers, where you will find more details on the linked documentation for these topics.

1) How can I have multiple pre-production environments in Salesforce - like dev, QA and UAT?

In Salesforce you utilize Sandboxes or Scratch Orgs for these purposes. The number of sandboxes/scratch orgs depends on the edition of your Production instance.

2) How can I apply the same configuration/code changes I applied in dev to QA and UAT (or how can I promote my changes from dev to QA and UAT)?

You can do this using couple of different ways:

*

*Metadata deployments

*Change Sets

*Salesforce DX


text:
Q: Xampp css and images dont show When I start xampp server and open localhost/project/public/main.css I see only blank screen same for images. I dont get any errors in console. I tried todelete cache no change.
When I start server at htdocs/project with command php -S localhost:8000 and go to /public/main.css  I see css code any advice why I dont see code if I use xampp?


text:
Q: Why is my RoR link pointing to the wrong controller action? I have the following in my projects_controller.rb:
def destroy
    @project = Project.find_by_slug(params[:id])
    @project.destroy
    redirect_to projects_url
end

And I have the following in my routes.rb file:
delete "projects/:id", to: "projects#destroy", as: "destroy_project"

I have the following link (inside the show.html.erb file):
<%= link_to destroy_project_path(@project), method: :delete, class: "btn-gradient btn-red" do %>
    Delete Project
<% end %>

Upon clicking the button, the page reloads. The show action is called upon clicking the button. I've added console logs in each method, and it is clear that the destroy action is never called.
Can anyone point me in the right direction?

A: the link_to helper receives 2 different sets of hashes for the options.
The first set is for things like the http method, and the second for the html attributes (class, id and so on)
The way you wrote it, you probably have method=delete in your query params, which is wrong. You have to explicitly enclose the method: :delete within its own options hash:
<%= link_to destroy_project_path(@project), { method: :delete }, class: "btn-gradient btn-red" do %>
    Delete Project
<% end %>

A: If you use rails 7 with turbo framework you can try below for buttons.
<%= button_to "Delete this project", destroy_project_path(@project), method: :delete %>

Or you can try below for links.
 <%= link_to destroy_project_path(@project.id) ,  data: { turbo_method: :delete }  do %>
    Delete Project
 <% end %>

A: the problem that you are having is with the JS. there is a problem where something is not loading properly.
For testing try to remove your JS and use something like this
<%= javascript_include_tag "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" %>

When you get the delete method working, then you can debug where in your JS there is a problem.
at this time there is not sufficient info on your question to be able to know what it is.


text:
Q: While playing video with HTML5 video player, if user clicks on other link its taking time to load new page I am using following HTML5 code to play video
<video class="myvideoplr" autobuffer controls autoplay poster="abc.jpg">
  <source src="play_video.php?link=".$link?>" type="video/mp4">
</video>

Following is the code which I am using at server side(play_video.php) to push data to video player.
ob_get_clean();
    header("Content-Type: video/mp4");
    header("Cache-Control: max-age=2592000, public");
    header("Expires: ".gmdate('D, d M Y H:i:s', time()+2592000) . ' GMT');
    header("Last-Modified: ".gmdate('D, d M Y H:i:s', @filemtime($this->path)) . ' GMT' );
    $this->start = 0;
    $this->size  = filesize($this->path);
    $this->end   = $this->size - 1;
    header("Accept-Ranges: 0-".$this->end);

    if (isset($_SERVER['HTTP_RANGE'])) {

        $c_start = $this->start;
        $c_end = $this->end;

        list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
        if (strpos($range, ',') !== false) {
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $this->start-$this->end/$this->size");
            exit;
        }
        if ($range == '-') {
            $c_start = $this->size - substr($range, 1);
        }else{
            $range = explode('-', $range);
            $c_start = $range[0];

            $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $c_end;
        }
        $c_end = ($c_end > $this->end) ? $this->end : $c_end;
        if ($c_start > $c_end || $c_start > $this->size - 1 || $c_end >= $this->size) {
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $this->start-$this->end/$this->size");
            exit;
        }
        $this->start = $c_start;
        $this->end = $c_end;
        $length = $this->end - $this->start + 1;
        fseek($this->stream, $this->start);
        header('HTTP/1.1 206 Partial Content');
        header("Content-Length: ".$length);
        header("Content-Range: bytes $this->start-$this->end/".$this->size);
    }
    else
    {
        header("Content-Length: ".$this->size);
    }

Everything is working fine. But while video is playing if user clicks on any other link on site, its taking minutes to stop video and load the new page. What can be the issue and how can it be resolved?


text:
Q: Representation of modular group Theorem : The following are equivalent:
a. $ρ(Γ)$ is finite,
b. $\overline{ρ} (Γ)$ is finite,
c. $ρ$ has projective level $M \le5$,
d. $ρ$ is modular of level $N$.
[Taken from here, Proposition $3.2$, Page $5-6$ ]

Proof

Doubt : I have some doubts about the proof of $(a) \Rightarrow (c)$. I am concerned about the case when the image $\rho(\Gamma)$ is Dihedral. It's written that $T$ generates the commutator quotient of $\Gamma.$ Is it because the commutator quotient is cyclic of order $6$ in this case? (so $T$ is the only candidate in general)?
Then, $\rho(T)$ generates the commutator quotient of the image $\rho(\Gamma).$ Now how they are arguing that $\rho(T)$ has a projective level at most $4$? The commutator subgroup of the Dihedral group is a product of two cyclic groups of order $2.$ This shows that $\rho(T)^2$ in the commutator subgroup of $\Gamma,$ but why should $\rho(T)^4$ be trivial?


text:
Q: Does a surface in pygame contain more than it can show (load a 40x40 picture on a 20x20 surface)? If I load a picture of 40x40 pixels on a surface of 20x20 pixels. Does the surface contain all 40x40 pixels even tho it only shows 20x20?

A: Assuming you are using a code like this one:
src_surface = pygame.image.load('foo.png')  # size: 40x40px

dest_surf = pygame.Surface((20, 20))
dest_surf.blit(src_surf)

Your image will be blit like that:

In red is the image you want to blit, in black the Surface where the image will be blit.
To avoid losing the part of the source surface not in the destination surface, you can use pygame.transform.scale like that for example:
src_surf = pygame.image.load('foo.png')

width, height = src_surf.get_size()
width = int(width / 2)
height = int(height / 2)

dest_surf = pygame.transform.scale(src_surf, (width, height))