text:
Q: How to check if a radio button is checked but input box is empty in tkinter? I got this sort of edgy scenario I would like to accomplish in my tinkter app. The way my tinkter app would work is: a user needs to enter in some text. Then select a radio button option. Once a user selects the radio button option some value would be calculated. Now here is the edge case. Basically if a user were to select a radio option without entering a value I would like to show an error message "you need to enter a value into the input box" below the input box.
a snapshot of what I mean:

Here is what my code looks like:
from tkinter import *

class GetInterfaceValues():
    def __init__(self):
        self.root = Tk()
        self.totalValue = StringVar()

        self.root.geometry('900x500')
        self.RadioText = StringVar()

        self.getPeg = Button(self.root, text='calculate kegs values', command=self.findPeg)

        self.quarterlyTextString = 'Keg'
        self.yearlyTextString = 'parKeg'

        self.textInputBox = Text(self.root, relief=RIDGE, height=1, width=6, borderwidth=2)
        self.frequencyText = Label(self.root, text="Frequency")
        self.normalKegRadioButton = Radiobutton(self.root, text="normal Keg", variable=self.RadioText,
                                                value=self.quarterlyTextString, command=self.selectedRadioButtonOption)
        self.parRadioButton = Radiobutton(self.root, text="Par Kegs", variable=self.RadioText, value=self.yearlyTextString,
                                             command=self.selectedRadioButtonOption)
        self.clearButton = Button(self.root, text="Clear",command=self.clear)

        self.textInputBox.pack()
        self.normalKegRadioButton.pack()
        self.parRadioButton.pack()

        self.getPeg.pack()
        self.clearButton.pack()
        self.root.mainloop()

    def selectedRadioButtonOption(self):
        radioButtonFrequencyOption = self.RadioText.get()

        if(radioButtonFrequencyOption == self.quarterlyTextString):
            self.findPeg()
        if(radioButtonFrequencyOption == self.yearlyTextString):
            print(self.yearlyTextString)

    def getTextInput(self):
        result = self.textInputBox.get("1.0", "end")
        results = result.upper()
        results = results.rstrip()
        results = int(results)

        return results

    def clear(self):
        self.parRadioButton.deselect()
        self.normalKegRadioButton.deselect()
        self.textInputBox.delete("1.0", "end")

    def findPeg(self):
        userInput = self.getTextInput()

        lab = userInput * 15
        print(lab)

app = GetInterfaceValues()
app.mainloop()

A: You can test if a entry field contains text by using:
if len(entry.get()) > 0:

You can also invoke a function whenever a radiobutton (or entry) is changed using:
myradiobutton = Radiobutton(root, command = thefunction)

Additionally, you can programmatically deselect a radiobutton with:
myradiobutton.deselect()

if that helps.
Putting this together you could do something like this:
def getinput():
    if len(entry.get()) > 0:
        #do whatever you want to do with the input
    else:
        radiobutton.deselect()
        #display your "enter something" message

entry = Entry(root)
radiobutton = Radiobutton(root, text = "Click when done typing", command = getinput)
entry.pack()
radiobutton.pack()

Let me know if I'm missing the point here. :)


text:
Q: HTTP not being redirected to HTTPS for certain Routes I recently switched to using HTTPS on my server, I found some code online that forces all incoming requests to the server to use HTTPS:
<?php namespace App\Http\Auth\Middleware;

use Closure;

class HttpsProtocol {

    public function handle($request, Closure $next)
    {
        if (!$request->secure() && env('APP_ENV') === 'production') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }

}

And added \App\Http\Auth\Middleware\HttpsProtocol::class to my middleware.
However now I have the following route:
Route::controller('test', 'TestController');

And the following controller:
<?php namespace App\Http\FrontEnd\Controllers;

use App\Http\FrontEnd\Requests;
use App\Http\FrontEnd\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\FrontEnd\Requests\TestRequest;

use App\Commands\SendEmail, App\Commands\SendSMS;

use Auth, Input, DB, Session, Queue, Crypt;

class TestController extends Controller {

    public function postCheck()
    {
        //
    }

    public function postConfirm()
    {
        //
    }

}

Now that specific route won't work if I try to post to the following URL:
/test/confirm

It only works when I use https and I can't understand why or how to fix that.

A: You may want to check out this question/answer: Laravel 5 - htaccess HTTPS redirect on post routes doesn't work.
While that question deals with htaccess redirects, the principle is the same.
Basically, when a client accesses the http version of the URL, your code is responding with a 302 redirect to the client telling it to use the https URL. The client then makes a new request to the https URL, but it incorrectly uses a GET request and also drops the original POST data.
To resolve the issue of clients incorrectly changing the request method on redirects, they came up with a new redirect status code 307 that, when implemented, is specifically meant to redirect without modifying the request method. You can attempt to solve this issue by responding with a 307, but since it was introduced in HTTP/1.1, there is no guarantee the client will understand how to handle it.
To respond with a 307 redirect in your code:
return redirect()->secure($request->getRequestUri(), 307);

However, any workaround is actually just defeating the purpose of requiring HTTPS everywhere. If a client POSTs to a non-secure URL, the post data could already have been compromised. Your best bet is to actually just reject POST requests to non-secure URLs to make sure people don't think it is okay to POST to your non-secure URLs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No Such File or Directory using SQLite with Git Bash I am very new to SQLite3 (very new). I am following a tutorial on how to create a database using SQLite3, and I am trying to run it with Git Bash. When I enter the command cd /c/sqlite in Git Bash, however, I get the error "no such file or directory". I am using PyCharm, so my python file is in users>myname>pycharmprojects (if this has anything to do with it). I am very sorry if this is a simple solution, but I am just beginning.

A: I found the solution! So Git Bash was not recognizing sqlite3 because I didn't have sqlite in the proper file directory. So what I did was create a new folder in my C: directory (where Git Bash was looking), place my python file in that folder, and execute the following commands in Git Bash:
Amari@DESKTOP-myDesktop MINGW64 ~
$ pwd
/c/Users/amari

Amari@DESKTOP-myDesktop MINGW64 ~
$ cd /c/sqlite

And there it is! It worked!


text:
Q: Checkboxlist in asp.net core I'm very new in asp.net core. How to create checkbox list in asp.net core? As the example, the list displays the course and student can choose the course that they interest.

A: Here is a complete example of how to use checkboxes in ASP.NET MVC and ASP.NET Core
Model :
public class Student
    {
        public Student()
        {
            Courses = new HashSet<Course>();
        }
        [Key]
        public int Id { get; set; }

        [Required]
        [Display(Name = "Student Name")]
        public string Name { get; set; }

        public virtual ICollection<Course> Courses { get; set; }
    }

public class Course
    {
        public Course()
        {
            Students = new HashSet<Student>();
        }
        [Key]
        public int Id { get; set; }

        [Required]
        [Display(Name = "Course Name")]
        public string Name { get; set; }
        public virtual ICollection<Student> Students { get; set; }

    }

Controller:
    public class StudentsController : Controller
            {
                private readonly CheckBoxListDbConetxt _dbConetxt = new CheckBoxListDbConetxt();

        [HttpGet]
        public IActionResult CreateStudent()
                {

                    ViewBag.AllCourses = _dbConetxt.Courses.ToList();
                    return View();
                }

                // POST: Students/Create
                [HttpPost]
                [ValidateAntiForgeryToken]
                public IActionResult CreateStudent(Student student, List<int> selectedCourses)
                {
                    if (ModelState.IsValid)
                    {
                        if (selectedCourses != null)
                        {
                            foreach (var item in selectedCourses)
                            {
                                Course course = _dbConetxt.Courses.Find(item);
                                student.Courses.Add(course);
                            }
                        }

                        _dbConetxt.Students.Add(student);
                        _dbConetxt.SaveChanges();
                        return RedirectToAction("Index");
                    }

                    ViewBag.AllCourses = _dbConetxt.Courses.ToList();
                    return View(student);
                }
}

In View:

                Course

                    @{
                        var count = Enumerable.Count(ViewBag.AllCourses);
                        foreach (var item in ViewBag.AllCourses)
                        {
                            <input type="checkbox" name="selectedCourses" value="@item.Id" />
                            @item.Name
                            if (--count > 0)
                            {
                                @:|
                        }
                        }
                    }

A: To make the browser render a checkbox you need an  elements of type checkbox:
<input id="checkBox" name="checkbox" type="checkbox">

To create a list of checkbox items you simply render multiple of those elements.
Asp.net core simplifies this by allowing you to express your loop using the razor syntax. You can put the following in your cshtml file to render e.g. 10 checkbox items:
@for (int i = 0; i < 10; i++)
{
        <input type="checkbox" />

}

Finally you can make use of an Asp.net Tag Helper to further ease the creation of the required html.
The example assumes you have a model called Student which has a property IsEnrolled.
@model Student

@for (int i = 0; i < 10; i++)
{
        <input asp-for="IsEnrolled" />

}

Due to the use of the input tag helper (asp-for) the html which is rendered to browser automatically includes the id and name HTML attributes. What is more the tag helper automatically sets the type=checkbox by evaluating the underlying data type of the IsEnrolled property.

A:   <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        <asp:ListItem>Electronics</asp:ListItem>
        <asp:ListItem>Electricals</asp:ListItem>
        <asp:ListItem>Civil</asp:ListItem>
        <asp:ListItem>Mechanical</asp:ListItem>
    </asp:CheckBoxList>


text:
Q: Django uploadify Model Foreignkey Hi I'm relatively new to Django. I'm creating an application, that allows users to upload imagegallries:
the important part of my models looks like this:
class location(models.Model):
    name = models.CharField(max_length = 15)

class gallery(models.Model):
    location_id = models.ForeignKey(location)
    date = models.CharField(max_length = 15)

class Image(models.Model):
    location_id = models.ForeignKey(location)
    name = models.CharField(max_length=15)
    image = ImageField(upload_to='songs')

class AuthKey(models.Model):
    user = models.OneToOneField(User)
    key = models.CharField(max_length=60)

my view looks like this:
def myFileHandler(request):
    if request.method == 'POST':
        for field_name in request.FILES:
            loc = request.POST['location']
            date = request.POST['date']
            if location.objects.filter(name=str(loc)):
                for l in location.objects.filter(name=str(loc)):
                    id = l.id
            gal = gallery(location_id=1, date='12/23/2009')
            gal.save()
        return HttpResponse("ok", mimetype="text/plain")
    else:
        return render_to_response('gallery_upload.html', context_instance=RequestContext(request))

