text:
Q: How to add 2 numbers together that are of different lengths in x86 linux nasm assembly I'm very new to assembly and having difficulties in getting basic calculations to work with different length numbers.
So this is my adding code, that works with numbers that are 3 or less characters long. for as long as both are the same length. for example 123 + 123 works just fine and outputs 246. But 12 + 123 does not work and it outputs 253 as the answer.
How would I be able to get this working with different length numbers?
    sys_exit equ 1
    sys_read equ 3
    sys_write equ 4
    stdin equ 0
    stdout equ 1

    section .data
        newLine db 10
        cquestion db 'Enter a number: ', 0xa
        cqLen equ $ - cquestion

        answer db 'Your answer is: '
        aLen equ $ - answer

    section .bss

        number1 resb 4
        number2 resb 4
        number1Len resd 1
        number2Len resd 1

        answ resb 8

    %macro write_string 2
        mov eax, 4
        mov ebx, 1
        mov ecx, %1
        mov edx, %2
        int 0x80
    %endmacro

    section .text
    global _start
    _start:
    write_string cquestion, cqLen

    mov eax, sys_read
    mov ebx, stdin
    mov ecx, number1
    mov edx, 4
    int 0x80
    mov [number1Len], eax

    write_string cquestion, cqLen

    mov eax, sys_read
    mov ebx, stdin
    mov ecx, number2
    mov edx, 4
    int 0x80
    mov [number2Len], eax

    write_string answer, aLen

    clc
    mov ecx, [number2Len]           ;number of digits
    dec ecx                         ;need to decrease one for some reason?
    mov esi, ecx
    dec esi                         ;pointing to the rightmost digit.
    .add_loop:

        mov al, [number1 + esi]
        adc al, [number2 + esi]
        aaa
        pushf               ; also no idea what this is here for
        or  al, 30h         ; or this
        popf                ; and this...

        mov [answ + esi], al
        dec esi
        loop addition.add_loop

        mov eax, sys_write
        mov ebx, stdout
        mov ecx, answ
        mov edx, 8
        int 0x80

        mov eax, sys_write
        mov ebx, stdout
        mov ecx, newLine
        mov edx, 1
        int 0x80

    mov [answ], DWORD 0

A: *

*Your loop never does more than 3 iterations. If there's a final carry, you'll need an extra write to the destination.

*If the code needs to deal with different length inputs, then you can't use the same offset ESI to address corresponding digits from both numbers.

*And neither can you use that same ESI to store the output since you could need one extra position to the left.

*About answ resb 8, summing a couple of 3-digit numbers can at most produce a 4-digit sum.

Below is one of the many solutions to this question.
                           ECX=1
                           v
num1:  31 32 0A 00      31 32 30 30
num2:  31 32 33 0A      31 32 33 30
                              ^
                              EDX=2

answ:                   00 00 00 00     --> 30 31 33 35
                                 ^
                                 EDI=3

    mov   ecx, [number1Len]           ; Number of bytes (eg. 3)
    sub   ecx, 2                      ; Offset to 'ones' digit
    lea   eax, [ecx + 1]              ; Offset to the newline
  .more1:
    mov   byte [number1 + eax], 30h
    inc   eax
    test  eax, 3
    jnz   .more1

    mov   edx, [number2Len]           ; Number of bytes (eg. 4)
    sub   edx, 2                      ; Offset to 'ones' digit
    lea   eax, [edx + 1]              ; Offset to the newline
  .more2:
    mov   byte [number2 + eax], 30h
    inc   eax
    test  eax, 3
    jnz   .more2

    mov   edi, 3                      ; 4 iterations
    clc
  .add_loop:
    movzx eax, byte [number1 + ecx]
    adc   al, [number2 + edx]
    aaa
    lahf                              ; Preserves CF gotten from `aaa`
    or    al, 30h                     ; Convert into character "0" to "9"
    mov   [answ + edi], al
    dec   ecx
    and   ecx, 3                      ; Wraparound in number1
    dec   edx
    and   edx, 3                      ; Wraparound in number2
    sahf                              ; Restores CF
    dec   edi
    jns   .add_loop

In the result in answ we can remove at most 3 leading zeroes. If the true result is 0, the 4th character in answ would have to remain.
    mov   edx, 4
    mov   ecx, answ
  .del:
    cmp   byte [ecx], 30h
    jne   .ok
    dec   edx
    inc   ecx
    cmp   edx, 1
    ja    .del
  .ok:
    mov   ebx, stdout
    mov   eax, sys_write
    int   80h


text:
Q: Keyboard layout on login Debian GNU/Linux 9 (stretch), no GUI
Recently something happened to my SSH, so I need to login to my debian locally. I stuck on login (GUIless) because of keyboard layout, which by default is likely set to "ru" and has no hotkey to switch. I've tried them all...
I've also tried to mount sd card on another computer and edited '/etc/default/keyboard' to
XKBMODEL="pc105"
XKBLAYOUT="us,ru"
XKBVARIANT=","
XKBOPTIONS="grp:caps_toggle,grp_led:scroll"
BACKSPACE="guess"

No luck either. Nothing changed. Layout is still 'ru' and hotkey doesn't work.
So, how to switch layout to english to be able to login?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert date string to a date object Getting the date from the user and storing the value as a string variable. The value looks like this Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)
I want to convert that string again into a new Date() object for further configurations (I need to add the number of days to the selected date and show it on another Angular mat-datepicker)
How can I do this..?

A: You can cast a date string directly to a Date object like:
let myDate = new Date("Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)");

You can manipulate your date as follows:
// For instance adding a day:
let today = new Date("Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)");

let tomorrow = new Date()
tomorrow.setDate(today.getDate() + 1);

A: You can achieve this by using momentjs
let momentObject = moment('Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)')
momentObject.add(1,'days');

Then to finally get your date object
let dateToBeSet = momentObject.toDate();

then you can use this dateToBeSet object to do whatever you want


text:
Q: Good PHP ORM Library? Is there a good object-relational-mapping library for PHP?
I know of PDO/ADO, but they seem to only provide abstraction of differences between database vendors not an actual mapping between the domain model and the relational model. I'm looking for a PHP library that functions similarly to the way Hibernate does for Java and NHibernate does for .NET.

A: I found ORM related classes in the PHP library Flourish.

A: You should check out Idiorm and Paris.

A: Give a shot to dORM, an object relational mapper for PHP 5. It supports all kinds of relationships (1-to-1), (1-to-many), (many-to-many) and data types. It is completely unobtrusive: no code generation or class extending required. In my opinion it is superior to any ORM out there, Doctrine and Propel included. However, it is still in beta and might change significantly in the next couple months. http://www.getdorm.com
It also has a very small learning curve. The three main methods you will use are:
<?php
$object = $dorm->getClassName('id_here');
$dorm->save($object);
$dorm->delete($object);

A: There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you're looking for database support besides the main ones you'll have to write your own code.

A: I am currently working on phpDataMapper, which is an ORM designed to have simple syntax like Ruby's Datamapper project.  It's still in early development as well, but it works great.

A: Tried the ORM of Flourish library.

A: I have had great experiences with Idiorm and Paris. Idiorm is a small, simple ORM library. Paris is an equally simple Active Record implementation built on Idiorm. It's for PHP 5.2+ with PDO. It's perfect if you want something simple that you can just drop into an existing application.

A: Axon ORM is part of the Fat-Free Framework - it features an on-the-fly mapper. No code generators. No stupid XML/YAML configuration files. It reads the database schema directly from the backend, so in most CRUD operations you don't even have to extend a base model. It works with all major PDO-supported database engines: MySQL, SQLite, SQL Server/Sybase, Oracle, PostgreSQL, etc.
/* SQL */
CREATE TABLE products (
    product_id INTEGER,
    description VARCHAR(128),
    PRIMARY KEY (product_id)
);

/* PHP */
// Create
$product=new Axon('products'); // Automatically reads the above schema
$product->product_id=123;
$product->description='Sofa bed';
$product->save(); // ORM knows it's a new record

// Retrieve
$product->load('product_id=123');
echo $product->description;

// Update
$product->description='A better sofa bed';
$product->save(); // ORM knows it's an existing record

// Delete
$product->erase();

Most of all, the plug-in and accompanying SQL data access layer are just as lightweight as the framework: 14 KB (Axon) + 6 KB (SQLdb). Fat-Free is just 55 KB.

A: Until PHP 5.3 release don't expect to have a good ORM. It's a OO limitation of PHP.

A: My friend Kien and I have improved upon an earlier version of an ORM that he had written prior to PHP 5.3. We have essentially ported over Ruby on Rails' Active Record to PHP. It is still lacking some key features we want such as transactions, composite primary key support, a few more adapters (only MySQL and SQLite 3 work right now). But, we are very close to finishing this stuff up. You can take a look at PHP ActiveRecord with PHP 5.3.

A: Try PHP ADOdb.
I can't say it's the best, because I haven't used the others. But it's fast, it supports Memcached and caching.
And it's waaaay faster than Zend Framework's DB/Select.

A: Brazilian ORM: http://www.hufersil.com.br/lumine. It works with PHP 5.2+. In my opinion, it is the best choice for Portuguese and Brazilian people, because it has easy-to-understand documentation and a lot of examples for download.

A: Have a look at the LEAP ORM for Kohana. It works with a bunch of databases, including DB2, Drizzle, Firebird, MariaDB, SQL Server, MySQL, Oracle, PostgreSQL, and SQLite. With a simple autoload function, it can work with almost any PHP framework. The source code is on GitHub at https://github.com/spadefoot/kohana-orm-leap. You can checkout LEAP's tutorials online.
The ORM library works with non-integer primary keys and composite keys. Connections are managed via a database connection pool and it works with raw SQL queries. The ORM even has a query builder that makes building SQL statements super simple.

A: I've been developing Pork.dbObject on my own. (A simple PHP ORM and Active Record implementation)
The main reason is that I find most ORMs too heavy.
The main thought of Pork.dbObejct is to be light-weight and simple to set up. No bunch of XML files, just one function call in the constructor to bind it, and an addRelation or addCustomRelation to define a relation to another dbObject.
Give it a look: Pork.dbObject

A: Try Doctrine2. It's probably the most powerful ORM tool for PHP. I'm mentioning it separately from Doctrine 1, because it's a completely different piece of software. It's been rewritten from scratch, is still in beta phase, but it's usable now and developed.
It's a very complex ORM, but well designed. Lot of magic from original Doctrine 1 disappeared. It provides a complete solution, and you can write your own ORM on top of Doctrine2 or use just one of its layers.