the additional post data (loc/date) is sent via uploadify. Everything works fine, but when i try to save the model "gal" it doesn't work. If I test it with the location model instead of the gallery model it works. If I delete the foreignkey from the gallery model it also works, so it seems to be a problem with the foreign key field. I hope one of you guys has a solution for this.

A: Use
gal = Gallery.objects.create(location=location, date='12/12/2012')

instead of
gal = gallery(location_id=1, date='12/23/2009')
gal.save()

You seem to get messed up with location_id filed which is not actually an ID but object.


text:
Q: making two scripts work together for a dropdown menu i have this HTML code

<select  onchange="calc()" class="shipping-method" id="shipping-method">
<option value="">-Choose a shipping method-</option>
<option selected="selected" value="1">normal shipping - $6.95</option>
<option value="2">Priority Shipping - $17.95</option>

</select>

    Subtotal:
    $97.00

    Shipping:
    $6.95

    Total:
    $103.95

the dropdown menu is at the bottom of a webpage, so i use the first script to to get the user to the top of the page after selecting one of the options and getting the total, but both scripts don't work together, i have to remove one of them for the other to work, how to make both scripts work together without any conflict, thanks.

A: Try sticking this:
function calc() {
var subtotal = parseFloat(document.getElementById("subtotal").innerHTML.substring(1));
var shipping = parseInt(document.getElementById("shipping-method").value);
if(shipping == 1) {
    var total = subtotal+6.95;
    document.getElementById("shipping").innerHTML = "$"+6.95;
} else {
    var total = subtotal+17.95;
    document.getElementById("shipping").innerHTML = "$"+17.95;
}
document.getElementById("total").innerHTML = "$"+total;
}

just before the function at the top:
window.onload = function(){
document.getElementById("shipping-method").onchange = function(){
    window.scrollTo(0, 0);
};

A: You are overriding the onchange function. If you want to do two things, then put them both in the onchange function, don't assign it twice.
Here is some example code (shorted for brevity).

<title>Example</title>

<select id="shipping-method"></select>

Note that I put the javascript at the bottom to avoid accessing an element that does not exist.


text:
Q: which server can host iOS push notification I cannot host my own server for iOS push notification because the router is limited by Admin.
I want to learn from scratch so I don't want to use Parse or quickblox. Where and how can I know which PHP hosting plan support iOS push notification? Is there any free hosting available?
From Apple, the server need to allow inbound and outbound TCP packets over port 2196. I don't think regular hosting plan will list out this information.
http://developer.apple.com/library/ios/#technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG41
When I learnt Android push notification, I can easily find a hosting plan with CURL. iOS is a bit demanding.

A: The port that you really need for sending push notifications is 2195. Even though the TCP packets are both inbound and outbound from your server, the connection is only outbound (you initiate the connection to Apple). Most web host providers won't have an issue with this.
Port 2196 is the feedback service, which you should implement, but it's optional. It's the same way, inbound and outbound TCP packets over port 2196, but you initiate the connection.
When a device registers with your server for push notifications by sending the device token, the device initiates the connection, and you have your choice of how to send the notification to the server. If you send it via HTTP (with NSURLConnection, for instance), any basic web server will do.
I implemented Easy APNS in only a couple hours and it works fine on my shared hosting environment at Dreamhost. You just need a basic LAMP stack (Linux, Apache, MySQL, PHP) and a downloaded copy of your APNS certificates. Easy APNS is all open source, so you can see how they're doing it.


text:
Q: ImagickPixel::__construct not implemented Imagick has been implemented for generating a QRcode when enabling MFA. When trying to visit the page to enable MFA this error appears:

500 ImagickPixel::__construct not implemented

Here is some more info:

*

*PHP 7.3 is in use

*php7.3-imagick has been installed

*Ubuntu 18.04 Server

*extension=imagick.so has been added to /etc/php/7.3/apache2/php.ini

*The apache server has been restarted after changes

*php7.3-fpm also has been restarted

*When running php -m | grep imagick imagick does appear

Thanks in advance!!

A: The issue has been resolved, Laravel upgrade fixed the error!


text:
Q: iPython Notebook Python 3 I always used iPython notebook with Python 2.7.6 on Mac OS X Yosemite. Now I have a notebook I only can use with Python 3. I installed Python 3.4.3 and tried to launch notebook with the command "ipython3 notebook", but this doesn't work... I also updated the iPython package with Canopy. Can anyone help me?

A: I just removed iPython from my Mac with Canopy and installed it again, now it works perfect!


text:
Q: Protractor e2e Testing ui grid For accessing grid objects in Angular JS, I am hoping to use the APIs provided at https://github.com/angular-ui/ui-grid.
But after going through the APIs, in https://github.com/angular-ui/ui-grid/blob/master/test/e2e/gridTestUtils.spec.js, for accessing a grid object, I need to know about Grid ID.

/**
  * Helper function for returning a grid element.
  * @param gridId Id of grid to return.
  *
  * @returns {ElementFinder|Grid}  Grid wrapped in an ElementFinder
  *
  * @example
  *

  *   var grid = gridTestUtils.getGrid( 'myGrid' ); //or internally
  *   var row = this.getGrid( gridId );
  *

  */
  getGrid: function( gridId ) {
    return element( by.id( gridId ) );
  },

But, in my Angular JS webapp, the ID is getting assigned to the grid dynamically at runtime.

<div role="grid" ui-grid-one-bind-id-grid="'grid-container'" class="ui-grid-render-container ng-isolate-scope ui-grid-render-container-body" ng-style="{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }" ui-grid-render-container="" container-id="'body'" col-container-name="'body'" row-container-name="'body'" bind-scroll-horizontal="true" bind-scroll-vertical="true" enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar" enable-vertical-scrollbar="grid.options.enableVerticalScrollbar" aria-multiselectable="false" id="1476870709232-grid-container" style="margin-left: 35px; margin-right: 0px;">

How to get the value of "id" of the grid in protractor test, to access the grid structure?


text:
Q: Show space, tab, CRLF characters in editor of Visual Studio Where are the settings to show a space, tab, paragraph, CRLF, etc. (extended) characters?

A: My problem was hitting CTRL+F and space
This marked all spaces brown. Spent 10 minutes to "turn it off" :P

A: Edit > Advanced > View White Space. The keyboard shortcut is CTRL+R, CTRL+W. The command is called Edit.ViewWhiteSpace.
It works in all Visual Studio versions at least since Visual Studio 2010, the current one being Visual Studio 2019 (at time of writing). In Visual Studio 2013, you can also use CTRL+E, S or CTRL+E, CTRL+S.
By default, end of line markers are not visualized. This functionality is provided by the End of the Line extension.

A: Display white space characters
Menu:
You can toggle the visibility of the white space characters from the menu:
Edit > Advanced > View White Space.
Button:
If you want to add the button to a toolbar, it is called Toggle Visual Space in the command category "Edit".
The actual command name is: Edit.ViewWhiteSpace.
Keyboard Shortcut:
In Visual Studio 2015, 2017 and 2019 the default keyboard shortcut still is CTRL+R, CTRL+W
Type one after the other.
All default shortcuts
End-of-line characters
Extension:
There is a minimal extension adding the displaying of end-of-line characters (LF and CR) to the visual white space mode, as you would expect. Additionally it supplies buttons and short-cuts to modify all line-endings in a document, or a selection.
VisualStudio gallery: End of the Line
Note: Since Visual Studio 2017 there is no option in the File-menu called Advanced Save Options. Changing the encoding and line-endings for a file can be done using Save File As ... and clicking the down-arrow on the right side of the save-button. This shows the option Save with Encoding. You'll be asked permission to overwrite the current file.

A: The correct shortcut is CTRL-R-W like you don't have to release CTRL button while pressing W. This worked for me in VS 2015

A: For those who are looking for a button toggle:
The name of this command is View white space in GUI menu (Edit -> Advanced -> View white space).

The name of this command in the Add command popup is Toggle Visual Space.

A: If you use Visual Studio Code => View => Render Whitespace
That's it!
For me this setting was on, but didn't work. I had to turn it off and on again and than it worked! So this is a bug in Visual Studio Code!
If you use Visual Studio 2022 you can change the display options for whitespace etc. in Tools => Options => Text Editor => General and select "View whitespace"

A: Edit -> Advanced -> View White Space or Ctrl+R,Ctrl+W for Visual Studio 2019

A: The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.
Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.

A: To see the CRLF you can try this extension: End of the Line
It works for VS2012+

A: For Visual Studio for mac, you can find it under Visual Studio -> Preferences -> Text Editor -> Markers and Rulers -> Show invisible characters
Please note you may need to restart Visual Studio for the changes to take effect

A: For completeness since I haven't seen it mentioned here, it is also in Options->Text Editor->General->View Whitespace.

A: In the actual version this Option ist under Editor: Render Whitespace


text:
Q: Как написать Trait для контроллера UserController.php, который вернет информацию о сотруднике по его id БД с таблицами users и users_roles я сообразил как создать но вот по поводу контролера и трейтов к нему в русском гугле я не нахожу

A: Трейтам в php без разницы какой глубокий смысл будет заложен в классе, к которому они применяются: будто контроллер, модель, и т.д. Применяют их для решения проблем одиночного наследования в php. При создании трейта для контроллера, по всей видимости, подчеркивается однообразность CRUD операций.
В Laravel метод, который детализирует сущность по id, называют show.
namespace App\Http\Controllers\Traits;

trait Crud
{
  // Модель для работы с БД.
  protected $model;

  // Шаблон зачастую совпадает с именем таблицы.
  // В данном случае шаблоны модели `User`
  // будут располагаться в поддиректории `users`.
  protected $template;

  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  protected function show(int $id)
  {
    // Получаем первый результат запроса, либо `404`.
    $entity = $this->model->findOrFail($id);

    // Динамически генерируем имя шаблона:
    // например, для файла `users/show.blade.php`
    return view($this->template.'.show', compact('entity'));
  }
}

Теперь данный трейт можно использовать в контроллере:
namespace App\Http\Controllers;

use App\User;

class UserController extends Controller
{
  // Подключаем наш трейт.
  use Traits\Crud;

  // Используя паттерн внедрения зависимостей
  // Dependency Injection:
  public function __construct(User $model)
  {
    // а) определим текущую модель;
    $this->model = $model;

    // б) получим таблицу, связанную с моделью.
    $this->template = $model->getTable();
  }
}


text:
Q: Which of the following are subspaces of the given real vector spaces? $$ B = \{(a, b, c) \in R^3:b \geq0\} \subseteq R^3$$
$$ C = \{(a - b, a+ b, 7a): a, b \in R\} \subseteq R^3$$
I know the steps to prove these are:
Let V be a vector space. A is a subset $W \subseteq V$ is a subspace of V if

*

*W is non-empty / must contain a zero vector

*W is closed under vector addition

*W is closed under scalar multiplication .

$$$$
Solving the first one:
$$u , v \in R^3  $$
$$ u, v \in B$$
$$ u = (u_1, u_2, u_3),v = (v_1, v_2, v_3) $$
$$ u_2, v_2 \geq 0$$
$$u_1 + v_1, u_1 + v_1,u_1 + v_1 \in R$$
$$\therefore (u_1 + v_1, u_1 + v_1, u_1 + v_1) \in R^3$$
$$(u_1 + v_1, u_1 + v_1, u_1 + v_1) = u + v$$
$$\therefore u + v \in B$$
Vector addition is closed
$$$$
$$$$
$$ \alpha u = (\alpha u_1,\alpha u_2,\alpha u_3), u_2 \geq0 $$
$$\alpha,u_1, u_2, u_3 \in R$$
$$\therefore \alpha u_1,\alpha u_2,\alpha u_3 \in R$$
$$\therefore (\alpha u_1,\alpha u_2,\alpha u_3) \in R$$
and so $\alpha u \in B$ and Scalar multiplication is closed
$$$$
I hope these are correct, but how do I do C?
From observation, shouldn't any vector $(a,b,c)$ where $a,b,c \in R$ always be in $R^3$, how come I need to do this?

A: Hints:
With $\;B\;$ check what happens with $\;\alpha=-1\;$ ...
For $\;C\;$ : do exactly as you did with $\;B\;$ . For example, addition:
$$(a-b,\,a+b,\,7a)+(\alpha-\beta,\,\alpha+\beta,\,7\alpha)=\left((a+\alpha)-(b+\beta),\,(a+\alpha)+(b+\beta), 7(a+\alpha)\right)$$
etc.


text:
Q: Displaying recent posts on static page with template-part via shortcode So, I'm taking my first shot at creating my own custom Wordpress theme with Underscores. I have everything straightened out, with the exception of one last thing I want to add.
I would like to add a latest/recent posts section to my front page. I know there's a lot of answers out there on how to do this, but I need to do it differently.
I noticed that the most common way is to create a static page template for the front page and and insert your own php code. This is the way everyone seems to suggest when someone asks. However, this won't work for me because of the way that I designed the site for the editors. The front page needs to be editable, so telling anyone to open up a php file and shift stuff around won't cut it. Instead, I've set it up so all front page can be changed through "edit page" in the admin panel. I have also created shortcodes for specific modules that allows the user to reflow the page without breaking the site. I want to do this same thing for recent posts, with a twist.
I came across a plugin called "display-posts" which seems to do what I describe, but not perfectly. This plugin creates a shortcode that shows any posts you want where you insert [display-posts]. What I don't like about this plugin is how it inserts the post using its own HTML fomatting, and not the same  code that is in the template's content.php.
I styled the post layout in content.php to be exactly as I want it to display on the blog page. I would like this same layout to be called in a shortcode on a static page where I want to display the recent posts. Essentially, I think want a shortcode that returns the main loop in index.php (which in turn does get_template_part), but limits to 3 posts.
I looking for others who wanted to do what I described, but I only came across about two people asking for something similar, and no solution. I made a brief attempt at creating my own shortcode but it only had the effect of looping the content of the static page itself, not the latest posts.
If anyone could help, it would be greatly appreciated. Since this is my first WordPress theme, I'm still a novice, and I don't have a ton of php experience as well. Enough to get by with basic things, but not enough to figure this out on my own.
Many thanks


text:
Q: Craps Game Simulation I am creating a craps game using javascript. I have pretty much everything working the way its supposed to be, just have to make a few minor adjustments, but the part I am stuck on is creating some type of type function, or possibly using the setTimeout(). I have a .wav file playing the sound of dice being rolled, but what I would like to do is have the text if the user won or lost appear after the sound of the dice being rolled(after the .wav file stops playing the dice rolling sound).

A: I don't think you can detect any event about the sound file ending.
You should play the sound, then start a setTimeout function with a hard-coded duration.
Eg:
setTimeout(diceRolled,3000); //these are millisecond -> 3 seconds wait

// ..........

function diceRolled(){
//do anything here
}

A: I would say the "correct" answer is to use html5 audio and bind to its various events - you can get the file's duration, detect if a sound has finished playing, get its current playback location, etc.
However, it's fairly complicated to use, and I wouldn't recommend it for this purpose or for starting javascripters.
http://html5doctor.com/html5-audio-the-state-of-play/
http://www.html5rocks.com/en/tutorials/webaudio/intro/


text:
Q: Website Error each time rebuild and upload to Server : Attempted to read or write protected memory My Server:
Window Server 2008 R2
IIS 7.5
Each time I edit code locally then upload it to the server, it gets an error:
Event code: 3005  Event message: An unhandled exception has occurred.  Event time: 7/4/2016 7:53:10 AM  Event time (UTC): 7/4/2016 12:53:10 AM  Event ID: d5bd5d3e12a14d1eabe43f91b5d3c7ef  Event sequence: 721307 Event occurrence: 704  Event detail code: 0    Application information:
    Application domain: /LM/W3SVC/30824/ROOT-4-131120555752900745
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\vhosts\xxxxxxxxx\httpdocs\
    Machine name: COLO1298    Process information:
    Process ID: 6932
    Process name: w3wp.exe
    Account name: COLO1298\IWAM_plesk(default)    Exception information:
    Exception type: AccessViolationException
    Exception message: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.    Request information:
    Request URL: http://xxxxxxxxx.com.vn/publish/form/RegisterForm.aspx
    Request path: /publish/form/RegisterForm.aspx
    User host address: 171.254.38.251
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: COLO1298\IWAM_plesk(default)    Thread information:
    Thread ID: 55
    Thread account name: COLO1298\IWAM_plesk(default)
    Is impersonating: False
    Stack trace:

at Microsoft.Win32.NativeMethods.CreateProcess(String lpApplicationName, StringBuilder lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes, Boolean bInheritHandles, Int32 dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION lpProcessInformation)
at System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at Microsoft.CSharp.CSharpCodeGenerator.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
 at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, String[] fileNames)    at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromFile(CompilerParameters options, String[] fileNames)