A: You can check out Repose if you are feeling adventurous. Like Outlet, it is modeled after Hibernate.
It is still very early in its development, but so far the only restrictions on the domain model are that the classes are not marked final and properties are not marked private. Once I get into the land of PHP >= 5.3, I'll try to implement support for private properties as well.

A: If you are looking for an ORM that implements the Data Mapper paradigm rather than Active Record specifically, then I would strongly suggest that you take a look at GacelaPHP.
Gacela features:

*

*Data mapper

*Foreign key mapping

*Association mapping

*Dependent mapping

*Concrete table inheritance

*Query object

*Metadata mapping

*Lazy & eager loading

*Full Memcached support

Other ORM solutions are too bloated or have burdensome limitations when developing anything remotely complicated. Gacela resolves the limitations of the active record approach by implementing the Data Mapper Pattern while keeping bloat to a minimum by using PDO for all interactions with the database and Memcached.

A: Agile Toolkit has its own unique implementation of ORM/ActiveRecord and dynamic SQL.
Introduction: http://agiletoolkit.org/intro/1
Syntax (Active Record):
$emp=$this->add('Model_Employee');
$emp['name']='John';
$emp['salary']=500;
$emp->save();

Syntax (Dynamic SQL):
$result = $emp->count()->where('salary','>',400)->getOne();

While Dynamic SQL and Active Record/ORM is usable directly, Agile Toolkit further integrates them with User Interface and jQuery UI. This is similar to JSF but written in pure PHP.
$this->add('CRUD')->setModel('Employee');

This will display AJAXified CRUD with for Employee model.

A: MicroMVC has a 13 KB ORM that only relies on a 8 KB database class. It also returns all results as ORM objects themselves and uses late static binding to avoid embedding information about the current object's table and meta data into each object. This results in the cheapest ORM overhead there is.
It works with MySQL, PostgreSQL, and SQLite.

A: NotORM
include "NotORM.php";
 $pdo = new PDO("mysql:dbname=software");
 $db = new NotORM($pdo);
 $applications = $db->application()
->select("id, title")
->where("web LIKE ?", "http://%")
->order("title")
->limit(10)
;
foreach ($applications as $id => $application) {
echo "$application[title]\n";
}

A: I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.

A: Look into Doctrine.
Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.
Also, check out Xyster. It's based on the Data Mapper pattern.
Also, take a look at DataMapper vs. Active Record.

A: I really like Propel, here you can get an overview, the documentation is pretty good, and you can get it through PEAR or SVN.
You only need a working PHP5 install, and Phing to start generating classes.

A: Check out Outlet ORM. It is simpler than Propel and Doctrine and it works similar to Hibernate, only with more of a PHP feel to it.

A: Try RedBean, its requires:

*

*No configuration

*No database (it creates everything on the fly)

*No models

*etc.

It even does all the locking and transactions for you and monitors performance in the background. (Heck! it even does garbage collection....) Best of all... you don't have to write a single... line of code... Jesus this, ORM layer, saved me ass!

A: Doctrine is probably your best bet. Prior to Doctrine, DB_DataObject was essentially the only other utility that was open sourced.

A: If you are looking for an ORM, like Hibernate, you should have look at PMO.
It can be easily integrated in an SOA architecture (there is only a webservice classe to develop).

A: PHP ORM Faces For PDO extension. See PHP Faces Framework.
$urun = new Product();
$urun->name='CPU'
$urun->prince='124';
$urun->save();

A: There's a fantastic ORM included in the QCubed framework; it's based on code generation and scaffolding. Unlike the ActiveRecord that's based on reflection and is generally slow, code generation makes skeleton classes for you based on the database and lets you customize them afterward. It works like a charm.

A: Look at http://code.google.com/p/lworm/ . It is a really simple, but powerful, lightweight ORM system for PHP. You can also easily extend it, if you want.

A: A really good simple ORM is MyActiveRecord. MyActiveRecord documentation. I have been using it a lot and can say it's very simple and well tested.

A: Looked at Syrius ORM. It's a new ORM, the project was in a development stage, but in the next mouth it will be released in a 1.0 version.

A: Try PdoMap. Wikipedia claims that is inspired by Hibernate. Since I never used Hibernate, I cannot judge :), but I would say from my experience that is good and fast ORM that is easy to implement, with a less steep learning curve that other ORMs.

A: Another great open source PHP ORM that we use is PHPSmartDb. It is stable and makes your code more secure and clean. The database functionality within it is hands down the easiest I have ever used with PHP 5.3.

A: Sado is a simple PHP ORM package, easy to use, and offers video tutorials

A: I work on miniOrm. Just a mini ORM, for using Object Model & MySQL Abstraction Layer as simply as possible. Hope it may help you : http://jelnivo.fr/miniOrm/