at System.Web.Compilation.AssemblyBuilder.Compile()
at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)    at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
 at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert)
at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

When I restart IIS, it's OK again.
I don't think the source code has a problem because when I upload it to another server, this doesn't happen.


text:
Q: Dual-boot archlinux and Windows 7 using grub-bios How can i add windows to the boot menu when using grub-bios. I couldn't find menu.lst file in my boot/grub directory. My bootloader is on /dev/sda1. Windows is on /dev/sda2, root and home are on /dev/sda3 and /dev/sda5

A: Here is the answer https://wiki.archlinux.org/index.php/Grub#With_Windows
Assuming Windows is in sda3 Add the following to /etc/grub.d/40_custom
# (2) Windows 7
menuentry "Windows 7" {
  set root=(hd0,3)
  chainloader (hd0,3)+1
}

Save and then run
grub-mkconfig -o /boot/grub/grub.cfg

A: Many distros now use grub2, which instead uses /boot/grub/grub.cfg.  However, they often recommend against manually editing this file, instead using the update-grub script.  If this is the case, simply installing os-prober should cause update-grub to automatically detect a Windows install and add it to the GRUB menu.


text:
Q: Angular dropdown switching from hard coded data to live data from service I have a Angular 5 dropdown that works fine with hard coded data, but I need to switch it to live data.  The problem is that the live data is plain array.
This is what currently works
HTML
<select...
  <option *ngFor="let activityType of activityTypes" [ngValue]="activityType.Id">
        {{activityType.Activity}}
  </option>

Typescript Component
activityTypes: any[];

this.activityTypes = [
        { Id: 1, Activity: "Select One" },
        { Id: 2, Activity: "Insert" },
        { Id: 2, Activity: "Update" },
        { Id: 3, Activity: "Delete" },
];

However, here is my issue, I'm pulling down data from a service and the data looks like this array
this.activityTypes v["INSERT", "UPDATE"]
                      0: "INSERT"
                      1: "UPDATE"

click to see dev tool image output
Now, how do I use the array to bind to the dropdown?
Clearly I would want to have values set as "0", "1" of the array .. then the DISPLAY ( which is my Activity in the hard coded example)  I would want it to hold "INSERT" and "UPDATE"  ...

A: You can use array index as value of option and data as label
<select...
  <option *ngFor="let activityType of activityTypes; let i = index" [ngValue]="i">
        {{activityType}}
  </option>

Solution2: You can create array of objects as:
this.activityTypes = this.activityTypes.map((currElement, index) => {
  let obj = {
    Id: index,
    Activity: currElement
  };
  return obj;
});


text:
Q: How to animate an attached property? I have a label in canvas. I want to animate the Canvas.Left of the label, but I don't known how to do it...
 DoubleAnimation Label_dx = new DoubleAnimation(150,60, new Duration(new TimeSpan(0, 0, 1)));

 label.BeginAnimation(???, Label_dx);

A: Try
label.BeginAnimation(Canvas.LeftProperty, Label_dx);

A: you can also use :
label.BeginAnimation(Canvas.LeftProperty, Label_dx);

or
TranslateTransform trans = new TranslateTransform();
label.RenderTransform = trans;
DoubleAnimation anim = new DoubleAnimation(150,60, new Duration(new TimeSpan(0, 0, 1));
trans.BeginAnimation(TranslateTransform.YProperty, anim);

The TranslateTransform is a specific kind of render transformation. Rather that changing properties of the control (such as the Left property), it simply affects how the control is displayed on the screen


text:
Q: Why teamviewer starts again after being killed My main desktop has Mint 14 and I approached it via SSH from another computer, because I didn't have a screen on the Mint one. Then I tried to start teamviewer just I order to launch its desktop session remotely. I started the teamviewer and everything ran fine, but then I tried to stop this application from the terminal and this is what happens:
Checking:
x@x-pc /opt/teamviewer8 $ ps -ef | grep team
root      1567     1  0 20:55 ?        00:00:00 /opt/teamviewer8/tv_bin/teamviewerd -f
x         2892     1  0 21:41 ?        00:00:00 /opt/teamviewer8/tv_bin/wine/bin/wineserver
x         2914  2822  0 21:48 pts/0    00:00:00 grep --colour=auto team

Using one-liner just to feel myself more hacker like :)
sudo for i in `ps -ef | grep team | awk {'print $2'} | xargs`; do kill -9 $i; done