text:
Q: how to change json provider limit in vba excel The API provider has set a limit of 20 records in json. For example I have 415 records. Would there be any way to circumvent this limit and search for all records?
{"offset":0,**"limit":20**,"total"415,"
Private Function GetResponse(ByVal url As String) As String
    Const RunAsync As Boolean = True
    Const ProcessComplete As Integer = 4

    Sheets("getLayer").Select

    'Limpa área que irá receber os dados

    Worksheets("getLayer").Range("A1:C1000").ClearContents

    Dim request As MSXML2.XMLHTTP60
    Set request = New MSXML2.XMLHTTP60

    Dim response, result As String
    Dim procura As Variant

    With request

    .Open "GET", url, RunAsync
    .setRequestHeader "Content-Type", "application-json"
    .send

    Do While request.readyState <> ProcessComplete
    DoEvents
    Loop

    response = .responseText

    Set request = Nothing

End Function


text:
Q: Widow word on a page? I thought LaTeX wouldn't do that Just had a surprise. I have a section in an article followed by a figure. The text flows over a page and ... one more word on the next page (which also includes the figure).
Yes, I added a ~ before that word to make it fit on the first page but I thought LaTeX wouldn't do this (leave widow words, not even sentences)!
Is there anything in particular that needs to be enabled to avoid this? I used MikTeX 2.8 with output to PDF (both pdftex and pdflatex produced the same problem).

A: During the manual final adjustments of the manuscript, I often (as a copy editor) use \looseness=1 to make TeX try to increase the number of lines in some paragraph by 1, so that I avoid widows, orphans and underfull pages.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus vitae mi dui.
Aliquam erat volutpat.
Vestibulum nec vehicula nisi.
Ut feugiat tortor a justo eleifend sit amet adipiscing dolor cursus.
\looseness=1

Nullam a neque consectetur magna suscipit rhoncus.
Vivamus gravida lorem non elit bibendum ac vulputate dolor cursus.
Etiam ac sapien quis dui commodo feugiat.
Praesent sagittis mi in metus cursus rutrum.
Pellentesque faucibus aliquam quam in vestibulum.
Sed non elit eget mauris tincidunt facilisis.
Suspendisse posuere elit ac magna vestibulum pulvinar.

A: LaTeX is set up to avoid this if possible but sometimes there just isn't a good alternative. You can suppress widow lines entirely with \widowpenalty=10000 but you'll want to have \raggedbottom enabled.
Avoiding widow words isn't as directly straightforward. You cannot automatically suppress them but you can specify that you want a final line of at least some certain length with
\parfillskip 0pt plus 0.75\textwidth

where "some certain length" is, in this case, one quarter of the text width of the document.


text:
Q: How to update multiple matches by SQL? I have data from tableA (columns A1 and A2) that I want to update in tableB (columns B1 and B2) when A1 matches B1. So A2 value will be updated in B2 when A1 and B1 match
The code below works but only for the first A1 and B2 match. In my database there are several matches and I would like to have all B2 values updated
$sql = "UPDATE tableB INNER JOIN tableA
set tableB.B2 = tableA.A2
where tableB.B1 = tableA.A1";

Any idea how to have all tableB.B2 values updated each time tableB.B1 = tableA.A1?

A: $sql = "UPDATE tableB INNER JOIN tableA ON tableB.B1 = tableA.A1
set tableB.B2 = tableA.A2";

Check this link for further details: Update a table using JOIN in SQL Server?


text:
Q: In Django, disable @login_required for search engine spiders I'm looking for a clean way to let search engine spiders bypass @login_required, viewing pages which typically require a logged-in user.  I could write middleware that would automatically log search engines into a dummy account, but that's not exactly what I'd call clean.  Any suggestions for a better solution?  Thanks.

A: Don't do this. This is 'cloaking', and can get you banned from Google's index.

Cloaking refers to the practice of presenting different content or URLs to users and search engines. Serving up different results based on user agent may cause your site to be perceived as deceptive and removed from the Google index.

*

*Cloaking: http://www.google.com/support/webmasters/bin/answer.py?answer=66355
Instead, you need to implement Google's First Click Free solution. In this setup, the first click from a Google search result is able to see the full content, subsequent clicks are trapped. This can be done on a referrer basis, or a cookie basis. You can read more about First Click Free here:

*

*First Click Free: http://www.google.com/support/webmasters/bin/answer.py?answer=74536

A: Why would you want to do this? If search engines can see the pages, then anyone can see them without being logged in, because the information would surface on the search engine's results page. In any case, the only way to identify a spider or bot is by its user agent string, which is trivial to spoof.

A: I don't get it. in "@login_required" you have an important word: "required". if it's "required", it's for a good reason. It means that, in order to see the webpage, your credentials are mandatory. Because the content is private, secret, etc.
If you want to make your pages to be available via search engines, you have to make them public, and thus, login is not required anymore. And so, your view should not be protected by the @login_required decorator.
Maybe your problem lies beyond the availabilty of your pages. Maybe your content is actually made to be public, and your views should not be protected by this decorator. Maybe the only thing you need is to load the public part for every user (logged or anonymous) and eventually load the private bits if your user is identified.
Otherwise, leaving a backdoor for spiders is definitely a bad idea, because your private content won't be private anymore.


text:
Q: Target only text and not nested elements I need to manipulate only the text of a nested list without touching the next ul. I have this:

Some text here

Lorem

ipsum dolor

Another text here

Lorem ipsum dolor

And I want to wrap the inner text in a span so I will have this:

Some text here

Lorem

ipsum dolor

Another text here

Lorem ipsum dolor

A: You can do it this way (the inserted span element has a red text color):
You first select the desired li element ('ul > li > ul > li:last-of-type') then you get the text node which contains "Another text here" (item.firstChild), create a span element with its content and replace it with your span.

let item = document.querySelector('ul > li > ul > li:last-of-type');

let text = item.firstChild.textContent;
let span = document.createElement('span');
span.textContent = text;
span.style.color = 'red';

item.replaceChild(span, item.firstChild);

Some text here

Lorem

ipsum dolor

Another text here

Lorem ipsum dolor

A: I know it's a mix with jQuery and vanilla, but that's what worked for me was:
$('.in-documents ul li').each(function() {
   var text = $(this).clone().children().remove().end().text();

    if($(this)[0].firstChild.textContent != "") {
        var span = document.createElement('span');
        span.textContent = text;
        $(this)[0].firstChild.textContent = '';
        $(this).prepend(span);
    }
});


text:
Q: Reading message from Websphere MQ is always destructive call I have observed that when msg is read from the queue(destructive call) later if TX is rolled back(MDB container managed TX) msg are placed back to the queue(Original or back out queue depending the on backcount & threshold settings for queue). Lets say if something happens(Repeated Network issue or some issue) due to which rollback of TX got failed then Msgs are lost.
Is it true??
Thanks

A: As I noted in the comments to the earlier question, the short answer is "no, WMQ will not lose those messages if the COMMIT fails" but let us look in a bit more detail.
When the client makes a connection to MQ over the network, what happens under the covers is that MQ starts a process that creates a shared-memory connection to MQ and a socket connection to the client application.  The thing holding the transaction open is the shared memory process which is called a 'channel agent' in WMQ terminology.
There are two cases where the COMMIT appears from the application's perspective to have failed.  In the first of these, the COMMIT is delivered to the channel agent and executed, but the acknowledgement never makes it back to the application due to a network problem.  From MQ's perspective, the message is not 'lost' because the app intentionally committed the GET calls.
The second case is that the network failure occurs before the COMMIT arrives at the channel agent.  In this case, the COMMIT truly has failed because it is not possible for the app to recover the connection handle in which the transaction lives.  When the channel agent realizes that the TCP connection has failed, it backs out the transaction and closes the channel.  The wrinkle in this process is that it may take a while for the channel agent to realize that the connection has died.  In fact, the default TCP timeout on most platforms is two hours.  Depending on your server's TCP settings, the transacted GET may hold that message under syncpoint for up to two hours, making it appear to have been consumed.  This is one reason that using a current level of QMgr and client is highly recommended - they rely less on TCP and more on an internal channel heartbeat protocol to detect lost connections.
From the application's perspective both of these cases appear to be the same - app calls COMMIT and gets back 2009 MQRC_CONNECTION_BROKEN.  But in the first case, the message is gone due to the COMMIT and in the second case, the message may be delivered again.  Because of this ambiguity, the app must be able to detect and gracefully handle dupe messages.
Now before declaring that this is a defect in MQ, let me point out that this ambiguity of outcomes is inherent when using messaging over the network and not anything specific to WebSphere MQ.  In fact, the JMS 1.1 specification addresses this directly in 4.4.13 where it says:

If a failure occurs between the time a client commits its work on a
  Session and the commit method returns, the client cannot determine if
  the transaction was committed or rolled back. The same ambiguity
  exists when a failure occurs between the non-transactional send of a
  PERSISTENT message and the return from the sending method.
It is up to a JMS application to deal with this ambiguity. In some
  cases, this may cause a client to produce functionally duplicate
  messages.
A message that is redelivered due to session recovery is not
  considered a duplicate message.

So the use of syncpoint can eliminate the case of lost messages because any GET must be followed by a COMMIT in order to permanently remove the message from the queue.  By definition, the COMMIT cannot arrive until the application has seen the message.  However, syncpoint cannot eliminate the possibility of duplicate messages because if a COMMIT of a GET fails, the app may see the message again.  Similarly, if the COMMIT of a PUT fails, the app has no way to know whether the COMMIT failed before or after reaching the channel agent and has no choice but to reconnect and PUT the message again.
If in fact you are experiencing 'lost' messages, the possibilities are that:

*

*The putting app failed on the COMMIT but did not put another copy of the message.

*The GETting app failed on the COMMIT and the message is not lost but actually under syncpoint.  In that case, stop any orphaned channels to roll back the transaction.

Other than those two cases, WMQ will not lose that persistent message.

A: No. Messages are not lost. In a transaction, the messages are removed from the queue only after successful commit. Messages reappear if commit or rollback fails. WebSphere MQ  automatically does a rollback if a connection between application and queue manager breaks before a commit or rollback is called. This ensures that messages are not lost.


text:
Q: How do I access "named properties" in a GTK struct? I'm trying to get a GTK-3.0-based app to build and I need to modify some code so that it uses the "master" property in a struct:
https://developer.gnome.org/gdl/stable/GdlDockLayout.html#gdl-dock-layout-new
I have little experience programming with GTK, so I don't know how to access these properties. And unfortunately "property" is such an overloaded term that Google yields nothing useful.

A: You want to use something like
GObject *master;
g_object_get (my_gdl_dock_layout_widget, "master", &master, NULL);

// Use master

// Once you've finished with master, don't forget to unref it
g_object_unref (master);

see the GObject reference documentation for details on g_object_get

A: You use the GObject (the base class of most objects in GTK+ and related libraries) API.
The (rather sparse) documentation is here.
Essentially, I think you're after the g_object_set_property() function.


text:
Q: z3, z3py: Is it possible to intrinsically reduce the search space of Function? I am inferring a Function(var1) and I only care about the values of this function when 0 <= var1 <= 10 and I know, when 0 <= var <= 10, 0 <= Function(var1) <= 10.
A common way (I guess) to constrain the search space of the Function is something like asserting constraints like (in z3py):
for i in range(11):
  solver.add(And(Function(i)>=0,Function(i)<=10))

My question is that: is there a better way so that I can constrain the search space of Function? Something like setting upperbound/lowerbound of this Function by nature?
My intuitions are that: since I have a lot other constraints for this Function, I feel like if I could constrain the search space of Function by nature, many impossible assignment might be automatically avoided by the solver, and the time spent on the inference might be reduced. I am not sure if this makes sense.

A: Z3 only supports simple types. You are basically constraining your function using a property. You could encode this using a quantified assertion. That is,
assert that
   ForAll([x], Implies(And(0 <= x, x <= 10), And(0 <= F(x), F(x) <= 10)))

The quantifier gets instantiated for each occurrence of F, as opposed to each
value in the domain of F. This helps a lot if your domain is huge and the number of occurrences is small. On the other hand if F gets used in many places (also as a consequence of instantiating other quantifiers during search), then stating the bounds up front will be cheaper.

A: One way that I think of is that we can probably restrict the domain and range of function by replacing "IntSort" as the sort for input and output with "BitVecSort".
Suppose I know the domain is [0,8] and range is [0,127]. Then we could define function as
F = Function('F',BitVecSort(3),BitVecSort(7))


text:
Q: How to define input types in Matlab Coder for a function that has a varying number of input? I have a function let's say sq_dist(). This function can be called like this sq_dist(a,b) or sq_dist(a). This function includes slow operations and thus I am trying to make a Mex version of it hoping that it will run faster. I am using the Matlab Coder GUI to do so.  In order to define input types (in the define input screen) i use a function that calls sq_dist(a,b) and sq_dist(a) to automatically determine input. This gives me an error:  Error determining type for input sq_dist:b. Index exceeds matrix dimensions. Here is my function:
n = 50;
dim = 50;
a = rand(n, dim);
b = rand(n, dim);

u = sq_dist(a, b);
v = sq_dist(a);

So, since sq_dist can be called in different ways I am not sure how to define its input in the Coder.
If i manually set the input to double :inf x :inf for a and b the mex file is compiled but i get a runtime error:  Function 'sq_dist' called with wrong number of arguments: expected 2, received 1.

A: In short, you cannot do what you want to do (with current version 2016a) for the top-level function - this has to have a defined number of inputs and outputs. Even if you use the 'varargin' parameter in the function definition, MATLAB Coder will generate the function with a fixed number of inputs based on the example arguments you provide.
If you have a particular function that has a variable number of input arguments, you can put a wrapper function (with a fixed number of input arguments) around the outside, and make the wrapper the top-level function.
Rules here:
http://uk.mathworks.com/help/simulink/ug/rules-for-using-variable-length-argument-lists-for-code-generation.html


text:
Q: test coordination procedures in the Acceptance testing of Diag what tool will be used for test coordination procedures in the Acceptance testing of Diag. Can any body explain a bit about Test Coordination Procedures in Acceptance Testing of Diag.
Thanks in Advance
can any body help me creating the skeleton of the Acceptance Testing


text:
Q: equivalent way using apply family instead of a for loop to get max value of each row in list of sublists R What would be the equivalent to this using apply family functions or a compbination between do.call and apply? I would like to keep it simple and when possible in one line:
a <- list(  as.data.frame(matrix(rnorm(12),4,3)),
            as.data.frame(matrix(rnorm(12),4,3)),
            as.data.frame(matrix(rnorm(12),4,3))
         )

l <- list()
for (i in 1:length(a)) {
  l[[i]] <- apply(a[[i]],1,max)
}

b <- do.call(data.frame, l)

A: I would use sapply for this particular example, however I don't know how representative this example is of your actual larger problem.
> sapply(a, function(x) apply(x, 1, max))
          [,1]      [,2]       [,3]
[1,] 0.5757814 0.9189774  0.6198257
[2,] 0.1836433 0.9438362  0.4179416
[3,] 1.5117812 1.1249309  1.3586796
[4,] 1.5952808 0.5939013 -0.1027877

sapply will simplify to a matrix whenever possible. If you want a data.frame, just wrap the output in data.frame.


text:
Q: How to get MVC action to return 404 I have an action that takes in a string that is used to retrieve some data. If this string results in no data being returned (maybe because it has been deleted), I want to return a 404 and display an error page.
I currently just use return a special view that display a friendly error message specific to this action saying that the item was not found. This works fine, but would ideally like to return a 404 status code so search engines know that this content no longer exists and can remove it from the search results.
What is the best way to go about this?
Is it as simple as setting Response.StatusCode = 404?

A: In MVC 4 and above you can use the built-in HttpNotFound helper methods:
if (notWhatIExpected)
{
    return HttpNotFound();
}

or
if (notWhatIExpected)
{
    return HttpNotFound("I did not find message goes here");
}

A: None of the above examples worked for me until I added the middle line below:
public ActionResult FourOhFour()
{
    Response.StatusCode = 404;
    Response.TrySkipIisCustomErrors = true; // this line made it work
    return View();
}

A: In NerdDinner eg. Try it
public ActionResult Details(int? id) {
    if (id == null) {
        return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
    }
    ...
}

A: In .NET Core 1.1:
return new NotFoundObjectResult(null);

A: I use:
Response.Status = "404 NotFound";

This works for me :-)

A: Code :
if (id == null)
{
  throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}

Web.config
<customErrors mode="On">
  <error statusCode="404" redirect="/Home/NotFound" />
</customErrors>

A: In ASP.NET MVC 3 and above you can return a HttpNotFoundResult from the controller.
return new HttpNotFoundResult("optional description");

A: If you are working with .NET Core, you can return NotFound()

A: There are multiple ways to do it,

*

*You are right in common aspx code it can be assigned in your specified way

*throw new HttpException(404, "Some description");

A: I've used this:
Response.StatusCode = 404;
return null;

A: You can also do:
        if (response.Data.IsPresent == false)
        {
            return StatusCode(HttpStatusCode.NoContent);
        }

A: Please try the following demo code:
public ActionResult Test()

{
  return new HttpStatusCodeResult (404,"Not found");
}


text:
Q: Pygame Collision on Rect I'm a student in Computer Programming at my high school and really need help to make the square an obstacle that ships can't enter and bullets disappear once you shoot at the square also for the circle the same thing. And both ships die if they collide with each other. Please help I know my question isn't the best worded but i really need help.
the link to the code is here https://docs.google.com/file/d/0B-Pb_T-Vgr3-TnhRY0lvVjJHX0U/edit?usp=sharing

A: I would suggest that you create a GameObject class which extends pygame.sprite.Sprite and both Ship and Bullet classes which extend GameObject. This allows you to then easily add properties that both will need, such as velocity and acceleration, and you can create a collide method that is overridden by both for specific behavior. The added bonus here is that pygame.sprite.collide_rect will work properly as such:
if (pygame.sprite.collide_rect(sprite1, sprite2)):
    # sprite1 and sprite2 are colliding!
    # do something, such as calling sprite1.collide(sprite2)
    # and sprite2.collide(sprite1)

So, pygame.sprite.collide_rect checks if two sprites collide using the Sprite.rect property of each. This functionality could also be recapitulated using rect.colliderect:
sprite1.rect.colliderect(sprite2.rect)


text:
Q: the .jar file does not execute when I click on it I know this question would sound very stupid, but this is my first java program after all.
K, the question is, when type this: java -jar JavaApplicationTest.jar the program executes without problems, but when I go to the folder where the JavaApplicationTest.jar file is, and click on it, it does not execute. I thought that .jar files were like .exe file, are they? I mean, in the way that we click on them and the program runs; 'cos the java virtual machine is running in the back ground.
Please, any help would be very much appreciated.

A: No, they aren't exactly like .exe.  Only .exe is an .exe.
When you execute a JAR file, it's the Java JVM that's running, not your JAR file.  The JVM opens the JAR, loads the .class byte code, and executes the main class that you specified in the META-INF.
I'm guessing that your Windows operating system is doing something besides running the JVM when you double click.  Try right clicking and seeing what options your Windows operating system presents to you.  If one of them is to unzip the file, you'll have to add running the JVM as another choice.

A: The jar-file runs. But there's a big difference between:
java -jar someJar and someJar.jar/respectively double-clicking on the jar.
The full command launches the jar in the same commandline, in which you have entered the command. Double-clicking on the jar creates a process aswell. But with a completely separate console-window that is hidden.

A: Java archive or jar is an archive of compiled java byte code and resources which can be run on a java virtual machine. ".exe" is a windows extension for directly executable code mostly used by installers or programs that do not need to be installed.


text:
Q: Disabling mod_mime_magic module per directory I would like to be able to disable the Apache module mime_magic in a particular directory (and its children). I've searched around, and there seem to be special one-off flags you can set to disable some modules (PHP, deflate, etc), but nothing general (or specific to mime_magic.
Is there a way to disable mime_magic in one directory? There's a known issue with it causing issues serving BAM files with JBrowse, and the recommended workaround is to disable mime_magic.

A: The module (like all modules) is enabled server-wide.  The only available configuration directive is MimeMagicFile, which can be set at the server or virtual host level.  So if you wanted to disable it for a specific virtual host, I suppose you could set MimeMagicFile /dev/null in that vhost.  But there doesn't seem to be any way of disabling it for a specific directory.


text:
Q: Should there be a better balancing system for voting to mark a question as a duplicate? It seems that many of my own questions have been closed simply because I misworded them and they assumed it was a duplicate question. Indeed, sometimes there was a duplicate question with an answer I could use, but many times, there was simply a miscommunication and my situation was indeed unique. However, I then come back to check on the answers to find no answers or comments, and the question had been closed.
Would it not be reasonable to require an asker to give their reasoning before marking their question as a duplicate, or to deal out a negative rep for voting to close a question? I'm not saying that no question deserves to be closed, as I've done my share of close voting, but many don't deserve to, and once one person votes to close, it seems that every next person that sees the question also votes and it's closed without even asking the original poster if the other question indeed helps them.

A: Closing is not the end of the world. Unlike forum closings, "closed" on SE means "temporarily put on hold till the question is fixed".
Is something misworded? Fix it and flag for reopening. Is your post not a duplicate? Make that clear by editing.
Don't look at a closed question and feel "Oh, great! They destroyed my post." Think "Oh look, they closed it till it gets fixed! That way I won't get answers that misinterpret my question!" and then fix it by following the advice in the comments.
Of course, there are some closed questions that aren't fixable, but that's a different story.


text:
Q: Why does this function split up like this? (Rudin, Real and Complex Analysis) This is regarding Theorem 1.8 on page 11 of Rudin's Real and Complex Analysis, we have a measurable space $X$ and two real valued functions on it $u$ and $v$. We then have a continuous mapping $\Phi$ from the real plane into a topological space $Y$. We define $f(x)=(u(x),y(x))$ and $h=\Phi\circ f$, and from here we need to show that $h$ is measurable and we know that it suffices to show that $f$ is measurable.
We then take a rectangle $R$ in the plane with sides parallel to the axes, which we write as the Cartesian product of $I_1$ and $I_2$ which are two segments, presumably two adjacent sides of the rectangle. We then say that: $$f^{-1}(R)=u^{-1}(I_1)\cap v^{-1}(I_2) \tag{1},$$ and this is what's confusing me. $I_1$ and $I_2$ are essentially just lines in the plane, why would the intersection of their preimage be equal to the preimage of the entire rectangle and not just two "lines" in $X$?
Disclaimer: I am a physicist not a mathematician please have mercy on my soul if this is a trivial error on my part.

A: As far as I understand, we have $R=I_1\times I_2$.
Now we want to show $f^{-1}(R)=u^{-1}(I_1)\cap v^{-1}(I_2)$.
This is a straight forward proof:
$f^{-1}(R)=\{x\in X: f(x)\in R\}=\{x\in X: (u(x),v(x))\in I_1\times I_2\}=\{x\in X: u(x)\in I_1~\text{and}~ v(x)\in I_2\}$
$=\{x\in X: u(x)\in I_1\}\cap \{x\in X: v(x)\in I_2\}=u^{-1}(I_1)\cap v^{-1}(I_2)$


text:
Q: what is <> in swift So, I see a function func applicationWillResignActive(_ application: UIApplication) in my AppDelegate.swift, but when I -print-ast, I see below
internal func applicationWillResignActive(_ application: UIApplication) -> <<error type>>
What is <<error type>>

A: <<errortype>> is compiler's issue or bug we can say that, indicates that complier is unable to compile your current object.
This frequently faced when you use object of type AnyObject.
Clean your project will resolve your issue,
Even if Cleaning does not do the job then Close XCode once(I never neeed to close XCode for this yet)

A: You have to provide an SDK and a target so that the compiler
finds the Swift standard library, the required frameworks (such as "UIKit") and knows how the types,
methods, etc are defined.
Example:

$ xcrun --sdk iphoneos swiftc -target arm64-apple-ios10.1 -print-ast AppDelegate.swift 2>/dev/null

Output:

import UIKit

@UIApplicationMain @objc internal class AppDelegate : UIResponder, UIApplicationDelegate {
  @objc internal var window: UIWindow?
  @objc internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool
  @objc internal func applicationWillResignActive(_ application: UIApplication)
  @objc internal func applicationDidEnterBackground(_ application: UIApplication)
  @objc internal func applicationWillEnterForeground(_ application: UIApplication)
  @objc internal func applicationDidBecomeActive(_ application: UIApplication)
  @objc internal func applicationWillTerminate(_ application: UIApplication)
  @objc deinit
  @objc override internal init()
}