Checking again:
x-pc teamviewer8 # ps -ef | grep team
root      3003     1  0 21:50 ?        00:00:00 /opt/teamviewer8/tv_bin/teamviewerd -f
root      3009  2957  0 21:50 pts/0    00:00:00 grep --colour=auto team

Killing again:
x-pc teamviewer8 # ps -ef | grep team
root      3003     1  0 21:50 ?        00:00:00 /opt/teamviewer8/tv_bin/teamviewerd -f
root      3011  2957  0 21:57 pts/0    00:00:00 grep --colour=auto team
x-pc teamviewer8 #
x-pc teamviewer8 #
x-pc teamviewer8 #
x-pc teamviewer8 #
x-pc teamviewer8 # kill -9 3003
x-pc teamviewer8 #
x-pc teamviewer8 #
x-pc teamviewer8 # ps -ef | grep team
root      3012     1  2 21:57 ?        00:00:00 /opt/teamviewer8/tv_bin/teamviewerd -f
root      3017  2957  0 21:57 pts/0    00:00:00 grep --colour=auto team
#########################################

No matter how many times I killed it, it receives new PID. How can I kill it?

A: Try to stop systemd service (if you use systemd):
# systemctl stop teamviewerd
# systemctl disable teamviewerd

A: If you do
teamviewer --daemon stop

you stop it once but it starts again upon next boot, but with
sudo update-rc.d teamviewerd remove

you also prevent it from starting itself on bootup

A: Try the following:
# teamviewer --daemon stop

A: To disable Teamviewer on startup :
teamviewer --daemon disable

A: I use Ubuntu 12.04, but I do not think the process will be different using other versions of Ubuntu.
TeamViewer screen sharing is my choice to replace the "TOO BLURRED TO READ" Skype screen share. The window sizes are about the same on my screen, but I can now read the print whereas the Skype blur makes reading impossible.
Please note that although TeamViewer runs under Wine, there are many native scripts that also run.
There has been some notice of the "TeamViewer remote control daemon" (teamviewerd) remaining active after the user is finished using and terminated TeamViewer. Respawning is also used to make sure it stays active.
The easiest solution is to reboot or logout after making sure the "start with system" check box is cleared. When you log in, TeamViewer should not start and the daemon should not appear.
If you want a solution that does not require logging out, you must delete the respawn commands from the configuration file.
In the terminal, enter:
gksudo gedit -s /etc/init/teamviewerd.conf

Delete the two lines:
respawn

respawn limit 5 60

Save the file. Do not worry about the teamviewerd.conf.bak file.
Now that respawn is disabled, ending the daemon will end it. I did not notice anything unusual in the way TeamViewer functions with the modified script.
Note: the changes will not initially take effect until TeamViewer reads the script. Reboot, log-out, or terminate and restart TeamViewer are options. I only tried log-out and it worked for me. I did not try the other options as I modified the script only once.


text:
Q: erb how to loop on array I can't simply loop on an array with ruby erb template system...
here is my template:
<% ['foo', 'bar'].each do |val| -%>
<%= val %>
<% end -%>