(I added 2>/dev/null to the command line because some warnings about 'UIApplicationMain' are printed to the standard
error, I haven't been able yet to suppress these properly.)


text:
Q: I have lots of test executables; how do I manage them? Where I work, we've been gradually beefing up our automated testing capabilities and coverage.
We're at the point where we've got a wide range of tests, and one configuration of "what needs to be run" is no longer sufficient. We want one set of tests to run when new code is checked in; a larger set for nightly builds; a set that runs before a release; a set that runs with specific hardware attached...
All of our tests are in the form of executables (or, e.g., python scripts that call executables).

*

*Let's assume, for simplicity's sake, that each executable returns 0 on success, and nonzero on failure.

*Some tests might have additional output (e.g. a unit-test executable will have multiple tests, and be able to export its results to an output file;  a higher-scope test might have logs I want to save; etc.).

*The executables are not all from a single type or framework.

*Some test executables might require arguments to define how the test should run; I might define multiple tests, as calls to the same executable with different parameters.

What I'm looking for when I say "test management" is a tool that can do things like:

*

*Make it easy to add a new test command to a test configuration.

*List what tests are included in a given configuration.

*Nice to have: make it easy to move or duplicate a test command from one configuration to another.

*Run tests, including graceful handling of tests that crash or time out.

*Generate a pass/fail report from a given test run.

*Nice to have: Maintain pass/fail history for individual test commands.

I know tools to manage our tests must exist. But I've had a hard time finding the right tools -- and even more than that, I've had a hard time finding the right terminology. This might just be me, but most resources I've read on testing seem to gloss over the "get the infrastructure up and running" bit of it. So: I'm hoping there's solid terminology I'm missing, or resources on getting infrastructure set up.
TL;DR: What I'm looking for is guidelines and terminology for this part of testing infrastructure. I've got a bunch of test executables, I've got a CI system (or we could switch to a new one, if need be); what are the steps I need to take (and what do I need to read up on) in order for the right sets of tests to run at the right time?

A: My two cents. You say:

We want one set of tests to run when new code is checked in; a larger set for nightly builds; a set that runs before a release; a set that runs with specific hardware attached

Each of those cases is different. Threat them differently. I would recommend taking a look at jenkins (or a similar tool). You can have a server running jenkins, which could:

*

*Launch a script every night.

*Launch a script when you commit to the repository.

Even though I think the last is possible to do in theory, I was not able to do so when I tried. So an alternative could be to add the script to your repository, and before pushing to master, all team members must run the script themselves. If somebody fails to do so and break the build, you will catch it at midnight. Alternative this script could be run several times a day, so you catch it more quickly.

*

*For the other two options (special hardware or release), you could add those scripts to the repository too and run them manually.

If you already have python scripts that do what you say, all you are missing is putting some order in the house.
The JUnit XML format is recognized by jenkins and other tools. If you manage to write the output of your python scripts in this format it will help you a lot in the long run. I'm not sure you can use jenkins if you don't.
Again, don't look for a "one answer to solve them all". Those tests cases are different, look for tools for each case.

A: First, your post reads a little bit like a question for a tools recommendation in disguise (but I am sure you know that this would be off-topic for this site). If you google for "test management system", you find plenty of links (like this one: 15 Best Test Management Tools of 2017).
The main part of what you are trying to achieve can be implemented by using (maybe "abusing") a typical unit testing tool like NUnit or JUnit (or the module "unittest" for Python). For example, in my dev team, we are actually using NUnit with its UI - not just for unit tests, but also for any kind of automated test, including ones where arbitrary executables are included. NUnit gives us the following capabilities:

*

*you can easily group and categorize tests and run (or exclude) tests by category

*the UI gives you a overview over all existing tests, and you can pick individual ones or subsets and run them interactively

*you can run tests either by GUI or command line (so you could integrate this easily into any CI system)

*you get a pass/fail report after each run

Of course, tests running arbitrary executables, especially with graceful handling in case of a crash or time out, is nothing you get "out of the box", for this part we implemented a little bit of infrastructure by ourselves.
If you decide to go a similar route, adding new tests to a configuration, or moving tests from one configuration to another will become easy over time. Just develop some conventions for your team, write some short documentation and provide some examples.
As you already noted by yourself, it helps to standardize the tests, for example, by making each test a command line program with similar parameters and standard behaviour, by using consistent naming conventions for tests and folders, and by putting output files of individual tests always in a specific folder (for example, in a subfolder below the folder where the executable is, or a temp folder with an according name). But that is nothing a test management tool will do for you, this part you will have to work out for yourself.


text:
Q: Getting error when I call class in Swift I am new to Swift. I have a simple class in swift
class ListItem: NSObject {
let itemName: String
var completed: Bool

init(itemName: String, completed: Bool = false)
{
self.itemName = itemName
self.completed = completed
}
}

When I refer to this class in my TableViewController, I get the following error:
"Instance member itemName cannot be used on type ListItem".
My TableViewController code (cellForRowAtIndexPath method) is shown below.
    let tempCell = tableView.dequeueReusableCellWithIdentifier("triggerCell")! as UITableViewCell
    let listItem = listItems[indexPath.row]

    // Downcast from UILabel? to UILabel
    let cell = tempCell.textLabel as UILabel!

    cell.text = ListItem.itemName

    if (ListItem.completed)
    {
        tempCell.accessoryType = UITableViewCellAccessoryType.Checkmark;
    }
    else
    {
        tempCell.accessoryType = UITableViewCellAccessoryType.None;
    }

    return tempCell
}

I'm probably making a basic error, but I can't seem to identify where I'm going wrong.

A: You're calling the class instead of your instance. Try this:
cell.text = listItem.itemName

if (listItem.completed)
etc...

EDIT: Updating the creation of listItems.
let listItems = [ListItem("Viruses"), ListItem("Changes in weather"), etc...]


text:
Q: Kivy returning black screen on wi I have been developing a mobile app in Kivy. However, I deleted something in the .py file (cant remember what) and now I cannot get anything other than a black screen when I run the program. I made the .py and .kv files as simple as possible to reduce points of failures and it still doesnt work.
Here is the .py file:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.text import LabelBase
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from time import strftime
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy import Config
Config.set('graphics', 'multisamples', '0')

class Anasayfa(Widget):
    pass

kv = Builder.load_file(r"C:\Users\Casper\Desktop\my.kv")
class myApp(App):
    def Build(self):

        return (kv)

if __name__ == "__main__":

    myApp().run()

There are some unnecessary stuff on import section, they are from the development of the actual app.
Here is the .kv  file:
<Anasayfa>
    GridLayout:
        cols:1
        Label:
            text:"Coming soon"
            color: 1,1,1,1

Thats all, I made both files dead simple and they still dont work. There are no error messages, just a black screen and a mouse cursor. The black screen is in full screen as well, but widgets didnt cover the screen when things did work(think of it like viewing a phone screen on a laptop screen).
Here is the event log:
[INFO   ] [Logger      ] Record log in C:\Users\Casper\.kivy\logs\kivy_20-08-26_13.txt
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "C:\Users\Casper\anaconda3\envs\CasperEnv\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.7 (default, May  6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\Casper\anaconda3\envs\CasperEnv\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.5.0 - Build 25.20.100.6373'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) HD Graphics 520'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 5
[INFO   ] [GL          ] Shading version <b'4.50 - Build 25.20.100.6373'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [Base        ] Start application main loop
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [Base        ] Leaving application in progress...
[INFO   ] [WindowSDL   ] exiting mainloop and closing.

I would be grateful if someone can tell me what is wrong, because I have no idea what is wrong here. Thank you.

A: Your kv file does not create a root widget, it only creates a rule. You can change:
<Anasayfa>

to:
Anasayfa:

so that it creates a root widget.
Another problem is your myApp definition. It should have a build() method, not a Build() method. Likely just a typo.

A: what about folks who still can't get anything to display on the screen?

    GridLayout:
        cols:1
        size: root.width, root.height
    GridLayout:
        cols:2

        Label:
            Text: "username"

        TextInput:
            multiline:False

        Label:
            Text: "password"

        TextInput:
            multiline:False

    Button:
        text: "confirm"#then save it and run the code


text:
Q: Simple power program I was asking today about power program. So, I almost figure out ho to do it and I want to ask, how to add, numbers before lines(like 1 is; 2 is; and etc.). So the program is
#include<iostream>
using namespace std;

int exponentiation(int base, int exponent);

int main(void)
{

 for(int i = 0; i <= 10; ++i)
   cout << exponentiation(i, i) << '\n';
}

int exponentiation(int base, int exponent){

int result = 1;
for (int i = 0; i < exponent; ++i)
result = result * base;
return result;
}

Output goes line by line
                      ....
                      .......
                      ..............

and I want to make it looks like this:
                      1 is ....
                      2 is .......
                      3 is ..............

I was trying to make a cout loop and add in code above, but it doesn't work:
           #include<iostream>
           using namespace std;
           int exponentiation(int base, int exponent);

         int main(void) {

         for(int c = 1; c < 10; c++)
         {
           cout << c << " is ";
           for(int i = 0; i <= 10; ++i)
           cout << exponentiation(i, i) << '\n';
            cout << endl;
           }

           }

           int exponentiation(int base, int exponent) {
           int result = 1;
           for (int i = 0; i < exponent; ++i)
           result = result * base;
           return result;
              }

A: You already have the perfect loop ready and waiting in your original program. Why do you need to add a new one? All you need to do is add stuff to the line on which you print exponentiation(i, i):
int main()
{
   for (int i = 0; i <= 10; ++i)
      cout << (i+1) << "is: " << exponentiation(i, i) << '\n';
}

It's really as easy as that!


text:
Q: Regsvr32 .dll registration. How can i build my own Setup? How can i build my own Setup to register a .dll file?
My puplished programm missing one .dll and its necessary for starting.
i referenced it to my program but i cannot toggle "save on local" to True. its not checkable.
Now i want to create installer for this problem.
How can i do this? the installer have to run this in cmd: regsvr32 file.dll
i tried to make a batch but all batch codes for regsvr32 dont work. not on my and not on other computers. i tried it so long and hope someone have a idea.

A: Well I assume your dll was built targeting .net 4 so regsrv32 will not work (Win32 only).
What you need to use is regasm, which is buried in the .net framework folders - one each for 32 & 64 bit.
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\regasm  my_32_bit.dll
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\regasm my_64_bit.dll

regasm options;
Microsoft .NET Framework Assembly Registration Utility version 4.8.4161.0
for Microsoft .NET Framework version 4.8.4161.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Syntax: RegAsm AssemblyName [Options]
Options:
/unregister          Unregister types
/tlb[:FileName]      Export the assembly to the specified type library
                     and register it
/regfile[:FileName]  Generate a reg file with the specified name
                     instead of registering the types. This option
                     cannot be used with the /u or /tlb options
/codebase            Set the code base in the registry
/registered          Only refer to already registered type libraries
/asmpath:Directory   Look for assembly references here
/nologo              Prevents RegAsm from displaying logo
/silent              Silent mode. Prevents displaying of success messages
/verbose             Displays extra information
/? or /help          Display this usage message

A: There are a number of installer technologies available to help build an installation package for Windows. My personal preference is the WIX Toolset.
While you may be able to accomplish what you are asking via some type of script, it's a best practice to create an installation package (such as an .msi or setup.exe).
A mature tool such as WIX will help with things such as cleaning up the system on uninstall, rolling back properly if the installation fails for some reason, logging which can help with troubleshooting, etc., which all wouldn't be covered by a simple script.


text:
Q: assignment operator for a vector of unique_ptr's I am experimenting with smart pointers and try to exchange a few shared_ptr's with unique_ptr's in my project to see if I can gain little performance improvements.
I have the following code snippt:
// --- probably can be replaced with with std::copy ...
if (j != sentences.size()) {
    // also gives me an error if I initialize vector with a size.
    std::vector<unique_ptr<StemmedSentence> > newSentences(j);
    int base = 0;
    for (size_t i = 0; i < j; i++) {
        newSentences[base++] = std::move(sentences[i]); // std::move ??
    }
    sentences = newSentences; // std::move, i guess not !?
}