Here is the command line and the result
erb test.erb
/usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `eval': test.erb:1: syntax error, unexpected ';' (SyntaxError)
'foo', 'bar'].each do |val| -; _erbout.concat "\n"
                              ^
test.erb:3: syntax error, unexpected ';'
;  end -; _erbout.concat "\n"
         ^
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `result'
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:878:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:149:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:170:in `<main>'

What is wrong with this really simple example?
Disclaimer: I am a ruby and erb noob ^^

A: You're not supposed to have those "-" at the end beofre the "%".
<% ['foo', 'bar'].each do |val| %>
    <%= val %>
<% end %>

This should work.

A: You have to set trim mode to -:
$ erb -T - test.erb
foo
bar

From the man page:

-T mode   Specifies trim mode (default 0). mode can be one of
          0   EOL remains after the embedded ruby script is evaluated.
          1   EOL is removed if the line ends with %>.
          2   EOL is removed if the line starts with <% and ends with %>.
          -   EOL is removed if the line ends with -%>. And leading whitespaces
              are removed if the erb directive starts with <%-.


text:
Q: AEM DAM apect ratio crop DAM editing snapshot
I need to add some more fixed aspect ratio cropping shapes to my AEM 6 SP3 DAM editor (e.g. 4:3, 3:4, 9:16). There need to be a configuration option, but a cannot find something to customize this. Maybe someone of you guys have had the same problem as me and can tell me about the solution.

A: I found a way to solve this problem. If you want to have custom aspect ratio in your crop options drop down, you just need to overwrite the
/etc/clientlibs/granite/coralui2/optional/imageeditor/js/cui-imageeditor.js in your project. The options for the drop down are hardcoded in this js file. see custom crop options
The next problem will come with an update to AEM 6.1. The file cui-imageeditor.js wont exist anymore. Just a dummy file will appear in the same directory...
dummy file am 6.1


text:
Q: Не сортируются позиции в массиве Есть массив [#<ProductAttributeValue position: 5>,#<ProductAttributeValue position: 2>,#<ProductAttributeValue position: 4>,#<ProductAttributeValue position: 1>,#<ProductAttributeValue position: 3>]
ProductAttribute has_many ProductAttributeValue
Сделал кнопку, которая сортирует ProductAttributeValue по атрибуту position.
def sort_attributes
    ProductAttribute.all.map do |pa|
      a = ProductAttributeValue.where(product_attribute_id: pa.id).sort_by(&:position)
    end

    redirect_to product_attributes_path
end

Нажимаю кнопку, Код ничего не делает и в логах только
  ProductAttributeValue Load (0.5ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 1878
  ProductAttributeValue Load (0.5ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 1771
  ProductAttributeValue Load (0.5ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 2241
  ProductAttributeValue Load (0.5ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 2242
  ProductAttributeValue Load (0.6ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 2197

Хотя когда дебажжу, то вроде бы позиции меняются. т.е. получается массив с [#<ProductAttributeValue position: 1>,#<ProductAttributeValue position: 2>,#<ProductAttributeValue position: 3>,#<ProductAttributeValue position: 4>,#<ProductAttributeValue position: 5>]
Запрос должен быть примерно таким, но эквивалент в ruby не могу составить:
  ProductAttributeValue Load (0.9ms)  SELECT "product_attribute_values".* FROM "product_attribute_values" WHERE "product_attribute_values"."product_attribute_id" = 1651 ORDER BY "product_attribute_values"."position"
  SQL (44.9ms)  UPDATE "product_attribute_values" SET "position" = 0 WHERE "product_attribute_values"."id" = 7537
  SQL (9.2ms)  UPDATE "product_attribute_values" SET "position" = 1 WHERE "product_attribute_values"."id" = 7474
  SQL (9.3ms)  UPDATE "product_attribute_values" SET "position" = 2 WHERE "product_attribute_values"."id" = 7395
  SQL (9.1ms)  UPDATE "product_attribute_values" SET "position" = 3 WHERE "product_attribute_values"."id" = 7216
  SQL (9.5ms)  UPDATE "product_attribute_values" SET "position" = 4 WHERE "product_attribute_values"."id" = 7046

A: Для сортировки записей ActiveRecord можно использовать метод order
@sorted_values = ProductAttribute.first.product_attribute_values.order("product_attribute_values.position")

Далее результат выполнения запроса @sorted_values можно использовать в представлении.
Однако, в Вашем случае, выполнение метода redirect_to в конце приведенного примера выполнят переход на другой экшн, в котором, грубо говоря, результаты данной сортировки уже учитываться не будут...


text:
Q: False proof: Every continuous-time financial market has arbitrage. We know that many continuous-time financial markets do not have arbitrage. But I have created a proof which shows a very large class of them has arbitrage, so there must be a mistake in the proof. Could you please point out where the mistake(s) are?
Assume that you have a filtered probability space $(\Omega,\mathcal{A},P,\mathcal{F}_t)$. Let $S_t$ be a risky asset on the probability space and let $B_t$ be the bank process, we assume that $B_t$ is positive. We also assume that the filtration saitisfies the usual conditions, that means the $F_0$ contains all the null-events, and the filtration is right-continuous.
Look at the discounted process $\bar{S}_t=S_t/B_t.$ We assume that this process is not constant almost surely. If it was, then $S_t=C\cdot B_t$. This does not a strong assumption as we know there are continuous time markets where the discounted proess is not constant, but they still don't have arbitrage.
Define
$$F_t=\limsup\limits_{n \rightarrow \infty}\frac{\bar{S}_{t+1/n}-\bar{S}_t}{\frac{1}{n}},$$
and also define
$$f_t=\liminf\limits_{n \rightarrow \infty}\frac{\bar{S}_{t+1/n}-\bar{S}_t}{\frac{1}{n}}.$$
We must have that $F_t$ and $f_t$ are $\mathcal{F}_t$-measurable because the filtration is right continuous.
Now we create the arbitrage process like this:
If we observe that $F_t>0$ for a $t$ we know that in the immediate future the discounted price will rise. So we loan $1$ dollar from the bank and invest it in the stock. We will have $-1/B_t$ bank units and $1/S_t$ stocks. Since $F_t$ is positive there is an $y>t$ with $\bar{S}_y>\bar{S}_t$, at this time sell the stock and pay back the bank. In this case we have $S_y/B_y>S_t/B_t\rightarrow  1/S_t \cdot S_y >1/B_t\cdot B_y$. This last equation means that the number of stocks we have times todays stock value is larger than the number of bank units we loaned times todays bank unit. Hence we have gotten free money. Something similar can be done with $f_t$.
Do you see the error in the proof?

A: "If we observe that $F_t>0$ we know that in the immediate future the discounted price will rise."
This statement is wrong. Here is a counterexample:
Let the process be given by a Wiener process, $\bar{S}_t=W_t$. Now $F_t=\infty$ almost surely (see https://people.math.wisc.edu/~roch/grad-prob/gradprob-notes27.pdf). However, using the definition of a Wiener process $P(W_{t+h}-W_t>0| \mathcal{F}_t)=\frac{1}{2}$ for any $h>0$.
The Wiener process is well-known to be recurrent (https://en.wikipedia.org/wiki/Wiener_process), that is it reaches any point $y$ almost surely. Does this imply an arbitrage opportunity?
No. The definition of arbitrage requires that you find a self-financing strategy that cannot take negative values. If you buy the stock and sell the bond, your strategy has a positive probability of interim losses and hence is not an arbitrage strategy.
Would this still make an good investment strategy even though it is not arbitrage? Not necessarily. If you wait long enough till the process takes a positive value you have to accept that it may take an arbitrarily low value before that. This essentially requires infinitely high wealth.


text:
Q: Can I have more than one favicon.ico on my site? I have a favicon.ico in my root directory. This now shows up when people browse to my site. I notice that I can also use the following:
<link
rel="icon"
href="[URL]
type="image/x-icon"
/>
<link
rel="shortcut
icon" href="[URL]
type="image/x-icon"
/>

Is there any advantage in adding this to my master page?
Can I use this syntax to specify different favico's for different pages on my site?
Thanks,

A: You can do it. (One different per page). But IMHO is better to provide consistency.

*

*If you do that on your Master Page all the pages will share the same one (recommended).

*Yes, you can specify as many as you want BUT need to provides the respective header declaration on each page.


text:
Q: dojo 1.8: Remotely update content pane from other content pane by widgets Hi do you have any idea how I can update in content pane from other content pane remotely?
ie html update in one contentpane and change one part in other contentpane by ajax...
Are there any examples or tutorials for me.
Thanks
Clement

A: Let try this tutorial you might get an idea from it.
http://dojotoolkit.org/reference-guide/1.8/dijit/form/TextBox.html#getting-and-manipulating-the-value
Then let try more example about dijit/registry.
http://dojotoolkit.org/reference-guide/1.8/dijit/registry.html#dijit-registry


text:
Q: Get all lead ads form facebook API I am trying to get all lead generation forms in my PHP script using Facebook API version 9.0
I am making the request like this:
https://graph.facebook.com/v9.0/<PAGE_ID>/leadgen_forms?<access_token>

But its returning error, saying
{
   "error": {
      "message": "(#12) leadgen_forms field is deprecated for versions v5.0 and higher",
      "type": "OAuthException",
      "code": 12,
      "fbtrace_id": "ARMp3WCko2raN5521458h"
   }
}

If I change the version in the above request, it says:

You are calling a deprecated version of the Ads API. Please update to
the latest version: v9.0.

UPDATE:
Here's the SDK function which i am using to get Lead Generation Forms:
public function getLeadGenForms(array $fields = array('first_name', 'last_name'), array $params = array(), $pending = false) {
    $this->assureId();

    $param_types = array(
      'query' => 'string',
    );
    $enums = array(
    );

    $request = new ApiRequest(
      $this->api,
      $this->data['id'],
      RequestInterface::METHOD_GET,
      '/leadgen_forms',
      new LeadgenForm(),
      'EDGE',
      LeadgenForm::getFieldsEnum()->getValues(),
      new TypeChecker($param_types, $enums)
    );
    $request->addParams($params);
    $request->addFields($fields);
    return $pending ? $request : $request->execute();
  }

A: This is the correct GET request URL:
https://graph.facebook.com/v9.0/<PAGE_ID>/leadgen_forms?access_token=<page_access_token>

And example use of the FB PHP SDK:
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/<PAGE_ID>/leadgen_forms',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

Source: Generated from the Graph API Explorer.
Screenshot of a working error-free response:
Requirements:

*

*Use the page access token of the page <PAGE_ID> (not your own user token or any other page).

*Grant the pages_show_list, pages_read_engagement and pages_manage_ads permissions to the FB app that you connect to (to get the page access token).


text:
Q: Accessing form attributes in Django form I am trying to get django's generic FormView function to work. But can't figure out what's teh problem.
This is my form:
class JobCreateForm(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(widget=forms.Textarea)

def save(self, user):
    data = self.cleaned_data
    company = user.get_profile().get_company()

    # create job
    job = Job(title=data.title, description=data.description, company=company, user=user)
    job.save()

This is my view:
class JobCreate(FormView):

form_class = JobCreateForm
template_name = "jobs/create.html"

def form_valid(self, form):
    form.save(self.request.user)
    return super(JobCreate, self).form_valid(form)

and this is my template:
<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

When I try to do form.save(...), I get an error: 'dict' object has no attribute 'title'.
What's wrong there?

A: This is because self.cleaned_data is not an object but a dictionary. Eg. you can't access it by .(dot) notation.
You have to select it from dict like:
title = data['title']

or better way:
title = data.get('title',None)

which will try to obtain the title from dictionary and if it doesn't succeed, it will set the None to the title.

A: You need to change dict.title to dict['title']


text:
Q: Trying to use GPS for Ada and keep having problems trying to compile and run the code I am currently trying to run a program in GPS and this is my first time trying to use Ada and don't quite understand some things to it. I have some code that was told was supposed to run but can't seem to get it running. When I try to compile it or run the code, I keep getting an error message: "end of file expected. file can only be one compilation unit." I also included a photo to help show the problem. I'd appreciate any tips or hints on how to solve this please!
enter image description here

A: From the image, you seem to have a source file that contains both the declaration (or "spec", "specification") of a package named CircularQueue, and the body (the implementation) of that package. For the GNAT compiler and GPS such combined files are not supported. You should put the declaration of the package and the body of the package each into its own source file. In general, for GNAT/GPS each Ada "compilation unit" must be in its own source file. (This is also good for version control and to reduce unnecessary recompilations.)
The package declaration is the first part of your current file, from
generic
   ...
package CircularQueue is

to the first occurrence of
end CircularQueue;

That should be in its own file, which (by GNAT/GPS convention) should be called circularqueue.ads. The final "s" stands for "spec" or "specification".
The body of the package forms the rest of your current file, from
package body CircularQueue is

to the second (and last) occurrence of
end CircularQueue;

The body should be in its own file, which (by GNAT/GPS convention) should be called circularqueue.adb. The final "b" stands for "body".
The first line of your current source file is a so-called "context clause" and says that your code will use the predefined package Ada.Text_IO. Such context clauses should be put at the start of the spec file and/or the body file, depending on which file needs it. In this case, the spec does not refer to Ada.Text_IO, but the body does, so this context clause should be at the start of the body file (circularqueue.adb).
HTH

A: If you use GNAT Studio the very first time, then I suggest you to spend a few minutes by reading the tutorial.


text:
Q: What is this group called? Let $X$ denote a set. There's a corresponding group obtained by taking the group freely generated by $X^2$ and then quotienting out by the following families of relations:

*

*$(x,x) = 1$

*$(x,y)(y,z) = (x,z)$

*$(x,y)(y,x) = 1$

*For each quadruple $(x,y,x',y')$ such that $\{x,y\} \cap \{x',y'\} = \emptyset$, we have:
$$(x,y)(x',y') = (x',y')(x,y)$$

Question. What is this group called?

My motivation for considering this group is that it acts on the set $(\{0,1\}^\mathbb{N})^X,$ of $X$-many binary streams, by interpreting $(x,y)$ as the act of taking the first digit of stream $x$, removing it from $x$, and appending it to the beginning of $y$. Each of the four families above can be explained in these terms; for example $(x,x)=1$ is saying that if I take the first digit of stream $x$, and put it back on stream $x$, nothing changes.

A: Not a complete answer, but too long for a comment:
The group you described has a neat equivalent characterization:
It can be described by the presentation $\langle a_1, a_2, ... , a_{|X| - 1}| [a_i, a_j] = [a_k, a_j] \forall i \neq j, j \neq k, k \neq i\rangle$
Proof:
Suppose, $X = \{0, ... , n\}$ ($|X| = n + 1$). Let's define $a_i := (0, i)$. That results in $(i, 0)$ being equal to $a_i^{-1}$ and for $i \neq j, j \neq 0, i \neq 0$ $(i, j) = a_i^{-1}a_j$. Now this change of notation already covers the first three rules, making them redundant.
Now, let's deal with the fourth rule. Without the loss of generality we can assume that one of the following cases takes place:
1)$x' = 0$, $x, y$ and $y' = z$ are pairwise distinct and non-zero. Then $(0, z)(x, y) = (x, y)(0, y')$, which turns into $a_{z}a_{x}^{-1}a_y = a_{x}^{-1}a_{y}a_{z}$ which results in $a_ya_za_y^{-1} = a_xa_za_{x}^{-1}$, or equivalently $[a_y, a_z] = [a_x, a_z]$
2)$x, y, x' = z$ and $y' = t$ are pairwise distinct and non-zero. Then $(x, y)(z, t)=(z, t)(x, y)$ turns into $a_x^{-1}a_ya_z^{-1}a_t = a_z^{-1}a_ta_{x}^{-1}a_y$ which is $(a_ya_z^{-1}a_y^{-1})(a_ya_ta_y^{-1})=(a_xa_z^{-1}a_x^{-1})(a_xa_ta_x^{-1})$ which is a direct corollary of case 1
Thus $[a_y, a_z] = [a_x, a_z]$ for all distinct $x$, $y$ and $z$ are the only non-trivial relations required.


text:
Q: Weird pdfLaTeX+babel+color bug, Missing = inserted for \ifnum I let the MWE speak for itself.
\documentclass{minimal}
% remove babel and it works
% remove one language and it works
% reorder the languages and it works
\usepackage[italian,spanish,UKenglish]{babel}
% remove the color package and it works
\usepackage{color}
\begin{document}
hi
\end{document}

which outputs

This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013/Debian)

...
(/usr/share/texlive/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
! Missing = inserted for \ifnum.
<to be read again>
                   \let
l.400 \newcount\nofMPsegments

A: The problem is in the fact that babel-spanish, by default, makes < as a shorthand character and with certain combinations of languages this ends with this strange error that is surely due to this fact. The complete error message if one enables more \errorcontextlines is
! Missing = inserted for \ifnum.
<to be read again>
                   \let
\protect ->\let
                \protect \@@mpstopdf@@protect \let \unprotect \@@mpstopdf@@u...

\active@prefix ...tect \noexpand #1\else \protect
                                                  #1\fi \expandafter \@gobbl...

<->\active@prefix <
                   \normal@char<
\alloc@ #1#2#3#4#5->\ifnum \count 1#1<
                                      #4\allocationnumber \count 1#1 \global...
l.400 \newcount\nofMPsegments

It's not very clear why loading italian before spanish produces the error and it's quite unclear why \usepackage[italian,spanish]{babel} doesn't stop.
However, calling the languages in a different order "fixes" the issue:
\usepackage[spanish,italian,UKenglish]{babel}

Alternatively, load etex just after the \documentclass lines.
What happens is that etoolbox is loaded at the wrong time, but there doesn't seem a better place for calling it from italian.ldf (apart not loading it in the first place).

A: This is a complement to egreg's answer
The source of the problem is that etoolbox hence etex will be loaded at a time where < is active. This is not completely catastrophic though, because even with < active, it might well expand to a catcode 12 < hence could work ok in \ifnum tests. However when package color is loaded and used with driver pdftex it then loads support file supp-pdf.mkii for MPS to PDF conversion. This file temporarily modifies the definition of \protect. And the active < then gives something unacceptable to \ifnum.
With only \usepackage[italian,spanish]{babel} and without color there is thus no error.
For some reason spanish.ldf temporarily makes makes < and > active during the time it is loaded by babel at the very end of spanish.ldf. This activity is cancelled for the rest of the preamble until \AtBeginDocument by code executed immediately after babel.sty is loaded. In the order \usepackage[spanish, italian]{babel} the loading of etoolbox which was demanded by italian.ldf at the end of package Babel is thus executed after the code, also at end of package Babel, which resets to unactive the catcodes of the activated characters by spanish (edit: activated at the very end of spanish.ldf itself).
In the order of \usepackage[italian,spanish]{babel} the end of package Babel demands of italian (which include the loading of package etoolbox hence also of package etex) are executed before those of spanish. As a result this is done at a time where < is active. Hence etex definition of \alloc@ is done with an active <. This is recipe for disaster although as seen above in some circumstances it may remain hidden, becasue the active < still will extend to a catcode 12 <.
I do not know enough the innards of Babel, but it appears to me that spanish.ldf should not demand to Babel to reset the catcodes of < and > at the end of loading of babel.sty [snip] but do it him/herself at the end of spanish.ldf...
in fact I am not sure spanish.ldf makes any explicit demand of this type what I see is that

*

*it demands to Babel to activate < and >,

*then it immediately resets the catcodes to 12,

*then at the very last command of spanish.ldf one sees it re-activates < and >.

Babel by default I think resets to 12 the catcodes for the rest of the preamble when the activation was done properly (I do not investigate more, but I tested it in the case of spanish by itself).
Thus, I recommend this issue should be raised to the spanish.ldf and babel.sty maintainers. In fact, it would seem that the \csname activatequoting\endcsname at the end of spanish.ldf might be a bug (perhaps should be from what I understand only \let\es@quoting\activatequoting but not do \shorthandon{<>} ?), as anyhow Babel resets for the rest of the preamble the catcodes to 12.


text:
Q: How to give variable in css by using jquery? Usually using jquery we ll give css as like this
$("p").css("margin", "20px");

In my project i have code like this
var descMargin = productImage + productName + 26;
$(".product-compare-modal__grid--label").css("margin-top",descMargin);});

store it in a variable and giving.
here we are not mentioning any "px" or "%"
Is this the correct method of using? or I need to change?

A:
Is this the correct method of using?

It's fine if your descMargin is meant to be in pixels (not % or em or rem or ...), and if it's actually a number (I'm guessing from your code snippet that it is).
If you just use a number, jQuery converts it to a string and appends px for you. From the documentation:

When a number is passed as the value, jQuery will convert it to a string and add px to the end of that string. If the property requires units other than px, convert the value to a string and add the appropriate units before calling the method.

What you don't want to do is pass it a string that's all digits. So don't give it "26", for instance; but 26 is fine.
So:
// This:
$("p").css("margin", 20);
// Does the same thing as this:
$("p").css("margin", "20px");
// But DON'T do this:
$("p").css("margin", "20"); // <== Wrong

Live Example:

var div = $("div");
test("50px");
setTimeout(test.bind(null, 40), 300);
setTimeout(test.bind(null, "30"), 600);

function test(value) {
  var rawValue = String(value).replace(/\D/g, '');
  var rawPadding;
  var result;

  div.css("padding-left", value);
  var result = div.css("padding-left").replace(/\D/g, '') == rawValue ? "worked" : "failed";
  $("
")
    .html("Result for " + JSON.stringify(value) + ": " + result)
    .appendTo(document.body);
}

text

A:
As i know that the by default when you pass value using the .css()
  that value will be taken as the "px" you want change the measure
  unit to the css  property you need to give it manually.

this the way how you can give it manually

var descMargin = productImage + productName + 26;

$(".product-compare-modal__grid--label").css("margin-top",descMargin + "px");

$(".product-compare-modal__grid--label").css("margin-top",descMargin + "%");

$(".product-compare-modal__grid--label").css("margin-top",descMargin + "em" );

$(".product-compare-modal__grid--label").css("margin-top",descMargin + "pt" );

and here is the unit list you can apply
CSS units's list


text:
Q: Bixolon SPP-R200 command to scroll to black mark I have a Bixolon SPP-R200 (and an SPP-R200III). I've set the printer to Label Mode. I'm able to print using Standard Mode and the user can move to the top of the next ticket by pressing the feed button on the printer.
Is there a command I can send (via Bluetooth) to do this on behalf of the user? I can send LF - but this behaves as expected, moving the paper by one line height.
According to an ESC POS document I found online, GS FF would be what I want. But that's not a command available to the R200 or the Mark III.
Is there anything else I can do?


text:
Q: Unforceable statements in ZFC How can I determine that some particular sentence (consistent with ZFC) $\phi$ cannot be forced within a model $M$ of ZFC for no notion of forcing $P$ ? Is there a procedure that works for most of the time ? What are natural examples of such $\phi$'s ?

A: Shoenfield Absoluteness Theorem says that $\Sigma^1_2$ and $\Pi^1_2$ sentences are absolute, so you cannot force them. An example is the Riemann hypotesis, which can be written as a $\Pi^1_2$ sentence, so you can't force it to be true.

A: You cannot force that $V=L$.
If no large cardinals exist in an inner model, then you cannot force the existence of large cardinals. Although it is possible to "resurrect" large cardinal axioms in some cases, this usually requires them to hold in an inner model (there are some caveats here, of course, we say that $\kappa$ is "Blargh" if $V_\kappa\neq L_\kappa$ and $\kappa$ is strongly inaccessible; then starting from an inaccessible cardinal we can always force the existence of a "Blargh" cardinal; but these sort of counterexamples are artificial).
Some large cardinal axioms are upwards absolute, e.g. the existence of $0^\#$, and we know that there is no (set) forcing that adds $0^\#$ to a model. So if it does not exist, then it will not exist in a generic extension. Similarly, if $0^\#$ does exist, then it will always exist further on, and so cannot be forced to not exist.
More generally, "smallness statements" about canonical inner models, like $0^\#$ or other sharps (which can be understood as "The universe is significantly larger than the canonical inner model in question), cannot be forced into inexistence once they exist, since the canonical inner models are more-or-less-by-definition are robust under generic extensions (there are some caveats, but they are not relevant to this context). At the very least this is true below Woodin cardinals.
Any statement that will ostensibly add ordinals (e.g. change $\omega$ by adding non-standard integers; add ordinals on top of the universe; add non-standard ordinals in between the existing ordinals) will also not be forceable, since forcing does not add new ordinals.


text:
Q: Using data-attr to identify an active selection I'll try to keep it at simple as I can.
I have a JSON object that is pulled via AJAX. I am displaying a list of icons in a main div from the data dynamically which can be toggled on or off.
I have a secondary div where the selected items are appearing, while the main div icon receives a class of active.
I want the end user to be able to remove any of them by clicking on them on either the main div or secondary div.
Most of this is working, but I'm having trouble figuring out the best way to map them together so that I have 2 separate click events which can control the same outcome.
I think it may have something to do with the fact that I'm dynamically creating elements... which create more elements... which have to alter the initial elements.
My structure so far is to map the current selection inside of an array. This gives me control over keeping a code-based list of everything that is selected (there is much more data than in the example I'll be providing).
So, here is how I have it so far:
HTML:

Javascript/jQuery:
// Simple simulated AJAX data
var ourData = {
  "color1": "yellow",
  "color2": "blue"
};
var $options = $('#options');
var $selectedOptions = $('#selectedOptions');
// Array to keep track of which objects are selected
var selectedOptions = [];

// Makes the initial option dynamic list
makeOptions(ourData, $options);

// If an option from the main div is clicked, handle class changing
$('button').on('click', function(){
    pickOption($(this));
});

/* This function is the problem. The option gets removed from the array, and from the secondary div, but the class of active still occurs on the main div. */
$selectedOptions.on('click', '.optionActive', function(){
  var option = $(this).data('color');
  var optionPosition = jQuery.inArray(option, selectedOptions);
  selectedOptions.splice(optionPosition, 1);
  displayOptions(selectedOptions, $selectedOptions);
});

// Creates initial icons (buttons in this case) to the DOM and applies a data-attribute for the color
function makeOptions(options, $container){
    var $results = $('
');
  $.each(options, function(key, value){
    var $optionButton = $('<button>' + key + ':' + value + '</button>');
    $optionButton.data('color', value);
    $results.append($optionButton);
  });
  $container.append($results);
}

/* Handler for selecting an option from the Main Div. Handling the class active.
I am not using a simple classToggle because there are many situations where a click is not allowed */
function pickOption($option){
  var selectedOption = $option.data('color');
  // If the option returns true, or that it doesn't exist yet
  if(modifyOptions(selectedOption, selectedOptions)){
    $option.addClass('active');
  } else {
    $option.removeClass('active');
  }
  // Recreate our current selected options
  displayOptions(selectedOptions, $selectedOptions);
}

/* Searches array to see if the option exists. Returns true or false and either pushes or splices the option from the array */
function modifyOptions(option){
  var optionPosition = jQuery.inArray(option, selectedOptions);
  if(optionPosition == -1){
    selectedOptions.push(option);
    return true;
  } else {
    selectedOptions.splice(optionPosition, 1);
    return false;
  }
}

/* Displays all currently selected options that exist in our array */
function displayOptions(selectedOptions, $container){
  $container.empty();
  $.each(selectedOptions, function(option, value){
    var $optionTile = $('
');
    $optionTile.data('color', value)
                          .text(option + ":" + value)
                .css('background', value);
    $container.append($optionTile);
  });
}

So, to summarize, I want some some way to remove the .active class from the main div equivalent element when the item from the second div is clicked.
I tried removing the class active by searching for any elements with the data-color=data-color of the selected item, but I couldn't get that to work.
ex:
$('*[data-color="' + $(this).data('color') + '"]').removeClass('active');

I would really like some data approach to this, such as removing the class active if it had data-color="yellow" for instance.
Playground:
https://jsfiddle.net/c75xcLha/
EDIT:
Both Are Selected, working as designed:

Clicked Yellow Div. Yellow Button is still active:

Should remove the active class from the button when the yellow div OR the button is pressed, as shown here:

A: You are assigning data-* property using .data(PROP), not attribute hence element having data-* property could not be accessed/selected using attribute-selector, assign attribute using .attr('data-color') instead of .data(property)

Attribute Equals Selector [name="value"], Selects elements that have the specified attribute with a value exactly equal to a certain value.
.data( key, value ), Store arbitrary data associated with the matched elements.

When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute[Ref]

// Simple simulated AJAX data
var ourData = {
  "color1": "yellow",
  "color2": "blue"
};
var $options = $('#options');
var $selectedOptions = $('#selectedOptions');
// Array to keep track of which objects are selected
var selectedOptions = [];

// Makes the initial option dynamic list
makeOptions(ourData, $options);

// If an option from the main div is clicked, handle class changing
$('button').on('click', function() {
  pickOption($(this));
});

/* This function is the problem. The option gets removed from the array, and from the secondary div, but the class of active still occurs on the main div. */
$selectedOptions.on('click', '.optionActive', function() {
  var option = $(this).data('color');
  var optionPosition = jQuery.inArray(option, selectedOptions);
  selectedOptions.splice(optionPosition, 1);
  $('[data-color="' + $(this).data('color') + '"]').removeClass('active');
  displayOptions(selectedOptions, $selectedOptions);
});

// Creates initial icons (buttons in this case) to the DOM and applies a data-attribute for the color
function makeOptions(options, $container) {
  var $results = $('
');
  $.each(options, function(key, value) {
    var $optionButton = $('<button>' + key + ':' + value + '</button>');
    $optionButton.attr('data-color', value);
    //___________^^^^^^^^^^^^^^^^^^Little trick here!
    $results.append($optionButton);
  });
  $container.append($results);
}

/* Handler for selecting an option from the Main Div. Handling the class active.
I am not using a simple classToggle because there are many situations where a click is not allowed */
function pickOption($option) {
  var selectedOption = $option.data('color');
  // If the option returns true, or that it doesn't exist yet
  if (modifyOptions(selectedOption, selectedOptions)) {
    $option.addClass('active');
  } else {
    $option.removeClass('active');
  }

  // Recreate our current selected options
  displayOptions(selectedOptions, $selectedOptions);
}

/* Searches array to see if the option exists. Returns true or false and either pushes or splices the option from the array */
function modifyOptions(option) {
  var optionPosition = jQuery.inArray(option, selectedOptions);
  if (optionPosition == -1) {
    selectedOptions.push(option);
    return true;
  } else {
    selectedOptions.splice(optionPosition, 1);
    return false;
  }
}

/* Displays all currently selected options that exist in our array */
function displayOptions(selectedOptions, $container) {
  $container.empty();
  $.each(selectedOptions, function(option, value) {
    var $optionTile = $('
');
    $optionTile.data('color', value)
      .text(option + ":" + value)
      .css('background', value);
    $container.append($optionTile);
  });
}
.active {
  background: #CCF;
}
.optionActive {
  min-width: 100px;
  min-height: 100px;
  display: inline-block;
  margin: 1em;
  background: #eee;
}

Updated Fiddle
Edit: If you still want to stick with .data method, use .filter to select target element.
$('button').filter(function(){
  return $(this).data('color')=='yellow';
}).removeClass('active');


text:
Q: trying (&failing) inserting data in sqlite from iphone Hello I m developing an app which uses a sqlitedb.
I read some examples and tried do create my app.
the table I want to insert has 3 columns.
ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, DURATION REAL, TIME REAL
I write the below code based on examples I have read.
but I always see failed to add a record.
PS:
I tested db creation , its ok.
I used this tuterial  it was okay on another application. but here doesnt work
        NSTimeInterval endTime = [[NSDate date] timeIntervalSinceReferenceDate];

    double elapsedTime = endTime-startcache;

    NSString *my=[NSString stringWithFormat:@"%f",elapsedTime];
    TextField1.text=my;

    // saving in database
   NSString * durationstring=[NSString stringWithFormat:@"%f",elapsedTime];
  NSString *   timestring=[NSString stringWithFormat:@"%f",endTime];

    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];

    if (sqlite3_open(dbpath, &_activityDB) == SQLITE_OK)
    {

        NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO ACTIVITYTABLE (name, duration,time ) VALUES (\"%@\", \"%@\", \"%@\")",
                               activityname, durationstring,timestring];

        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(_activityDB, insert_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            self.status.text = @"record added";

        } else {
            self.status.text = @"Failed to add record";
        }
        sqlite3_finalize(statement);
        sqlite3_close(_activityDB);
    }

A: Its because you are directly writing data to database in resources folder.it is not writable first you need to copy the database in document directory.
NSError *err=nil;
    NSFileManager *fm=[NSFileManager defaultManager];

    NSArray *arrPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, -1);
    NSString *path=[arrPaths objectAtIndex:0];
   NSString path2= [path stringByAppendingPathComponent:@"ProductDatabase.sql"];

   if(![fm fileExistsAtPath:path2])
    {

      bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
        if(success)
            NSLog(@"file copied successfully");
       else
           NSLog(@"file not copied");

    }

and remove the bind statements from the code and change it to
if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
        {

        if(sqlite3_step(statement)==SQLITE_DONE)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Added" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];

        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Not Added" message:@"An error has occured" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            alert=nil;
        }
}

If you're really interested in learning how to use SQLite to manage data in an iPhone app, I would recommend you to complete the following tutorial, as it's a very good introduction:
http://www.icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/
The tutorial handles Selecting, Updating, Inserting and Deleting data in an iPhone app, using SQLite.


text:
Q: PInvokeStackImbalance Not Caused By CallingConvention I have no idea what the problem is here.
I have a ton of p/invoke calls that are working without incident... except this one.
I've managed to reduce my problem to the following sample code.
If I remove either struct member (either the double or the int) it works fine.
I'm assuming the problem is somehow related to the layout of the struct - but when I do a sizeof() in C and a Marshal.SizeOf() in C#, they both return the same value... so if the struct size is the same in C# and C, what could the problem be?
I'm obviously missing something basic here.
SampleDLLCode.c
#pragma pack(1)

typedef struct SampleStruct {
    double structValueOne;
    int structValueTwo;
} SampleStruct;

__declspec(dllexport) SampleStruct __cdecl SampleMethod(void);
SampleStruct SampleMethod(void) {
    return (SampleStruct) { 1, 2 };
}

Build Script
gcc -std=c99 -pedantic -O0 -c -o SampleDLLCode.o SampleDLLCode.c
gcc -shared --out-implib -o SampleDLL.dll SampleDLLCode.o

C# Code
using System;
using System.Runtime.InteropServices;

namespace SampleApplication
{
    [StructLayout(LayoutKind.Sequential, Pack=1)]
    public struct SampleStruct {
        public double structValueOne;
        public int structValueTwo;
    }

    class Program
    {
        [DllImport("SampleDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern SampleStruct SampleMethod();

        static void Main(string[] args)
        {
            SampleStruct sample = SampleMethod();
        }
    }
}

A: First of all let me congratulate you on a very well asked question. It was a delight, for once, to receive all the code that was needed to reproduce the problem.
The problem is due to the slightly different ABIs used by gcc and Microsoft tools for function return values. For return values that can fit into registers, for example int return values there are no differences. But since your struct is too large to fit in a single register and there are differences between the APIs in that situation.
For larger return values, the caller passes a hidden pointer to the function. This hidden pointer is pushed onto the stack by the caller. The function writes the return value to the memory address specified by that hidden pointer. The difference in the ABIs is in who pops that hidden pointer off the stack. The Microsoft tools use an ABI that requires the caller to pop the hidden pointer, but the default gcc ABI asks the callee to do that.
Now, gcc being almost infinitely configurable, there is a switch that will allow you to control the ABI. And you can make gcc use the same rules as the Microsoft tools. Doing so requires the callee_pop_aggregate_return function attribute.
Change your C code to be like this:
__declspec(dllexport) SampleStruct __cdecl SampleMethod(void)
    __attribute__((callee_pop_aggregate_return(0)));
    // specifies that caller is responsible for popping the hidden pointer

SampleStruct SampleMethod(void) {
    return (SampleStruct) { 1, 2 };
}


text:
Q: symplectic structure on $S^2$ i was looking for a symplectic structure on the $S^2 $. Originally i considered the Poisson-Structure of a rigid body, which was given by $\{F,G\}=\langle \Pi, \nabla F \times \nabla G \rangle$, for $F,G\in C^\infty(\mathbb{R}^3,\mathbb{R})$ . It turns out, that the sphere $S^2$ is invariant w.r.t. this structure. At the moment i´m looking at functions on the sphere which i´ve multiplied with a bump-function $\varphi(r)$ to extend the functions on the sphere in to the $\mathbb{R}^3$. In order to use the Poisson-structure i have to calculate $\nabla F$ and $\nabla G$ w.r.t. the Cartesian coordinates. Therefore i used the spherical coordinates.
$\Pi_1=r sin(\theta) cos(\eta),
\Pi_2=r sin\theta) sin(\eta),
\Pi_3=r cos(\eta)$
and with the Jacobian J i´m able to calculate the gradient in Cartesian coordinates by
$
  \nabla F=\left(\begin{smallmatrix}
  \frac{\partial F}{\partial \Pi_1}\\
   \frac{\partial F}{\partial \Pi_2}\\
   \frac{\partial F}{\partial \Pi_3}\end{smallmatrix} \right)=(J^{-1}(r,\theta,\eta))^T\left(\begin{smallmatrix}
   \frac{\partial F}{\partial r}\\
   \frac{\partial F}{\partial \theta}\\
   \frac{\partial F}{\partial \eta}\end{smallmatrix} \right)=\left(\begin{smallmatrix}
   \frac{\partial F}{\partial r}\sin(theta)\cos(\eta) + \frac{\partial F}{\partial\theta}\frac{1}{r}\cos(\theta) \cos(\eta)- \frac{\partial F}{\partial \eta}\frac{\sin(\eta)}{r\sin(theta)}\\
   \frac{\partial F}{\partial r}\sin(\theta)\sin(\eta) + \frac{\partial F}{\partial \theta}\frac{1}{r}\cos(\theta) \sin(\eta) + \frac{\partial F}{\partial\eta}\frac{\cos(\eta)}{r\sin(theta)}\\
   \frac{\partial F}{\partial r}\cos(\theta) -\frac{1}{r}\frac{\partial F}{\partial \theta}\sin(theta)
   \end{smallmatrix} \right)$
Now we put $\nabla F $ and $\nabla G$ into the Poisson-structure.
 $$\{F,G\}=-\langle \Pi, \nabla F \times \nabla G \rangle =$$ $$
    -\biggr\langle \left( \begin{smallmatrix}
 r sin(\theta) cos(\eta)\\
 r sin(\theta)sin(\eta) \\
 r cos(\theta)
 \end{smallmatrix} \right),
 \left(\begin{smallmatrix}
 \frac{\partial F}{\partial  r} sin(\theta) cos(\eta) + \frac{\partial  F}{\partial  \theta}\frac{1}{r}cos(\theta)cos(\eta)- \frac{\partial  F}{\partial  \eta}\frac{sin(\eta)}{r sin(\theta)}\\
 \frac{\partial  F}{\partial  r} sin(\theta) sin(\eta) + \frac{\partial  F}{\partial  \theta}\frac{1}{r}cos(\theta)sin(\eta)+ \frac{\partial  F}{\partial \eta}\frac{cos(\eta)}{r sin(\theta)}\\
 \frac{\partial  F}{\partial  r}cos(\theta) -\frac{1}{r}\frac{\partial  F}{\partial \theta} sin(\theta)
 \end{smallmatrix} \right) \times
 \left(\begin{smallmatrix}
 \frac{\partial  G}{\partial  r} sin(\theta) cos(\eta) + \frac{\partial  G}{\partial  \theta}\frac{1}{r}cos(\theta)cos(\eta)- \frac{\partial G}{\partial  \eta}\frac{sin(\eta)}{r sin(\theta)}\\
 \frac{\partial  G}{\partial  r} sin(\theta) sin(\eta) + \frac{\partial G}{\partial \theta}\frac{1}{r}cos(\theta) sin(\eta) + \frac{\partial  G}{\partial \eta}\frac{cos(\eta)}{r sin(\theta)}\\
 \frac{\partial  G}{\partial  r}cos(\theta) -\frac{1}{r}\frac{\partial  G}{\partial  \theta} sin(\theta)
 \end{smallmatrix} \right) \biggr\rangle $$
My solution is the following:
$$\frac{1}{r\sin(\theta)}[\frac{\partial G}{\partial \theta} \frac{\partial F}{\partial \eta}-\frac{\partial F}{\partial \theta} \frac{\partial G}{\partial \eta}]$$
I checked it with Matlab but i expected a symplectic structure and my structure is not defined at $\theta=0$ or $\theta = \pi$. Are there any mistakes in my ansatz? Thanks for help


text:
Q: I don't know how to realize a lightweight AKE protocol based on the Elliptic curve Diffie-Hellman key agreement I want to design a light-weight AKE protocol, whose function is transmitting the data to the the more advanced computational capabilities computer from the another computer.
Here, I have connected the two computers with IEEE 802.15.6.
One computer is as client to send the message, and another computer is as server to receive the message. The two machines change the data based on Elliptic Curves Cryptography.
The **server_ip **  is the adress of Bob.
And the server.py means Alice sends message to Bob:
Client.py:
import errno
import socket
import time
import random
import hmac

from collections import OrderedDict

from ecc.Key import Key
from hashlib import sha256
from ecc.elliptic import mul,add,neg

DOMAINS = {
    # Bits : (p, order of E(GF(P)), parameter b, base point x, base point y)

    256: (0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff,
          0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551,
          0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b,
          0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296,
          0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
}

if __name__== '__main__':

    global Ra,Tb,p,n,b,x,y,c_p,c_q,c_n,M1,M2,M3,Ka,macb
    server_ip = "192.168.0.114"
    server_port = 9003

    # initialization
    p, n, b, x, y = DOMAINS[256]
    c_p = 3
    c_n = p
    c_q = p - b
    idA='00000001'
    idB='00000002'
    token=0

    # TCP connection to responder B
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setblocking(1)
    print('begin connection')
    sock.connect((server_ip, server_port))

    try:
        while (token==0):
            print('connection up')
            print ('connected')
            # 1. A side: send M1=(B,A,Na,PKax,PKay) to B
            #1.1) generate my (A) keypair PKa SKa
            keypair = Key.generate(256)
            PKax = keypair._pub[1][0]
            PKay = keypair._pub[1][1]
            PKa = (PKax,PKay)
            SKa = keypair._priv[1]
            #1.2) generate my (A) nonce Na
            Na=random.randint(000000,999999)
            # 1.3) A->B: M1=(B,A,Na,PKax,PKay)
            M1=idA+','+idB+','+str(Na)+','+str(PKax)+','+str(PKay)
            sock.send(M1.encode())

            # 3. A side: 1)receive M2, 2)compute Ka, 3)compute maca,macb_check 4)send M3
            # 3.1) receive M2 from B, M2=(A,B,Nb,PKbx,PKby)
            M2 = sock.recv(1024).decode()
            Nb = M2.split(',')[2]
            PKbx = M2.split(',')[3]
            PKby = M2.split(',')[4]
            PKb = (int(PKbx),int(PKby))
            # 3.2) compute Ka
            Ka=mul(c_p,c_q,c_n,PKb,SKa)
            # 3.3) compute maca,macb_check
            hmac_stringa=idB+idA+Nb+str(Na)
            newhash=hmac.new(str(Ka[0]).encode(),''.encode(),sha256)
            newhash.update(hmac_stringa.encode())
            maca=newhash.hexdigest()
            hmac_stringb=idA+idB+str(Na)+Nb
            newhash=hmac.new(str(Ka[0]).encode(),''.encode(),sha256)
            newhash.update(hmac_stringb.encode())
            macb_check=newhash.hexdigest()
            # 3.4) A->B: M3=(maca)
            M3=maca
            sock.send(M3.encode())

            # 5. A side: 1)receive M4, 2)verify macb
            M4 = sock.recv(1024).decode()
            macb=M4
            if str(macb_check)==macb:
                print('macb is valid')
                print ('the shared secret is', Ka)
            else:
                print('macb is invalid, protocol fails')
            token=1

    except KeyboardInterrupt:
        sock.close()
        print("KeyboardInterrupt")
    #sys.exit(0)

The HOST  is the adress of Alice.
And the server.py means Bob send re-send message to Alice:
#import serial
import socket
import time
import random
import hmac

from collections import OrderedDict
from ecc.Key import Key
from hashlib import sha256
from ecc.elliptic import mul,add,neg
from ecc.curves import get_curve

DOMAINS = {
    # Bits : (p, order of E(GF(P)), parameter b, base point x, base point y)
    256: (0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff,
          0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551,
          0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b,
          0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296,
          0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
}

if __name__ == '__main__':

    global Ta,Rb,p,n,b,x,y,c_p,c_q,c_n,M1,M2,M3,Kb

    HOST = '192.168.0.114'
    PORT = 9003

    # initialization
    p, n, b, x, y=DOMAINS[256]
    c_p=3
    c_n=p
    c_q=p-b
    idA='00000001'
    idB='00000002'
    token=0

    print('Begin')

    #TCP link
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind((HOST,PORT))

    print('Listen to the connection from client...')
    sock.listen(5)
    try:
        while (token==0):
            connection, address = sock.accept()
            print('Connected. Got connection from ', address)

            # 2. B side: 1)receive M1 from A, 2)generate my keypair 3)generate Nb 4) send M2
            # 2.1) receive M1=(B,A,Na,PKax,PKay) from B
            M1=connection.recv(1024).decode()
            Na=M1.split(',')[2]
            PKax=M1.split(',')[3]
            PKay=M1.split(',')[4]
            PKa=(int(PKax),int(PKay))
            # 2.2) generate my keypair
            keypair = Key.generate(256)
            PKbx = keypair._pub[1][0]
            PKby = keypair._pub[1][1]
            SKb = keypair._priv[1]
            # 2.3) genearate my nonce Nb
            Nb=random.randint(000000,999999)
            # 2.4) B->A: M2=(A,B,Nb,PKbx,PKby)
            M2=idA+','+idB+','+str(Nb)+','+str(PKbx)+','+str(PKby)
            connection.send(M2.encode())

            # 4. B side: 1) receive M3 from A 2) compute Kb 3) compute maca_check, macb 4)verfiy maca 5)send M4
            # 4.1) receive M3=maca from A
            M3=connection.recv(1024).decode()
            maca=M3
            # 4.2) compute Kb
            Kb=mul(c_p,c_q,c_n,PKa,SKb)
            # 4.3) compute maca_check, macb
            hmac_stringa=idB+idA+str(Nb)+Na
            newhash=hmac.new(str(Kb[0]).encode(),''.encode(),sha256)
            newhash.update(hmac_stringa.encode())
            maca_check=newhash.hexdigest()
            hmac_stringb=idA+idB+Na+str(Nb)
            newhash=hmac.new(str(Kb[0]).encode(),''.encode(),sha256)
            newhash.update(hmac_stringb.encode())
            macb=newhash.hexdigest()
            # 4.4) verify maca
            if maca_check==maca:
                # 4.5) send M4
                M4=macb
                connection.send(M4.encode())
                print('maca is valid')
                print('the shared secrety is', Kb)
            else:
                print('maca is invalid, protocol fails')
            token=1

    except KeyboardInterrupt:
        print('>>>quit')
    #sys.exit(0)

Here is the additional lib ecc.Key and ecc.elliptic:
enter link description here
And I want to implement like this picture:

to let the limited device to pre-compute some values.
Actually, i'don understand how to pre-compute the values based on the limited device. I don't know how to solve the problem? Can any one give me some ideas? Thanks!

A: You can precompute the key pair obviously - actually if both sides are authenticated you must precompute the key pairs and establish trust in the public keys of the other party.
R_A can be generated in advance using your secure random number generator. U_A can be precomputed using ECC point addition as both R_A and the secret key SK_A are known by A(lice).
Possibly you could reformulate the K_1 calculation as K_1 = T_B * R_A - PK_B * R_A, although you'd still be left with a multiplication and point subtraction with the same complexity, so I don't think that makes all that much sense.