I copy a vector of pointers into a new vector (in this case a vector of unique_ptr's). Using shared_ptr, this is no problem at all. As I understand, shared pointer uses the implicit assignment, all is working fine. With unique_ptr though, I need to overload the assignment operator (to transfer ownership) and this gives me quiet a headache.
I created this assignment:
ArrayStemmedSnippet& operator=(const ArrayStemmedSnippet& other) {
    if (this != &other) {
        sentences.clear();
        std::vector<unique_ptr<StemmedSentence> >::const_iterator it;
        for (it = other.sentences.begin(); it != other.sentences.end(); ++it) {
            sentences.push_back(std::unique_ptr< StemmedSentence >(*it ?
                *it : std::unique_ptr< StemmedSentence >())); // --- compiler error
        }
        return (*this);
    }
}

The pointers to copy can contain "Null" pointers. I try to check this in the for loop
and copy either the pointer or an empty unique_ptr instance (a nullptr).
That line marked with compiler error gives me a problem, I can not figure out the correct syntax. Also I think I have to create a new pointer (clone) if I copy a non-null object. Can somebody please give me a hint on that?
I found a similar post Handling smart pointers in stl container, the answer from Howard Hinnant gave me the inspiration to give it a try. But I can not use that syntax, I have gcc version 4.4.3 on my testmachine.
I have no clue if I will gain more performace, like I said, I experiment. As far as I know I would have no ownership problems in my code, so I thought making a test with unique_ptr and skip the shared_ptr (with all its overhead) might be a little gain in performance. I have about 5 objects where I use shared_ptr, so I would give it a try.
If all this makes no sense, let me know if it is worth playing arround with uniqe_ptr at all.
Thanks in advance!

A: The question makes little sense. The decision of using shared_ptr or unique_ptr should be taken based on whether ownership is shared or unique. The question is focusing on the details of forcing a change in the design that is probably not wanted.
In the original design, multiple vectors holding shared_ptr and sharing the ownership of some other objects, but in the modified approach, because unique_ptr has unique ownership you will be forced to copy the objects. The side effects of the change are multiple: now you need to copy the objects (higher cost). Because the type is a base, you need to implement a clone() approach so that the objects are not sliced, that will also have a (minimal) cost. After the copies are made the vectors will no longer refer to shared objects, so that a changed performed through one of them will not be visible through the rest, changing the semantics.
At this point, I can only start thinking whether you have profiled your code, and how much of the cost of the application is in the copying of the shared pointers, because that is not an expensive operation. My feeling is that you might be barking at the wrong tree, spending time unnecessarily and breaking your application in the process, with a much more obscure approach for nothing.
Sorry to sound negative, but I feel that you should really think this through. unique_ptr is not a replacement to shared_ptr, unless shared_ptr was the wrong solution from the start (objects should not really be shared), but that does not seem the case, since in your current program you are copying the pointers to different containers, and thus sharing.

If what you want is to compact the vector, you don't need copies at all, or even coding:
// [untested, but you can build on top of this]
typedef std::vector< std::unique_ptr< StemmedSentence > > vector_t;

vector_t v = ... // build the vector
// compact:
v.erase( std::remove( std::make_move_iterator( v.begin() ),
                      std::make_move_iterator( v.end() ),
                      std::unique_ptr<StemmedSentence>()
                    ).base(),
         v.end() );

But this should not be implemented as operator= on the enclosing type taking a constant reference. unique_ptr cannot share ownership, so if the pointers are moved to the new container, then the old container is going to be emptied (this could fit a moving operator=, but not one that promises not to modify the original container.


text:
Q: При отправке формы перезагружается страница Вот скрипт, при отправке формы перезагружается страница. Почему?
        <script>
    (function ($) {
    $(document).ready(function(){
        $('#btn_submit').click(function(){
            var name     = $('#name').val();
            var tel      = $('#tel').val();
            $.ajax({
                url: "send.php",
                type: "post",
                dataType: "json",
                data: {
                    "name":     name,
                    "tel":  tel
                },
                success: function(data){
                    $('.messages').html(data.result);
                }
            });
        });
    });
    }(jQuery));
</script>

A: Нужно отменить стандартное поведение браузера по нажатию кнопки с type="submit":
$('#btn_submit').click(function(e) {
  console.log("test click");
  e.preventDefault();
  var name     = $('#name').val();
  var tel      = $('#tel').val();
  $.ajax({
    url: "send.php",
    type: "post",
    dataType: "json",
    data: {
      "name":     name,
      "tel":  tel
    },
    success: function(data){
      console.log("test success");
      console.log("data = ", data);
      $('.messages').html(data.result);
    },
    error: function(xhr, status, error) {
      console.log("test error");
      console.log(xhr, status, error);
    }
  });
});

console.log(jQuery.fn.jquery);
$("#btn").click(function(e){
  e.preventDefault();
  console.log("test");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form>
<input/>
<button type="submit" id="btn">Click</button>
</form>

A:

(function ($) {
    $(document).ready(function(){
        $('#___form_id___').submit(function(e){
            e.preventDefault();
            var name = $('#name').val();
            var tel = $('#tel').val();
            $.ajax({
                url: "send.php",
                type: "post",
                dataType: "json",
                data: {
                    "name": name,
                    "tel": tel
                },
                success: function(data){
                    $('.messages').html(data.result);
                }
            });
        });
    });
}(jQuery));


text:
Q: How to solve MySQL subquery with joins? Is there a way to retrieve the result from the given tables? Tbh I have no idea how to accomplish this with subqueries. Current examples are full with datetime cases. I find them immensely confusing...
Table #1
** red **
|id| green_id |
|--| ---------|
|1 | 1        |
|2 | 2        |
|3 | 3        |

Table#2
**green**
|id| blue_id | enum |
|--| --------|------|
|1 | 1       |100   |
|2 | 1       |101   |
|3 | 1       |102   |
|4 | 2       |105   |

Table#3
**blue**
|id| title |
|--| ------|
|1 | abc   |
|2 | def   |
|3 | ghi   |

MySQL query
SELECT
    r.*,
    g.enum AS g_enum,
    ???????? g.enum_max ????????? <--- how
    b.title AS b_title
  FROM red AS r
  LEFT JOIN green AS g
    r.green_id = g.id
  LEFT JOIN blue AS b
    g.blue_id = b.id
  WHERE
    r.id = 1

Where g.enum_max would be:
SELECT MAX(enum) FROM green WHERE blue_id = 1

Result where r.id=1
|id| green_id | g_enum | g_enum_max | blue_title |
|--| ---------|--------|------------|------------|
|1 | 1        | 100    | 102????    | abc        |

A: Use a subqUery for thaT
SELECT
    r.*,
    g.enum AS g_enum,
    (SELECT MAX(enum) FROM green WHERE blue_id = g.blue_id) g_enum_max ,

    b.title AS b_title
  FROM red AS r
  LEFT JOIN green AS g ON
    r.green_id = g.id
  LEFT JOIN blue AS b ON
    g.blue_id = b.id
  WHERE
    r.id = 1


text:
Q: How do I offset orientation coordinates (Euler or Quaternion) by a 'calibration' orientation? I have a device called the Myo Armband and am using the orientation data it's outputting to control the position of an 'arm' in python (using Vizard for the rendering). Right now, I have it where I can do
arm.setQuat(armbandQuat)

and it kinda works. Up and down are accurate, but rotation about the vertical axis starts in a random direction each time. To fix this, I made it so that when you press the spacebar it records the offset quaternion. What I want to happen is that whenever you press space, the arm onscreen goes to a set '0' position and all motion about the vertical axis will be relative to that. In other words, the user will press space with their arm horizontal to calibrate it.
What do I need to do with these two quaternions to setQuat to the correctly rotated coordinates? Originally I thought you could just multiply the two quaternions together (or the inverse of the second), but if one is 0,0,0,0 then the arm will be frozen at 0,0,0,0.
I can also get and set Euler coordinates instead, if that's easier. It seems like quaternions are more of a perfect system for rotations like this though.
I think it should be somewhat simple, but I've spent hours looking up the answer and trying things out and nothing works.


text:
Q: MySQL: Treating a whole expression as a string Is there any way to treat a whole part of a regular expression as a string?
Example:
WHERE `head` REGEXP '" . implode("|", $selectedHEADs) . "'

where $selectedHEADs can be filled with $, |, /, \ and all kinds of special-characters. I want to match those as normal letters. Is there any PHP-function or any "tweaks" in MySQL to make this available?
Just so you know, I only want each of the items to be treated as strings, the | between them in the "implode" should still be treated as a separator between different patterns.


text:
Q: Why backticks command exit first while testing? If I open pry and run
o = `npm outdated`

I get the behavior that I expect, it blocks everything until the npm command return and store the output.
The same code, in a test:
def get_outdated
 o = `npm outdated`
end

def test_get_outdated
 assert_equal(true, get_outdated().length > 1)
end

Fail because if I print the o before return it is empty, and I noticed that the test runs way faster so it is impossible that it waits until the command finishes.
Printing the exit code of the process it show no errors.
puts $?.success? #=> true

A: Seems pretty likely that your environment is different in testing than in pry. One thing you could check is if you have any packages installed at all:
puts `npm ls`

With no packages installed or if all of your packages are updated, npm outdated returns immediately with no output and a successful return code. That would be consistent with the behavior you are observing.
You could also try running npm config ls -l to verify your configuration is the same both ways you are running the command.


text:
Q: jquery ajax call fails ie7 I have the following function, which works in Firefox but not IE7:
function flagDocRead(currentdocid, currentuserid){

   alert(currentdocid);

   alert(currentuserid);

   $.get("./blocks/rc_importantdocs/flagdocread.php",{ docid: currentdocid, userid:    currentuserid });

}

currentdocid and currentuserid are both integers.
IE7 fails with "Object doesn't support this property or method".
Thanks in advance for any advice.

A: OK I fixed this by going to Tools->Internet Options->Advanced->[Security section]-> then Uncheck "Enable Native XMLHTTP support"


text:
Q: Dynamically draw outline oval over a view I am working with a custom UI element highlights.So I need to draw a half ellipse like shape over a particular view on runtime.
For example:
I have to draw a yellow color half ellipse over a white ellipse.

Help will be appreciated.

A: public class MyView extends View {

    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {

        // TODO Auto-generated method stub
        super.onDraw(canvas);
        float width = (float) getWidth();
        float height = (float) getHeight();
        float radius;

        if (width > height) {
         radius = height / 4;
        } else {
         radius = width / 4;
        }

        Path path = new Path();
        path.addCircle(width / 2,
         height / 2, radius,
         Path.Direction.CW);

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.FILL);

        float center_x, center_y;
        final RectF oval = new RectF();
        paint.setStyle(Paint.Style.STROKE);

        center_x = width / 2;
        center_y = height / 2;

        oval.set(center_x - radius,
            center_y - radius,
            center_x + radius,
            center_y + radius);
        canvas.drawArc(oval, 90, 180, false, paint);
    }
}

Add
new MyView(this)


text:
Q: Why does an actor start twice? I start the child actors only once as follows:
object DetectorSupervisor {

  def create(): Behavior[NotUsed] =
    Behaviors.setup { context =>

      context.log.info(s"=============> Start DetectorSupervisor <=============")

      val informant = context.spawn(InformantActor.create(Vector.empty), "InformantActor")
      val stateMachine = context.spawn(DetectorStateMachine.create(informant,
        State(KafkaInactiveConfirmed, SapInactiveConfirmed)), "StateMachine")

      context.spawn(DetectorReceptionActor.create(informant), "ReceptionActor")

      context.spawn(KafkaDetectorActor.create(stateMachine, None), "KafkaActor")
      context.spawn(SapDetectorActor.create(stateMachine, None), "SapActor")

      Behavior.empty

    }

}

And in the log, I can see, that an actor always starts twice.
[INFO] [07/03/2019 22:21:35.513] [testSystem1-akka.actor.default-dispatcher-2] [akka://testSystem1/user/DetectorSupervisor] =============> Start DetectorSupervisor <=============
[INFO] [07/03/2019 22:21:37.456] [testSystem1-akka.actor.default-dispatcher-3] [akka://testSystem1/user/DetectorSupervisor/InformantActor] =============> Start InformantActor <=============
[INFO] [07/03/2019 22:21:37.460] [testSystem1-akka.actor.default-dispatcher-3] [akka://testSystem1/user/DetectorSupervisor/StateMachine] =============> Start DetectorStateMachine <=============
[INFO] [07/03/2019 22:21:37.460] [testSystem1-akka.actor.default-dispatcher-3] [akka://testSystem1/user/DetectorSupervisor/ReceptionActor] =============> Start DetectorReceptionActor <=============
[INFO] [07/03/2019 22:21:37.473] [testSystem1-akka.actor.default-dispatcher-4] [akka://testSystem1/user/DetectorSupervisor/SapActor] =============> Start SapDetectorActor <=============
[INFO] [07/03/2019 22:21:37.473] [testSystem1-akka.actor.default-dispatcher-5] [akka://testSystem1/user/DetectorSupervisor/KafkaActor] =============> Start KafkaDetectorActor <=============
[INFO] [07/03/2019 22:21:37.503] [testSystem1-akka.actor.default-dispatcher-5] [testSystem1] =============> Start KafkaDetectorStream <=============
[INFO] [07/03/2019 22:21:37.503] [testSystem1-akka.actor.default-dispatcher-4] [testSystem1] =============> Start SapDetectorStream <=============
[INFO] [07/03/2019 22:21:43.950] [testSystem1-akka.actor.default-dispatcher-3] [akka://testSystem1/user/DetectorSupervisor/InformantActor] =============> Start InformantActor <=============

As you can see, the InformantActor starts twice and I could not figure out why.
Here is the implementation of InformantActor:
object InformantActor {

  sealed trait InformantEvent

  case object ServerOnlineConfirmed extends InformantEvent

  case object ServerOfflineConfirmed extends InformantEvent

  case class SubscribersChanged(actor: Vector[ActorRef[ServerEvent]]) extends InformantEvent

  def create(subscribers: Vector[ActorRef[ServerEvent]]): Behavior[InformantEvent] =
    Behaviors.setup { context =>

      context.log.info(s"=============> Start InformantActor <=============")

      Behaviors.receiveMessage[InformantEvent] {
        case ServerOfflineConfirmed =>
          subscribers.foreach(a => a ! ServerOfflineApproved)
          Behavior.same
        case ServerOnlineConfirmed =>
          subscribers.foreach(a => a ! ServerOnlineApproved)
          Behavior.same
        case SubscribersChanged(actors) =>
          create(actors)
      }
    }

}

The source code is hosted on https://gitlab.com/sweetsoft/plugger.

A: I don't think, it is started twice.
Your create funciton is recursive and executed whenever case SubscribersChanged(actors) => happens.
So whenever your list of subscribers changes, you will see your log message.
You refactor create to exclude the log message from recursion ... something like this:
def create(initialSubscribers: Vector[ActorRef[ServerEvent]]): Behavior[InformantEvent] = {
  Behaviors.setup { context =>

    context.log.info(s"=============> Start InformantActor <=============")

    def behavior(subscribers: Vector[ActorRef[ServerEvent]]): Behavior[InformantEvent] = Behaviors.receiveMessage[InformantEvent] {
      case ServerOfflineConfirmed =>
        subscribers.foreach(a => a ! ServerOfflineApproved)
        Behavior.same
      case ServerOnlineConfirmed =>
        subscribers.foreach(a => a ! ServerOnlineApproved)
        Behavior.same
      case SubscribersChanged(actors) =>
        behavior(actors)
    }

    behavior(initialSubscribers)
  }
}


text:
Q: Getting an 'Undefined index' error for 'Same as Above' field I have a form field with items
    <label for='usrad_resi'>
Residential Address </label><input id='usrad_resi' name='usrad_resi' type='text' required>

Upon clicking a 'same as above' checkbox I managed to get the value in another textbox:
    <label for='co_addrcheckl'>
        Address </label><input type='checkbox' name='co_addrcheck' id='co_addrcheck' onSelect='sameAbove()'> Same as Above
    </li>
    <li>
        <label for='usrad_co_addr'>
        C/O Address </label><input id='usrad_co_addr' name='usrad_co_addr' type='text' required>

The javascript for this is:
   var loc = document.getElementById('co_addrcheck');
   var home = document.getElementById('usrad_co_addr');
   var post = document.getElementById('usrad_resi');
   loc.onclick = function(){if(loc.checked)
   {
        home.disabled = true; home.value = post.value;}
   else
   {home.disabled = false; home.select();}}

My problem is that when trying to access $_POST['usrad_co_addr'] using php i get an 'Undefined index: usrad_co_addr' error. This happens irrespective of whether the 'usrad_resi' field is empty or not.
Any reason why this is happening?

A: You set that field to disabled in javascript. Disabled fields are not submitted. If you want to keep behaviour and still submit the value as well you could create a hidden field and also copy the data there.

A: What hoppa said is true. Disabled fields are not submitted. What you can do is use a hidden object to send this data.
<input id='usrad_co_addr' type='text' required />
<input id='usrad_co_addr_h' name='usrad_co_addr' type='hidden' />

And in your Javascript:
   var loc = document.getElementById('co_addrcheck');
   var home = document.getElementById('usrad_co_addr');
   var home_h = document.getElementById('usrad_co_addr_h');
   var post = document.getElementById('usrad_resi');
   loc.onclick = function(){
       if(loc.checked)
       {
           home.disabled = true;
           home.value = post.value;
       }
       else
       {
           home.disabled = false;
           home.select();
       }
       home_h.value = home.value;
    }


text:
Q: [UICTFont isEqualToString:]: unrecognized selector sent I am facing this issue with Xcode 9 and ios 11 only. Not even getting a back trace of where it is occuring. The app just crashes by giving me this error.

A: When you describe a key-value pair for NSFontAttributeName with NSDictionary and if you attempt to set object as a key and key as an object, it will crash with [UICTFont isEqualToString:]: unrecognized selector sent error.
An example in Objective-C:
NSDictionary *attributedDictionary = [NSDictionary dictionaryWithObject:NSFontAttributeName forKey:[UIFont systemFontOfSize:15]];

In the example, the attribute name is set for the object and the object is set for the key. So you must fix it.
It will crash with error what you have.

A: I have a smilier issue on iOS 11, I was using
self.title = @"Select places";
in viewDidLoad to set the title, that was causing an issue when I add a search bar to NavigatonBar the crash need to further debug to root cause.
Hope this helps for debugging the issue in your case.


text:
Q: How to display image in Django templates with the same image name In views.py
def list_image(request):
    if form.is_valid():
        list_image = form.cleaned_data['list_image']
        return render(request, "list.html", ...) // How to give list_image to query_image

def query_image(request):
    if form.is_valid():
        query_image = form.cleaned_data['query_image']
        list_image = ??? //I also want to get list_image here,and display in all_image.html
        return render(request, "all_image.html", ...)

I can display image in list.html or query.html well.
Now I want to display images from list_image and query_image in all_image.html.But how?

A: If query_image and list_image are came from the same form, you can do this:
Try to
def query_image(request): #it woul be better to rename it to all_image
    if form.is_valid():
        query_image = form.cleaned_data['query_image']
        list_image = form.cleaned_data['list_image']
        my_context = {'query_image': form.cleaned_data['query_image'],
                      'list_image': form.cleaned_data[]
                      #... any other data}
        return render(request, "all_image.html", my_context)

And you have to make sure that all_image.html renders list_image somehow (using django templates for, for example)


text:
Q: Jmeter assertions on random controller Will there be a difference in results when we add response assertion, duration assertion to controllers instead of thread?

A: I don't know what "thread" is in your world, but Assertions obey JMeter Scoping Rules so you can apply one or more assertions to:

*

*a single Sampler

*several Samplers

*all Samplers in the Thread Group

*all Samplers in the Test Plan
Here is the image from the How to Use JMeter Assertions in Three Easy Steps article showing how do scoping rules work:


text:
Q: I need help assigning the output from a JS Json result to a variable and displaying it in HTML Here is what I have so far. I want to put the result in a variable, which then I will work with. I would also like to display the result/variable on a webpage. How can I do this?
<button onclick="function startRefresh()">Get Rates</button>

A: Not sure exactly what you are trying to do, but maybe this:
<button onclick="startRefresh()">Get Rates</button>

A: $(function () {
    $("#load-button").click(function(){
        startRefresh();
    });
});

function startRefresh() {
    //alert("hi");
    //setTimeout(startRefresh, 10000);
    var turl = 'https://btc-e.com/api/2/ltc_usd/ticker';
    var results = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(turl) + '%22&format=json', function (data) {
        var result = data.query.results.ticker;
        var html = "";
        for(var key in result){
            html += '
' + key + ' = ' + result[key] + '

';
        }
        $("#mydiv").html(html);
    });

}

DEMO FIDDLE.


text:
Q: Ubuntu server burn in test We've assembled a simple storage server with COTS SATA disks that we're planning to tie together with software raid (Ubuntu Server, mdadm). What burn-in tests can one run to test the system, in particular the disks since they're brand new?

A: Use DriveStress to test the drives. See: http://www.roylongbottom.org.uk/linux%20burn-in%20apps.htm#anchor7 for more info


text:
Q: ionic native api not working with vue, how to achieve it? when i install
npm install cordova-plugin-native-ringtones in my ionic vue project got this following error
Failed to compile.
./node_modules/@ionic-native/native-ringtones/ngx/index.js
Module not found: Error: Can't resolve '@angular/core' in '/Users/afzal-8396/Desktop/other_frameworks/ionic/myApp/node_modules/@ionic-native/native-ringtones/ngx'

A: you dont import the ngx..
from the documentation...
npm install cordova-plugin-native-ringtones
npm install @ionic-native/native-ringtones
ionic cap sync

in yout file
import { NativeRingtones } from '@ionic-native/native-ringtones

NativeRingtones.getRingtone().then((ringtones) => { console.log(ringtones); });


text:
Q: Is every open subset of a locally compact Hausdorff space, locally compact in the subspace topology? I tried proving it but I didn't use the fact of the subspace topology at all, therefore, I am doubting the correctness of the proof.
Let $X$ be a locally compact Hausdorff space and $Y$ an open subset of $X$. Since $X$ is a locally compact Hausdorff space, it is a regular space and since regularity is hereditary $Y$ is a regular space. Choose a random $x\in Y$ and a $U\subset Y$ such that $\overline{U}\subset Y$ with $x\in U$, we can do this because $Y$ is regular. since $\overline{U}$ is the closure of an open set in a locally compact space we know that $\overline{U}$ is compact in $X$. Therefore for every open cover of $\overline{U}$, there exists a finite subcover of $\overline{U}$. Because $Y$ is open in $X$, the intersection of (any open cover of $\overline{U}$ in $X$) and $Y$, would still be an open cover of $\overline{U}$ in $X$ therefore there exists a finite subcover for this open cover contained in $Y$. therefore $\overline{U}$ is compact in $Y$ which implies that $Y$ is locally compact.

A: $\mathbb R$ is locally compact. $U=\mathbb R$ is open in it. The closure $\overline {U}$ is not compact. So your assumtion that the closure of an open set in a locally compact space is compact is false.

A: Let $X$ be a locally compact Hausdorff space and $Y$ an open subset of $X$. Since $X$ is locally compact and Hausdorff $X$ is regular.
Choose $x\in Y$, then there exists an open $U\subset X$ such that $\overline{U}$ is compact in $X$ with $x\in U$.
Choose $V$ such that $\overline{V}\subset U$ and $\overline{V}\subset Y$ with $x\in V$ we can do this because $Y$ is regular.
So $\overline{V}$ is a closed subset of a compact set, therefore $\overline{V}$ is compact in $X$. Therefore for every open cover of $\overline{V}$ there exists a finite subcover. The intersection of any open cover of $\overline{V}$ and $Y$ is open in $X$ because $Y$ is open, therefore for every open cover of $\overline{V}$ in $Y$ there exists a finite subcover in $Y$, therefore $Y$ is locally compact.

A: Let O be an open subset and assume x in O.
Since X is regular,
exists open U with x in U, $\overline U \subseteq O.$
Since X is locally compact,
exists open V with compact closure and x in V subset U.
Hence the compact closure is a subset of O.
Thus O is locally compact.

A: Let $x$ be in $Y$, and as $X$ is locally compact and regular and $Y$ is open, it has an open neighbourhood $V \subseteq Y$ with compact closure $\operatorname{cl}_X(V) \subseteq Y$. Then $V$ is open in $Y$, contains $x$ and $\operatorname{cl}_Y(V) = \operatorname{cl}_X(V) \cap Y = \operatorname{cl}_X(V)$ which is compact (in $X$ or $Y$ that does not matter, it's absolute). So $Y$ is locally compact Hausdorff.


text:
Q: Deny login if session exists in database I have a php login system implemented in my script. How would I make a script that denies a user to login if there is an existing session in the database?
For example,
User 1 logs into system > Login accepted
User 2 logs into system with same account as user 1 > Denies because another session exists.
that's how I want it to work.
Thanks.

A: store your sessionId in your db and then reject the login attempts for users with different sessionID if the last access time is recent(calculate by finding the difference between the last login time to current time).clear ID on logout

A: There should be a new field in your users table which named as logged_in. When authenticating check this field what value it has.
If it is 0 / false let the user log in and set the logged_in field to 1/true.
else if logged_in field is 1/true do not let the second user log in.
Do not forget to set the logged_in field to 0/false when logging out.

A: Good question.
If you are refering to PHP session: You could store the session ID (and last access time) in a database, and reject login attempts for users with different session IDs if the last-access time is too recent(say, within the past 20 minutes). Clear the ID on logout, of course.
Note, though, if a user closes their browser without logging out and then reopens it, they may well be locked out for a while (the 20 minutes above, or whatever interval you decide on), since they won't have the matching session cookie anymore.
If you are refering to DB session: You have to configure the Setting Account Resource Limits in your Mysql DB like in this link. But the problem here is that the number of simultaneous connections to the server by an account is available only as of MySQL 5.0.3.
If you are refering to REAL-TIME cheking then you can use COMET Programming to push data to a browser, without the browser explicitly requesting it.

A: For that
you have to store session values in database. and then when other user login with same details. you can check it from database that already one user online with same login details

A: I would place another field into database called, for instance, last_seen. Each time logged in user produce request - just put current date into that field.
When someone tries to log in - just check how long ago user were seen on site. If more than session timeout time (20 minutes by default) - you may consider that users is logged out and allow login.
Otherwise - deny login.
You can't figure out for sure if user is still using your site or no. You may put 1/0 in some field when user logs in/out, but nobody can guaranty that user will click logout link before closing tab.
But you may improve behavior of your site by setting that new field to null when user clicks logout link. Otherwise it may happen that someone logged out and now tries to do login again, but can't do that because system still handle his account as being used.


text:
Q: sudo still ask for password when NOPASSWD is used I read all sudo posts on serverfault, but I still cannot figure out what I'm doing wrong. Normally I finally find the solution but not this time :
I want apache user to be able to execute this command as user "hremotessh" :
sudo /home/hremotessh/scripts/redirect.sh 8892 8893

Therefore I added this in visudo :
apache ALL=(hremotessh) NOPASSWD: /home/hremotessh/scripts/redirect.sh

But sudo is still asking the password ?
sudo /home/hremotessh/scripts/redirect.sh
[sudo] password for apache:

I tried this, but not better :
sudo -u hremotessh /home/hremotessh/scripts/redirect.sh
hremotessh is not in the sudoers file.  This incident will be reported.

Any idea would be warmly welcomed :-)
Denis

A: Unless you want to run the command as root you need to specify the username, so
 su - apache -s /bin/bash
 sudo -u hremotessh /home/hremotessh/scripts/redirect.sh 8892 8893

is the correct syntax to test the sudo command.
Since you're not prompted for the apache user's password sudo seems to be configured correctly.
The resulting warning: hremotessh is not in the sudoers file. indicates that another sudo command is used in the redirect.sh script. And there's no (valid) sudo policy for that user.

A: I had a similar problem when trying to run a python3 code as sudo from a script and cound't enter password from the script. The solution was to edit visudo so that python3 would run as sudo without prompting the password, NOT run the python3 script as sudo. So I believe you need to run apache as sudo without prompting for password, NOT running the .sh script as sudo without password.


text:
Q: Storing string variable contains with comma and new line as value to CSV in R i am trying to save this two objects into a csv file , this i used inside function that is why i used append write.table
dt <- "Error in .verify.JDBC.result(r, \"Unable to retrieve JDBC result set for \",  : \n  Unable to retrieve JDBC result set for SELECT * FROM rAXA (ORA-00942: table or view does not exist\n)\n"
er <- "error"
er_file <- cbind(er,dt)
write.table(er_file, file = "E:\\Hama_Hex\\Project\\Predictive\\log1.csv",sep=",",
        col.names = FALSE, append=TRUE)

but when i execute the above script its not properly saving into csv file, the special character \n in dt object is creating problem , it making to move new line . i want to store entire line in one cell. Here i am saving in csv format, value has some comma so it got splits and enter into new cell.

A: You just need to escape the newline characters:
write.table(gsub("\\n", "\\\\n", er_file),
            file = "E:\\Hama_Hex\\Project\\Predictive\\log1.csv",sep=",",
            col.names = FALSE, append=TRUE)

This will replace every \n with \\n. Note in the above code that you have to escape the \ characters in order to create a usable regular expression for gsub.


text:
Q: Setting min-width of mat-select-panel leaves a visible animation in Angular 2+ I am trying to re-position a mat-select-panel, to be below the corresponding dropdown form-field. Using some of the code provided in here, I have been able to do that. The problem is, that upon clicking, you can see the panel change size. This behaviour is visible in the stackblitz provided in the same question and accepted answer. So far I haven't been able to find a solution.
Currently my .mat-select-panel in styles.css looks like this:
.mat-select-panel {
  position: absolute;
  top: 94px;
  left: 28px;
  min-width: calc(100% + 24px) !important;
  border-radius: 0px !important;
  border-top-style: none;
}

A:
There is jump animation added to <mat-select> by angular
  material, that's the reason it looks like width is increasing.

Simple solution is to disable animation, but I could not find a solution to disable animation on specific element/component
As said/discussed here and here

To disable animation on single elements or material components

//TS
isDisabled = true;

//HTML
<div [@.disabled]="isDisabled">
 <div [@childAnimation]="exp"></div>
</div>

<mat-form-field appearance="outline">
 <mat-select [@.disabled]="isDisabled" placeholder="Favorite food" disableOptionCentering>
  <mat-option *ngFor="let food of foods" [value]="food.value">
   {{food.viewValue}}
  </mat-option>
 </mat-select>
</mat-form-field>

But unfortunately that doesn't work for <mat-select>

To disable animation for component

export class YourComponent {
 @HostBinding('@.disabled')
 public animationsDisabled = true;
}

This doesn't work either.
What works is ?

Disabling animation for material cdk overlay (Include all material components) from component

import { Component, Renderer2 } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
...
overlayContainerElement: HTMLElement
constructor( private overlayContainer:OverlayContainer, private renderer:Renderer2) {
    this.overlayContainerElement = this.overlayContainer.getContainerElement();
    //To disable pass true as third argument
    this.renderer.setProperty( this.overlayContainerElement, "@.disabled", true );
}

Note: The above code disables animation for whole application, if you want to disable animation for your specific component, simply add the above code in your component and add below code to re-enable animation.
ngOnDestroy() {
 this.renderer.setProperty( this.overlayContainerElement, "@.disabled", false );
}

To disable animation for whole application

You can add the above code in main component (i.e., app.component.ts) or
Replace BrowserAnimationsModule with NoopAnimationsModule in app.module.ts
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
...
@NgModule({
  imports:      [ NoopAnimationsModule ],
  declarations: [ ... ],
  bootstrap:    [ ... ]
})

Working example (Animation disabled for component).