text:
Q: Infinite loop in Fortran This is my code in Fortran 90
program final
   implicit none
   real, dimension(421,422) :: a
   real :: temp,factor
   real, dimension (421) :: soln
   integer :: i, rmax, pivot, row,n, O,P,COL,k,a_j,n2,a_i,t

   open(unit=177241,file="input_21.txt",status="old")
   open(unit=20,file="output.txt",status="unknown")

   do i =1,421
      read (177241,*) (a(i,:))
   end do
   do i = 1,421
      print *,a(i,13)
   end do
   do T=1,421
      n=421
      a_i=n

      n2=422
      a_j=n2

     !pivoting
      do pivot = T,n-1
         print *, 'pivot=',pivot
         rmax = pivot
         do row = pivot,a_i
            if (ABS(a(rmax,pivot)) < ABS(a(row,pivot)) ) then
               rmax=row
            end if
         end do
         if (rmax /= pivot) then
            do k=1, a_j
               temp = a(rmax,k)
               a(rmax,k) = a(pivot,k)
               a(pivot,k) = temp
            end do
         end if
  !elimination
         do row = pivot+1, n
            if ( a(pivot,pivot) /= 0 ) then
               factor = (a(row,pivot)) / (a(pivot,pivot))
               print *,'factor=',factor
               do col = 1, n2
                  a(row, col) = a(row,col) - a(pivot,col) * factor
                  print *,'a=',a(row,col)
               end do
            end if
         end do
      end do
   end do
   !back-substitution
   soln(n2) = 0
   do o=n,1,-1
      do p=n2,o+1,-1
         a(o,n2) = a(o,n2) - soln(p)*a(o,p)
      end do
      soln(o) = a(o,n2) / a(o,o)
   end do
   do i=1,n
      print *,soln(i)
      write (121,*) soln(i)
   end do
end program final

The input file is 441x442 matrix txt file. I think this can read that input file but it's going to be a infinite loop on here
if ( a(pivot,pivot) /= 0 ) then
   factor = (a(row,pivot)) / (a(pivot,pivot))
   print *,'factor=',factor
   do col = 1, n2
      a(row, col) = a(row,col) - a(pivot,col) * factor

How can I solve this problem?

A: If you have this properly indented, you will see the following loop structure (ignoring the math portion):
    do T=1,421
       do pivot=T,420
          do row=pivot+1,421
             do col=1,422
                print *,a
             enddo
          enddo
       enddo
    enddo

It is not an infinite loop you have, you are just printing a(row,col) to the screen 522,326,280 times (and if you put that to a file, which I do not recommend, you will have an 11 GB file in your folder!). If you comment out the print statements regarding a and factor but leaving in the one for pivot, it will run in about 3 minutes. Neglecting all print statements, it runs in just a few seconds.
Needless to say, you probably should not be putting anything more than 10 lines to the screen.


text:
Q: Install Dual Boot fail: Ubuntu cannot find Windows 7 I need to install Ubuntu as dual boot option on a HP Z800 Workstation which has Windows 7 installed.
Ubuntu installer cannot detect Windows and complains "This computer currently has no detected operating systems".
I tried to allocated a partition of 200GB of free space using Windows disk manager, and the Ubuntu installer fails to see any free space.
The PC features: 24Gb of RAM, dual Xeon CPU, 2TB of disk space.
Does anyone know what's going on?
Windows Disk Partition image
UBUNTU did not find Windows

A: Do you know, if the hard disk uses a GPT or a MBR structure? If it is GPT, there should be also a corresponding fake MBR. Maybe these two are not consistent.
Some time ago, I had a similar problem. The Ubuntu installer could not detect the fresh Windows 7 installation. I solved it by wiping the first sectors of my hard disk. Then I could create a clean MBR structure and install Windows and Ubuntu again. Before you continue with any experimental steps, you should create a complete backup of your Windows installation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mathematica is messing around with absolute values and sqrts of complex numbers? I know that $$\begin{pmatrix}0&Z\\Z^*&0\end{pmatrix} \quad\text{has eigenvalues}\quad \lambda_\pm=\pm|Z|$$
but Mathematica gives me
Eigenvalues@{{0,z},{Conjugate[z],0}}
(* { -Sqrt[z]Sqrt[Conjugate[z]], Sqrt[z]Sqrt[Conjugate[z]] } *)

I think this is not right because we have $\,\sqrt{ZZ^*}\neq\sqrt{Z}\sqrt{Z^*}$.
e.g. For $Z=-1$ we have $\sqrt{1}\neq (\sqrt{-1})^2\,$.
So, given this, I wonder if there is a way to solve this and output the result as $\pm|Z|$, even for the cases where instead of Z we had a product, or a sum of products.

A: Perhaps this?
Eigenvalues[
 ComplexExpand[{{0, z}, {Conjugate[z], 0}},
  z, TargetFunctions -> {Abs, Arg}]]

(*  {-Abs[z], Abs[z]}  *)


text:
Q: Laravel query builder - using data within row to compare with time in another I have got this working using a whereRaw as follow:
Reports::whereRaw('last_check_datetime < CURRENT_TIMESTAMP - INTERVAL `check_schedule_minutes` MINUTE')->get();

The table has a number of reports in it, with differing schedule minutes. i.e. I want one report to be checked every 15 mins and another to be checked every 60 mins. If the time in last_check_datetime is not older than the number of minutes in check_schedule_minutes then the report should not be returned in the collection.
Is there a way to achieve the same thing using a more Eloquent syntax, ideally with Carbon?

A: Tbh I think what you're doing here is right. The problem is in your question - you're wanting to merge PHP/MySQL syntax, but the data is in MySQL. So without first fetching all records and then doing a check, what you've done is right, and not really avoidable. However, if you really want more eloquent buildery-solution, here:
Reports::where('last_check_datetime', '<', DB::raw('CURRENT_TIMESTAMP - INTERVAL `check_schedule_minutes` MINUTE'))->get();

Tbh though, I think the whereRaw is neater.

A: You can use eloquent's whereBetween method on date columns
Reports::whereBetween('last_check_datetime', [Carbon::now()->subMinutes($check_schedule_minutes), Carbon::now()])->get();
Should do the trick for you.
EDIT: I realise this relies on you knowing the $check_schedule_minutes value before making the query, where your question is reading check_schedule_minutes from the table.
One way to solve this would be to have a predefined standard for check_schedule_minutes (15 or 60 mins as you said) then have that value passed into the function performing the query and add that to your conditions:
$check_schedule_minutes = 60;

Reports::whereBetween('last_check_datetime', [Carbon::now()->subMinutes($check_schedule_minutes), Carbon::now()])
->where('check_schedule_minutes', $check_schedule_minutes)
->get();


text:
Q: C# - Convert UTF8 String into bits, modify bits, and convert back into UTF8 String For a project I'm working on, I need to be able to convert a UTF8 string into bits or bytes for modification and back.
(Bit/Byte type doesn't matter.. '138' or '00000001' or '0A' - as long as I'm able to modify it as a string and convert the Bytes back into a string)
I've tried a few things, but nothing has worked.
For the most part, I've been trying to take the result of File.ReadAllBytes(path) and convert the bytes into a modifiable string and back, but haven't had any success. Also tried doing the same using a test string into a BitArray with no better luck.
Here's what I'm trying to do in a better example (pseudocode)
string input = "ABC";

Byte[] bytes = StringToBytes(input);
Byte[] bytes2;

string bytestring;
foreach (Byte byte in bytes) {
    bytestring = byte.ToString();
    /// modify bytestring to the value of a different byte here ///
    bytes2.Add(bytestring.ToByte());
}

return BytesToString(bytes2);

Return: 'ACD' (or whatever)

A: If you're trying to read a file into a byte[] array, modify those bytes, and convert that back to a string, you could do something like this:
// read the file into a byte array
var bytes = File.ReadAllBytes(inputFileName);

// modify the bytes

// now convert back to a UTF string
var stringFromByteArray = Encoding.UTF8.GetString(bytes, 0, bytes.Length);


text:
Q: How to read what is in the database I have a DatabaseHandler class and am saving my parsed XML to the database. Well, I hope I am. I am not sure how to see what is in the database and see if it is saving correctly so I can pull some of the data out and do more development. I have tried a log statement but all I get is my package name and some random string of numbers.
I'm creating the table and adding the parsed data in the onResponse as I want to save this as soon as the parsing is done as the web service is slow.
public void getXMLData() {
        OkHttpClient client = getUnsafeOkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.API_FULL_URL))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String responseData = response.body().string();
                final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
                final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
                final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
                employeeModel = new Employee();
                mEmployees.clear();
                mEmployees.addAll(employees);

                DatabaseHandler databasehandler = new DatabaseHandler(getApplicationContext());
                db = databasehandler.getWritableDatabase();
                databasehandler.onCreate(db);
                databasehandler.addEmployee(employeeModel);

                //tell adapter on the UI thread its data changed
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTopListViewAdapter.notifyDataSetChanged();
                        mBottomListViewAdapter.notifyDataSetChanged();
                        mMangerList.setVisibility(View.VISIBLE);
                        directReportListView.setVisibility(View.VISIBLE);
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
            }
        });
    }

A: you can pull your db file if you are using a rooted device or emulator. Here is an example while using Eclipse. if you are on Android Studio, you can find DDMS from

Tools -> Android -> Android Device Monitor

Once you have your database file, you may view it in sqlitebrowser.


text:
Q: summation inequality/limit for decreasing sequences Let $(w_n)_{n=1}^\infty$ be a decreasing sequence of real numbers satisfying
$$
\lim_{n\to\infty}w_n=0\;\text{ and }\;\sum_{n=1}^\infty w_n=\infty.
$$
Conjecture.  For each $M,N\in\mathbb{N}$ we have
$$
\lim_{j\to\infty}\frac{\sum_{n=(M-1)j+1}^{(M-1)j+N}w_n}{\sum_{n=(M-1)j+1}^{Mj}w_n}=0.
$$
Obviously this is true if $M=1$ and I suspect it is true for general $M$, but I'm stuck on proving it.  The problem is that $w_n/w_{n+1}$ can be arbitrarily large.  On the other hand, such large jumps must be spaced out to ensure that $\sum w_n=\infty$, and it seems like that might be enough to get the limit expression small.  But a proof is eluding me, and maybe the conjecture isn't even true, my intuition notwithstanding.
Any help would be much appreciated.  Thanks!

A: Let us take $M = 2$, $N = 1$.
Let us define $w_n$ by steps. Say we have already defined it up to $m$. Then let $w_{m + 1} = w_m$, $k > \max(\frac{m}{w_m}, m)$ and $w_n = \frac{w_m}{m - 1}$ for $n = m + 2, \ldots, m + m$. Then for $j = m$ we have $\frac{\sum_{n=m+1}^{m+1} w_n}{\sum_{n=m+1}^{2m} w_n} = \frac{w_m}{w_m + \frac{w_m}{m - 1} \cdot (m - 1)} = \frac{1}{2}$.
Also we have $\sum_{n=m+1}^{m+m} w_m > 1$, so our series diverge.


text:
Q: Django module Issue/running django Started having issues running Django.  Install runs without error, however when I check the version packages that show "already satisified" are not found.
I've removed my .local and re-installed files, no change.
% pip3 install /path/.../Django-3.0b1/ --user
Processing /path/.../Django-3.0b1
Requirement already satisfied: pytz in /usr/lib/python3.6/site-packages (from Django==3.0b1) (2018.5)
Requirement already satisfied: sqlparse in /path/.../.local/lib/python3.6/site-packages (from Django==3.0b1) (0.3.0)
Requirement already satisfied: asgiref in path/.../.local/lib/python3.6/site-packages (from Django==3.0b1) (3.2.3)

Installing collected packages: Django
  Running setup.py install for Django ... done
Successfully installed Django-3.0b1

% python3 -m django --version
Traceback (most recent call last):
  File "/path/.../python/3.7.3b/lib/python3.7/runpy.py", line 193, in
_run_module_as_main   "__main__", mod_spec)
  File "/path/.../python/3.7.3b/lib/python3.7/runpy.py", line 85, in _run_code  exec(code, run_globals)
  File "/path/.../Django-3.0b1/django/__main__.py", line 6, in <module>  from django.core import management
  File "/path/.../Django-3.0b1/django/core/management/__init__.py", line 14, in <module> from django.core.management.base import (
  File "/path/.../Django-3.0b1/django/core/management/base.py", line 11, in <module> from django.core import checks
  File "/path/.../Django-3.0b1/django/core/checks/__init__.py", line 9, in <module>  import django.core.checks.database  # NOQA isort:skip
  File "/path/.../Django-3.0b1/django/core/checks/database.py", line 1, in <module> from django.db import connections
  File "/path/.../Django-3.0b1/django/db/__init__.py", line 2, in <module> from django.db.utils import (
  File "/path/.../Django-3.0b1/django/db/utils.py", line 5, in <module>  from asgiref.local import Local
ModuleNotFoundError: No module named 'asgiref'


text:
Q: Send Blob file via Axios I have object like this:
{
    "name": "filename",
    "size": 3523507,
    "type": "image/png",
    "extension": "png",
    "url": "blob:http://localhost:8081/082e9c22-9869-4289-a9c8-e36b0640e61c"
}

And i need upload it to backend. I try it:
const session = axios.create({
  baseURL: debug ? 'http://localhost:8000': '',
  xsrfCookieName: CSRF_COOKIE_NAME,
  xsrfHeaderName: CSRF_HEADER_NAME,
});
let formData = new FormData();
formData.append('file', file, 'file.name');

return session.post(`/chats/files/`,{...formData},), {
  headers: {
    "Content-Type": `multipart/form-data`,
  }
}

But it doesn't work to add Blob to the formData
UPD I get an object with files from the send-message method in the vue-advanced-chat component in this form:
{
    "name": "filename",
    "size": 3523507,
    "type": "image/png",
    "extension": "png",
    "localUrl": "blob:http://localhost:8081/aae047a9-5f9e-481f-b0cc-17febe954c31",
    "blob": {}
}

Then I format it to display in the interface before uploading to the server
UPD2
I converted blob to file
send_file(roomId, messageId, blob_file, isAudio, duration) {
        let formData = new FormData();
        let file = new File([blob_file.blob], blob_file.name);
        formData.append('file[]', file, blob_file.name);
        return session.post(`/chats/files/`,
            {'chat': roomId, 'message': messageId, ...formData},), {
            headers: {
              'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
            },
            timeout: 30000,
        }
    },

and still get:
{"file":["No files were sent."]}

A: After several days of searching, debugging and dozens of attempts, I managed to find a solution.

*

*You need a Blob object, not a URL

*You need to convert Blob to File
let file = new File([blob_file.blob], fileName);

*To correctly identify the file type, you need to add blob_file.extension to the name
let fileName = `${blob_file.name}.${blob_file.extension}`;

*You need to add all attributes to formData

formData.append('file', file, fileName);
formData.append('chat', roomId);
formData.append('message', messageId);

*Specify 'Content-Type': multipart/form-data, and don't specify _boundary - because in new versions of formData it is determined automatically!

headers: {
   'Content-Type': `multipart/form-data`,
},

so the final version of the code looks like this:
send_file(roomId, messageId, blob_file) {
    let formData = new FormData();
    let fileName = `${blob_file.name}.${blob_file.extension}`;
    let file = new File([blob_file.blob], fileName);
    formData.append('file', file, fileName);
    formData.append('chat', roomId);
    formData.append('message', messageId);

    return session.post(`/chats/files/`,
        formData, {
           headers: {
             'Content-Type': `multipart/form-data`,
           },
        })

A: You are not sending data in correct way. It should be:
export const uploadFileRequest = ({ file }) => {
   const data = new FormData();
   data.append('file', file, file.name);

   return session.post(`/chats/files/`, data, {
     headers: {
       'Content-Type': `multipart/form-data;boundary=${data._boundary}`,
     },
     timeout: 30000,
   });
};

it should work, for reference https://medium.com/@fakiolinho/handle-blobs-requests-with-axios-the-right-way-bb905bdb1c04


text:
Q: Assigning variable inside the EOF This part of the code works on Ubuntu 16.04 but when I try to run this code on CentOS 6.x the value of server_url were not assigned properly, the value becomes blank.
Here's my code:
server_url="http://local.host.net"

cat > /etc/cron.daily/update_rules.sh <<EOF
#!/bin/bash

mkdir -p /opt/rules
rm -f /opt/rules/rules.tmp

echo "[`date`] Updating rules ..."
wget $server_url -O /opt/rules/rules.tmp && \
    mv /opt/rules/mhn.rules.tmp /opt/rules/mhn.rules && \
    (/usr/local/bin/supervisorctl update ; /usr/local/bin/supervisorctl restart appserv ) && \
    echo "[`date`] Successfully updated the rules" && \
    exit 0

echo "[`date`] Failed to the rules"
exit 1
EOF

I'm getting this result, take note of line 6:
#!/bin/bash

mkdir -p /opt/rules
rm -f /opt/rules/rules.tmp

echo "[Tue Aug 29 16:42:26 UTC 2017] Updating rules ..."
wget  -O /opt/rules/rules.tmp && \
    mv /opt/rules/mhn.rules.tmp /opt/rules/mhn.rules && \
    (/usr/local/bin/supervisorctl update ; /usr/local/bin/supervisorctl restart appserv ) && \
    echo "[`date`] Successfully updated the rules" && \
    exit 0

echo "[Tue Aug 29 16:42:26 UTC 2017] Failed to the rules"
exit 1


text:
Q: Camel: Jetty response encoding I want to use the Jetty component in a Camel environment. This is an excerpt of my spring-config.xml:
...
<bean id="webEnc" class="web.WebEnc" />
<camelContext>
    <route>
        <from uri="jetty:http://0.0.0.0/enc" />
        <process ref="webEnc" />
    </route>
</camelContext>
...

And here is the code used to return a String:
import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class WebEnc implements Processor{

    @Override
    public void process(Exchange exchange) throws Exception {
        exchange.getOut().setBody("abcäöüß\"€一二三"); //the last three symbols are chinese for '123'
    }
}

The local address works (http://127.0.0.1/enc) but the browser does not display the string correctly (displayed as 'abcäöüß"€一二三'). I assume the problem is some encoding. How to set the encoding like 'utf-8'?I can't find any hint here (http://camel.apache.org/jetty.html) concerning encoding or charset or something like that.

A: I think you have to set Content-Type header with utf-8 charset in the output message, something like this:
@Override
public void process(Exchange exchange) throws Exception {
    exchange.getOut().setBody("abcäöüß\"€一二三"); //the last three symbols are chinese for '123'
    exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/html; charset=utf-8");
}

A: After some help and hints from Łukasz (thx for your time) i found a good solution. This forces Jetty to deliver bytes, not a string:
exchange.getOut().setBody("abcäöüß\"€一二三".getBytes("utf-32"));

To help the browsers to display the correct symbols i did this:
exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/html; charset=utf-32");

My firefox cannot display the chinese symbols with utf-32, it's fine with utf-8. Chrome does it with both encodings.But actually i was not interested in that, my intention was to deliver bytes. getBytes() does the job.


text:
Q: Number of 5-distinct-digit odd numbers whose tens digit is greater then their hundreds digit. I am trying to find the number of 5-digit (All different, out of the range $[1...9]$, no 0's) odd numbers whose tens digit is greater then their hundreds digit.
My attempt at solving this is to divide into the 5 different options for the unit digit and then further dividing each of these according to possible values the tens-digit can have. This works, but is enormously cumbersome and I get the feeling that a more elegant solution must exist. Any ideas?

A: My approach is as follows:
Choose an odd unit digit: $5 \choose 1$
We have $8$ numbers left. Choose any $2$ for the ten and hundred digits: $8 \choose 2$
The order is fixed so the larger number will always go to the ten digit: $1$
Fill in the remaining $2$ digits with the remaining $6$ numbers: ${6 \choose 2} \cdot 2!$
Total numbers of way is thus
$${6 \choose 2} \cdot 2! \cdot {8 \choose 2} \cdot 1 \cdot {5\choose 1} =4200$$


text:
Q: Azure T-SQL SELECT concatenation behavior I have really strange problem (or misunderstanding) of the string concatenation on Azure Sql. I used to build T-SQL code for EXEC like this:
DECLARE @tsql nvarchar(max)
SELECT @tsql = CONCAT(@tsql, Prop1, Prop2) FROM Table
PRINT @tsql

This works fine in SQL from 2012 to 2016. But in Azure SQL I have really strange behavior: only LAST row is in @tsql
Here is live T-SQL to clean up some tables:
    DECLARE @deleteTsql nvarchar(max)
    SET @deleteTsql = ''
    -- just show all table
    SELECT O.[name] FROM [sys].[objects] O
    LEFT JOIN sys.schemas SCH on O.schema_id = SCH.schema_id
    WHERE (SCH.[name] = 'dbo' AND [type] = 'U') or (SCH.[name] = 'data' and O.[name] = 'Objects')
    ORDER BY O.create_date desc

    -- build T-SQL to cleanup
    SELECT @deleteTsql = CONCAT(@deleteTsql, 'PRINT ''Deleting data from ', O.[name], '''', CHAR(10), CHAR(13), 'DELETE FROM [', SCH.[name], '].', '[', O.[name],']', CHAR(10), CHAR(13)) FROM [sys].[objects] O
    LEFT JOIN [sys].[schemas] SCH on O.[schema_id] = SCH.[schema_id]
    WHERE (SCH.[name] = 'dbo' AND [type] = 'U') or (SCH.[name] = 'data' and O.[name] = 'Objects')
    ORDER BY O.create_date desc

    PRINT @deleteTsql

This works fine in SQL 2016. For instance I have tables data.Objects, dbo.Table1 and dbo.Table2. Then following will be printed:

(3 rows affected)
PRINT 'Deleting data from Objects'
DELETE FROM [data].[Objects]
PRINT 'Deleting data from Table1'
DELETE FROM [dbo].[Table1]
PRINT 'Deleting data from Table2'
DELETE FROM [dbo].[Table2]

But if I do the same on Azure SQL (v12) database with same tables then I got this:

(3 rows affected)
PRINT 'Deleting data from Table2'
DELETE FROM [dbo].[Table2]

So only last record is in @deleteTsql.
Why?????

A: The result for aggregate concatenation (with the SELECT @x=@x+... syntax) is undefined. See KB 287515 and this answer. Using CONCAT does not change that. As Panagiotis Kanavos suggested, you should use STRING_AGG or GROUP_CONCAT.
And one more thing: in my databases, I get the results from a single row using your query, even in SQL Server 2016 or SQL Server 2017. So it's not an Azure thing, it's just depending on the execution plan (if it is using a nested loops join, you get all the rows; if it is using a merge join, you get a single row). That may be dependant on the number of rows in the system tables, the CPU count, the updated statistics, etc.


text:
Q: Converting Str to Datetime which extracted from Beautifulsoup I am extracting the date from the article and want to store into MySQL database.
html = urlopen('https://www.horizont.net/medien/nachrichten/spot-remake-das-ist-der-neue-pick-up-spot-mit-fahri-yardim-und-christian-ulmen-178272')
bs = BeautifulSoup(html, 'html.parser')

pub = bs.find('span', {'class':'PublishDate_date'}).get_text()

O want to convert the str to datetime but nothing working so far?
Any idea how to solve this problem?
This is how output shows
16. Oktober 2019

A: If your goal is to parse only dates from that website, which is in German, you can use the dateparser module:
Installation:
pip install dateparser

Sample output:
>>> dateparser.parse('16. Oktober 2019')
datetime.datetime(2019, 10, 16, 0, 0)


text:
Q: Am trying to find price of a particular route basing on the distance but whenever i put the places, the if loop returns the else not the price //main.js
    //set map options
    var myLatLng = { lat: 51.5, lng: -0.1 };
    var mapOptions = {
        center: myLatLng,
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };

    //create map
    var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

    //create a DirectionsService object to use the route method and get a result for our request
    var directionsService = new google.maps.DirectionsService();

    //create a DirectionsRenderer object which we will use to display the route
    var directionsDisplay = new google.maps.DirectionsRenderer();

    //bind the DirectionsRenderer to the map
    directionsDisplay.setMap(map);

    //define calcRoute function
    function calcRoute() {
        //create request

        var request = {
            origin: document.getElementById("source").value,

            destination: document.getElementById("destination").value,
            travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
            unitSystem: google.maps.UnitSystem.METRIC
        }

        //pass the request to the route method
        directionsService.route(request, function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                //Get distance and time
                var distance = result.routes[0].legs[0].distance.text;
                $("#output").html("
From: " + document.getElementById("source").value + ".
To: " + document.getElementById("destination").value + ".
 Driving distance: " + result.routes[0].legs[0].distance.text + ".
Duration: " + result.routes[0].legs[0].duration.text + ".
");

                //START CALCULATING PRICE
                if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 1  ){
                        document.getElementById("fareairport").value = "30000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 2  ) {
                        document.getElementById("fareairport").value = "50000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 3  ) {
                        document.getElementById("fareairport").value = "50000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 4  ) {
                        document.getElementById("fareairport").value = "100000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 5  ) {
                        document.getElementById("fareairport").value = "50000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 6  ) {
                        document.getElementById("fareairport").value = "100000";
                    }else if(result.routes[0].legs[0].distance.value <= 20 && document.getElementById("carclass").value == 7  ) {
                        document.getElementById("fareairport").value = "200000";
                    //END OF ZONE A
                 }
                 else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 1  ) {
                    document.getElementById("fareairport").value = "70000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 2  ) {
                    document.getElementById("fareairport").value = "100000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 3  ) {
                         document.getElementById("fareairport").value = "100000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 4  ) {
                    document.getElementById("fareairport").value = "150000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 5  ) {
                    document.getElementById("fareairport").value = "90000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 6  ) {
                    document.getElementById("fareairport").value = "120000";
                 }else if(result.routes[0].legs[0].distance.value >= 21 && result.routes[0].legs[0].distance.value <= 30 && document.getElementById("carclass").value == 7  ) {
                    document.getElementById("fareairport").value = "200000";
                 } //END OF ZONE B
                else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 1 ) {
                    document.getElementById("fareairport").value = "100000";
               }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 2 ) {
                    document.getElementById("fareairport").value = "150000";
                }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 3  ) {
                    document.getElementById("fareairport").value = "150000";
                }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 4  ) {
                    document.getElementById("fareairport").value = "250000";
                }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 5  ) {
                    document.getElementById("fareairport").value = "170000";
                }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 6  ) {
                    document.getElementById("fareairport").value = "250000";
                }else if(result.routes[0].legs[0].distance.value >= 31 && result.routes[0].legs[0].distance.value <= 40 && document.getElementById("carclass").value == 7  ) {
                   document.getElementById("fareairport").value = "300000";
                } //END OF ZONE C
                else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 1 ) {
                    document.getElementById("fareairport").value = "130000";
                }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 2 ) {
                   document.getElementById("fareairport").value = "200000";
               }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 3  ) {
                    document.getElementById("fareairport").value = "200000";
                }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 4  ) {
                    document.getElementById("fareairport").value = "300000";
               }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 5  ) {
                    document.getElementById("fareairport").value = "200000";
                }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 6  ) {
                    document.getElementById("fareairport").value = "300000";
                }else if(result.routes[0].legs[0].distance.value >= 41 && result.routes[0].legs[0].distance.value <= 50 && document.getElementById("carclass").value == 7  ) {
                    document.getElementById("fareairport").value = "330000";
                }//END OF ZONE D
                else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 1 ) {
                   document.getElementById("fareairport").value = "160000";
                }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 2 ) {
                   document.getElementById("fareairport").value = "200000";
                }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 3  ) {
                    document.getElementById("fareairport").value = "200000";
                }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 4  ) {
                    document.getElementById("fareairport").value = "300000";
                }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 5  ) {
                   document.getElementById("fareairport").value = "200000";
               }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 6  ) {
                    document.getElementById("fareairport").value = "300000";
                }else if(result.routes[0].legs[0].distance.value >= 51 && result.routes[0].legs[0].distance.value <= 60 && document.getElementById("carclass").value == 7  ) {
                    document.getElementById("fareairport").value = "330000";
                }
                //END OF ZONE E
                else{

                    alert(document.getElementById("carclass").value);
                }

                //display route
                directionsDisplay.setDirections(result);
        } else {
                //delete route from map
                directionsDisplay.setDirections({ routes: [] });
                //center map in London
                map.setCenter(myLatLng);

                //show error message
                $("#output").html("
Could not retrieve driving distance.
");
        }
        });

    }

    //create autocomplete objects for all inputs
    var options = {
        types: ['(places)']
    }

                    <form name="airport_booking" method="POST" action="{{action('Spe\AirporttransfersController@store')}}" role="form" class="form-horizontal" id="pickup">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                                <input type="hidden" name="type" >

                                    Full Name

                                        <input type="text" name="fullname" class="form-control" required disabled value="{{$summary['fullname']}}"  >

                                    Telephone

                                        <input type="tel" id="pickup_telephone" name="Telephone" pattern="^[0-9\ \(\)\+]{13}" class="form-control" disabled style="width:21.5em" value="{{$summary['telephone']}}" >

                                    Email

                                        <input type="email" name="email" class="form-control" disabled value="{{$summary['email']}}" >

                                    Arrival

                                        <input type="text" name="pickupdate" onchange="checkDate_arrival()" value="{{$summary['pickupdate']}}" id="arrival"  class="form-control datetimepicker" disabled>

                                    Adults
                                    <input type="text" name="adults" id="arrival" value="{{$summary['adults']}}" class="form-control datetimepicker" disabled >

                                    Children
                                    <input type="text" name="children" value="{{$summary['children']}}"  id="arrival" class="form-control" disabled >

                                    Elderly
                                    <input type="text" name="elderly" id="arrival" value="{{$summary['elderly']}}" class="form-control" disabled>

                                   Airline

                                        <input type="text" name="airline" value="{{$summary['airline']}}" class="form-control" disabled >

                                   Flight Number

                                        <input type="text" name="flightnumber" value="{{$summary['flightnumber']}}" class="form-control"  disabled >

                                    Source
                                    <input type="text" name="carclass" id = "source" value="{{$summary['fromwhere']}}"  id="arrival" class="form-control" disabled>

                                    Destination

                                        <input type="text" name="destination" id="destination" value="{{$summary['destination']}}" class="form-control" disabled >

                                    Car Type/Class

                                        <input type="text" name="carclass" id="carclass" value="{{$summary['carclass']}}" class="form-control" disabled >

                                    YOUR PAYMENT METHOD
                                    <input type="text" name="ptmethod"  id="ptmethod" class="form-control" disabled >

                                    FARE DETAILS

                                        <input type="text" name="fare" id="fareairport" disabled class="form-control" >

                                <input type="hidden" name="fromwhere" value="EBB INT AIRPORT">

                                    <input type="submit" name="airport_pickup_submit" class="btn btn-theme md-btn text-uppercase mt-2" value="Book">

                        </form>

This is the javascript script which calculates the the distance, time and sets the value of an input(total price) in the form. The script returns the distance and time but it does not set the price according to the "if loop" it returns the else part
  the id fairairport is the id of the price input that is set if a distance is within a certain and depends also on the class of the car chosen.

A: Instead of using the if else in your use case, you can use Switch Statement in Javascript. It will be more efficient and easier to debug.
For your use case, you can create 2 switch statement: 1 for the car class and 1 for the distance. Here is a sample code that calculates the fare of your trip depending on the distance from your source and destination. I base some of the values in your code.
Below is the part where I used a Switch Statement for the distance inside a Switch Statement for the car class.
 switch (activities.value) {
            case "1":

                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "30000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "70000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "130000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "160000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            case "2":
                //Price2
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            case "3":
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                       alert("More than 60 KM");
                }
                break;
            case "4":
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            case "5":
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            case "6":
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            case "7":
                switch (true) {
                    case (distance <= 20):
                        //Price
                        document.getElementById('fare').innerHTML = "50000";
                        break;
                    case (distance >= 21) && (distance <= 30):
                        //Price
                        document.getElementById('fare').innerHTML = "100000";
                        break;
                    case (distance >= 31) && (distance <= 40):
                        //Price
                        document.getElementById('fare').innerHTML = "150000";
                        break;
                    case (distance >= 41) && (distance <= 50):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    case (distance >= 51) && (distance <= 60):
                        //Price
                        document.getElementById('fare').innerHTML = "200000";
                        break;
                    default:
                        alert("More than 60 KM");
                }
                break;
            default:
                alert("default");
        }
    });


text:
Q: Javascript `replace` Replacement Fallback Take the following example:
var tag_oh_so_alone_ = '[FieldName]',
    tag_with_default = '[FieldName:The default value]',
    the_regex = /\[([a-z]+)(\:([^\]]+))?\]/i;

console.log(
    "Results:\n",
    tag_oh_so_alone_.replace(the_regex,"1: $1\n 2: $2\n 3: $3\n"),
    tag_with_default.replace(the_regex,"1: $1\n 2: $2\n 3: $3\n")
);

The console reads:
Results:
 1: FieldName
 2:
 3:
 1: FieldName
 2: :The default value
 3: The default value

What I'd like to do is, within the replacement declaration (in other words, the place where we include "$1" etc), specify basically: if $3 is populated use $3, otherwise use $1.
The expected output would be the following:

tag_oh_so_alone_ => FieldName
tag_with_default => The default value

Is this possible?

A: You can pass a function as the replacer to the String.replace, like this
function replacer(match, p1, p2, p3) {
    if (p3) {
        return "1: " + p1 + "\n 2: " + p2 + "\n 3: " + p3 + "\n"
    } else {
        return "1: " + p1 + "\n 2: " + p1 + "\n 3: " + p1 + "\n"
    }
}

console.log(
    "Results:\n",
    tag_oh_so_alone_.replace(the_regex, replacer),
    tag_with_default.replace(the_regex, replacer)
);

with that, the output becomes,
Results:
 1: FieldName
 2: FieldName
 3: FieldName
 1: FieldName
 2: :The default value
 3: The default value

Here, p1, p2 and p3 are the actual matched groups. If p3 is not populated/matched, then it will be undefined. You can customize the return value of the function, as you like in the replacer function.


text:
Q: Grayscaled image I have still a problem with saving a gray image with Java. How could I do this?
The format is not so important, but there should be no image compression.
Does anyone know that?

A: This may not be the most elegant method, but it will work:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageTest {

    public static void main(String[] args) throws IOException {

        int width = 10 // width of your image
        int height = 10 // height of your image

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                int grayscale = ... // get your greyscale value 0..255 from your array here.
                int colorValue = grayscale | grayscale << 8 | grayscale << 16;
                img.setRGB(x, y, colorValue);
            }

        }

        ImageIO.write(img, "png", new File("output.png"));
    }

}

The colorValue is composed of r, g, and b (b on the lowest byte, g one before that, and r one before that). Since your image is greyscale, you can simply use the same r, g and b values for your image, so that's why you can simply do:
int colorValue = grayscale | grayscale << 8 | grayscale << 16;


text:
Q: How to run app that needs bluetooth in background for forever? I have an app that uses Bluetooth to connect with a Bluetooth device that gives a temperature reading. When the temperature reaches a certain level the alarm rings. It works perfectly fine in the foreground.
The problem is I am not being able to get data from a device while it's in the background. Since the nature of the app is it must connect with Bluetooth devices and get data all the time. How can I run this kind of app in the background forever?

A: Have you requested the bluetooth-central background mode?
See the Core Bluetooth Programming Guide for more:

If your app needs to run in background to perform certain Bluetooth-related tasks, it must declare that it supports a Core Bluetooth background execution mode in its Information property list (Info.plist) file. When your app declares this, the system wakes it up from a suspended state to allow it to handle Bluetooth-related events. This support is important for apps that interact with Bluetooth low energy devices that deliver data at regular intervals, such as a heart rate monitor.


text:
Q: enabling .vscode/tasks.json with gulefile.js tasks When i create dotnet x-platform [dnx] based asp.net 5 web apps, and apache cordova x-platform [acx] + angular2 based ionic2 mobile apps, they both setup a gulpfile.js containing a default set of gulp based task runner entries.
When i open those sources in vscode 1.0.0 and use f1 | tasks: configure task runner | gulp it generates a .vscode/task.json where "command": "gulp" is defined but it throws the warning dialog and output window errors shown below.
I have npm gulp@3.9.1 package installed locally.  Am i supposed to have some other package configuration in place to facilitate vscode task runner configuration that will use an existing gulpfile.js in my sources?

A: The fix was I needed to have gulp installed as a global package in addition to the local package.json definition for it.
After doing a "npm install -g gulp" when I then executed f1 | tasks: configure task runner | gulp it setup a .vscode/tasks.json allowed me to use f1 | tasks: run tasks |  [ or ctrl+p |  ] to execute tasks defined and maintained in gulpfile.js .


text:
Q: Auto shrink title in product archive? I'm using Elementor with JetWooBuilder from Crocoblock. When designing the product archive page I would like all rows to be equal height. When the product tile is too long it needs two lines, and making that product "card" bigger than the one with one title line.
Is there any way of auto shrinking the title to make it always fit in one line?

A: I guess your problem is that the cards have not the same height in your shop page. To fix it, add the products grid in your shop page and toggle "Equal Columns Height" in the product grid settings.


text:
Q: requirejs - loading the same module with a different name in different files Using requirejs, I have two files that depend on the same module.
Must I make sure that I always use the same module name in both dependencies?
For example, if I defined a path for require.config:
'myMod':'src/js/myModule'

And then one time use the name and one time use the actual path, like so:
//in a.js
define(function(require){
 var mod = require('myMod');
});

//in b.js
define(function(require){
 var mod = require('src/js/myModule');
});

Obviously, the best practice would be to use the module name everywhere, but I want to know why this causes an actual error.
Does requirejs store a map between the module name used and the actual loaded module?

A: As you yourself say:

Obviously, the best practice would be to use the module name everywhere

RequireJS enforces this practice, up to a point. The thing is that when you tell RequireJS in your paths that 'myMod':'src/js/myModule' you are effectively saying that you want to load src/js/myModule under the name myMod. In all likelihood, if you then refer to it by the full path this is an error in your part. If this were to happen in my code, I'd consider it to be an error. So I'd like RequireJS to fail when this happens.
There's also the issue of semantics. The basic case is that if two names passed to require differ, once relative paths have been resolved, then they refer to two different modules. Going by this, if you do require('myMod') and require('src/js/myModule') you are expecting two different modules. And if you do require('myMod') and require('myMod'), you get the same module. So with the paths you've set, what do you actually want? The same module or different modules?
RequireJS has ways to give you both. If you want both module names to give you the same module, then you remove your paths config and use a map config instead:
map: {
  '*': {
    myMod: 'src/js/myModule'
  }
}

What this means is "in all modules (*), if a request is made for the module myMod, then load module src/js/myModule instead." The intent is crystal clear.
If you'd like instead both paths to give you different modules although they share the same source, you could do it using a RequireJS plugin that loads the same source for your modules but has RequireJS register this single source as different modules.


text:
Q: CSS package as a node module Is it possible to create a node module that contains only CSS files served in git that I could call through dependencies in package.json
package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "author": "",
  "license": "ISC",
  "isLocal": "true",
  "devDependencies": {
    "core-css": "git+ssh://git@git.myproject:porject/core-css.git",
    "node-sass": "^3.6.0",
    "webpack": "^1.13.0"
  }


text:
Q: UWP ListView DataTemplate Bindings My ViewModel
BookingTakerViewModel

has a property
public List<string> Vias {get;set;}

I am wanting to bind a ListView with a DataTemplate but I can not find out how to do it. This is my code and it is throwing this error when it runs:
 "Unable to cast object of type 'System.String' to type 'UI_Test_1.ViewModels.BookingTakerViewModel'."

I thought that the x:DataType should reference the class and in this case it is my Viewmodel.I presume that the x:Bind Vias is wrong beacuase this is a List so lost as to what to do.
<ListView
    Name="viasList"
    Width="300"
    BorderBrush="Black"
    BorderThickness="5"
    ItemsSource="{x:Bind viewModel.Vias, Mode=OneWay}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                  <Setter Property="MinHeight" Value="1" />
                   <Setter Property="MaxHeight" Value="15" />
            </Style>
            </ListView.ItemContainerStyle>
               <ListView.ItemTemplate>
                    <DataTemplate x:Name="dt" x:DataType="viewmodels:BookingTakerViewModel">
                        <Grid>
                            <TextBlock FontSize="14" Text="{x:Bind Vias, Mode=OneWay}" />
                        </Grid>
                    </DataTemplate>
             </ListView.ItemTemplate>
</ListView>

The Vias are intantiated with data so it's not that which is causing a NullReference Exception. I believe the XAML is incorrect.

A: Probably you are looking for something like this?
<ListView.ItemTemplate>
    <DataTemplate x:Name="dt" x:DataType="x:String">
        <Grid>
            <TextBlock FontSize="14" Text="{x:Bind}" />
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

Inside the data template, the context of {x:Bind} is the templated object, which is a string item from the collection you set in ItemsSource.


text:
Q: simple strcpy from string to string crashes entire programme sorry if this is a commonly asked question but I'm not sure as to why this code will not output anything:
#include <stdio.h>
#include <string.h>

int main()
{
char source[] = "hello world!";

char **destination;

strcpy(destination[0], source);

puts(destination[0]);
puts("string copied!");

return 0;
}

it looks like it is crashing at strcpy() as "string copied!" does not appear in the terminal either

A: Your problem is that char **destination is an empty pointer to a pointer.
destination[0] points to absolutely nothing.
Here is how you would actually do it:
#include <stdio.h>
#include <string.h>

int main()
{
  char source[] = "hello world!";

  char destination[100];

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");

  return 0;
}

Or if you want to determine the size of destination dynamically:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char source[] = "hello world!";

  char *destination = malloc(strlen(source) * sizeof(char)+1); // +1 because of null character

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");

  free(destination); // IMPORTANT!!!!
  return 0;
}

Make sure you free(destination) because it is allocated on the heap and thus must be freed manually.


text:
Q: Python dictionary vs django.Template.Context Can i use any python dictionary as a context or should i use the one provided by django.template.Context?
What difference does it make?
TIA

A: You just have to insert your (python-)dictionary into django request context, to have your variables for use in your template, like:
def some_view(request):
    my_data_dictionary={...}
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))


text:
Q: Getting a list of assemblies needed by application Is there a way of getting all required assemblies (excluding the .net framework) for a .net project into a folder ready to be packaged into an nsis as setup file?
I've tried writing a small console app that uses reflection to get a list of dlls but have got stuck with finding a foolproof way of determining if a dll is from the .net framework or not.
The answer could be a simple switch in Visual Studio to output all dependencies, or a standalone app that can do it, or a plugin for Nsis, or some information on reflection that I've missed.

A: In Visual Studio (2005 at least - what I'm using right now), each reference that you have associated to a project has a property called "Copy Local", this can be set to true/false. When true it will copy the dll's for you into the current configuration directory.

A: You can use NDepend for this. Download it, build a new NDepend project, drag&drop your assemblies in the Application Assemblies data grid view, and you'll see NDepend resolving instantly the tier assemblies needed by your set of Application Assemblies.
You can also provide a list of folders to tell NDepend where to look. If a tier assembly can't be found, then NDepend will mark it as not found, which I think is a valuable information.

A: Dependency Walker is what you need. Or maybe Depends.Net


text:
Q: Accessing XML data online? I am just testing an app to get data off our web server, previously I had been using:
NSURL, NSURLRequest, NSURLConnection etc. to get the data that I wanted.
But I have just noticed that if I swap to using XML I can simply do the following and pass the results to NSXMLParser:
NSURL *url = [NSURL URLWithString:@"https://www.fuzzygoat.com/turbine?nbytes=1&fmt=xml"];

Am I right in thinking that if your just after XML this is an acceptable method? It just seems strongly short compared to what I was doing before?
gary

A: That code only creates a URL object that represents a URL. It doesn't make any request or download any data. You still need to use NSURLRequest and NSURLConnection in order to actually download any data from the server.
Also, stay away from methods like 'initWithContentsOfURL:` and friends, unless you understand that they will block the thread that they are called on until complete. For network services, this method shouldn't be used because it'll block your UI for an indeterminate time, because you can't predict how fast the internet connection will be wherever the app is used.
NSURLConnection's asynchronous request system is exactly what you need. It won't block the UI, and provides a nice encapsulated interface to downloading data from a remote location.

A: This is definitely the right way to go.  There do exist many different connection methods (including my favorite, ASIHTTPRequest) and many, many different xml parsers (including my favorite, KissXML) that are faster or more memory efficient than the Apple built in methods.
But to answer your question, yes, your logic and design pattern is correct.
UPDATE: Because Jasarien seems to think the question talks about asynchronous actions, I will discuss that here.  ASIHTTPRequest handles async very very easily. Just check out the quick samples.

A: Depending on how much XML you get back from the web service, NSXMLParser may not be ideal because the entire XML document has to be read into memory.
Memory is pretty scarce on an iPhone, so using a SAX parser like that in libxml2 is probably better for larger XML files. Instead of reading the entire document into memory, the XML is streamed through and parsed for specific nodes of interest. The memory overhead is lower because less data is stored at once.
Once a node of interest is parsed, an event handler is called to do something useful, like store the node data somewhere.
In this case, take a look at Apple's XMLPerformance sample project for example code.


text:
Q: Could a Kelvin Probe Force Microscope, in principal, be used as a voltmeter? This question goes into the very nature of the work function that the Kelvin Probe Force Microscope (KPFM) measures.
https://en.wikipedia.org/wiki/Kelvin_probe_force_microscope
Let's say, you have a battery of 1.5 V, you connect two identical metal leads to both ends.  If you measure the work function on both ends with a KPFM, would they be the same or would the work function be different by 1.5 eV?
A co-worker and I were discussing this, and unfortunately, we don't have a KPFM to test this.  The idea is that since the electrons have energies differing by 1.5 eV, there would be a difference in the workfunction between the two metals by 1.5 eV.  I disagree with this, but cannot give a good argument why I think the workfunction for both leads would be the same.

A: KPFM can detect if a voltage is applied to a metal, as it measures the contact potential difference due to the work function diffence between the probe tip material and the metal surface. So if there is a voltage applied to the metal (sample), you are then conceptually changing the fermi level of the metal hence changing the work function difference between the sample and probe tip.
However, in your thought experiment there is a small detail that you have to consider. For KPFM to work, the probe tip and the sample metal have to be externally connected. So whether or not you will measure the applied voltage due to the external battery you added depends on how you connect the setup.
In the assumed case where each metal lead is connected to the terminals of a 1.5V battery in an open circuit, during measurement each metal lead will be connected to the probe tip in the setup. In that case you will measure the same value for both metal leads and the battery will have no effect.
The other case where you will detect the applied voltage on one of the metal leads would be if the battery is connected to the probe tip within the setup (a series voltage source to the compensating kelvin voltage). So a practical connection would be that where one of the metal leads is connected to the battery with the other lead grounded with the same ground of the kelvin probe tip. The resulting measurement would be the contact potential diffence between the probe tip and the metal lead + the 1.5 eV due to the battery.


text:
Q: How can I overwrite a global variable in Python after using os.fork? I'm trying to figure out how to pass a variable value from a parent process to a child.
A child process gets s as "WhyICantOverwriteIt" instead of the received msg.
Code:
import socket
import sys
import os
import time
import contextlib

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('0.0.0.0', 12345)
sock.bind(server_address)

sock.listen(2)
pid = os.fork()

s = "WhyICantOverwriteIt"

def update(new):
    global s

    s = new

while True:
    connection, client_address = sock.accept()

    try:

        #parent
        if pid > 0 :
            print("\nI am parent:\n")
            nawiazanie = connection.recv(100)
            cPID = nawiazanie
            print("b4: ", s)
            update(nawiazanie)
            print("updated: ", s)

            print >>sys.stderr, 'pid clienta: "%s"\n' % cPID
            connection.sendall('zgoda')
            time.sleep(2)
        #child
        else :

            print >> sys.stderr, 'Czy mam tutaj pid: "%s"' % s
            wiadomosc = connection.recv(100)
            print("\nI am child process:\n")
            print("Wiadomoscc:", wiadomosc)
            path = s + ".txt"
            print(path)
            f = open(path, "w")
            f.write(wiadomosc)
            f.close()

    finally:
        connection.close()

I tried a few ideas with a global variable and similar ideas but nothing worked as I wished.


text:
Q: Having a hard time printing out stars in java I am having a hard time trying to print out a number of stars based on what is being passed to those methods that are responsible for printing them. Here is the code that I worked on so far. I added comments to those areas I am not sure about what to do. I am trying to follow everything that the Purpose of the methods ask of me. But I have been unsuccessful in doing so.
public class Stars
{
  private static final int MAX_STARS = 15;
  private static String BAR_REP = "*";
  private static DecimalFormat valueFormatter = new DecimalFormat("00.00");
  private static DecimalFormat indexFormatter = new DecimalFormat("000");

  public static void main (String[] args)
  {
     processQuestionData("5,25,30,36,46");
  }

 public static void processQuestionData(String data)
 {
    double[] values = fillArray(data);
    double max = findMax(values);

    drawBar(values, max); // This won't work but I have to pass 2 double values.
 }

 /**
 * PURPOSE: accepts a String data containing a comma separated list
 *          and converts it into an array of double values
 *
 *  @param String data - comma separated string containing double data
 *
 *  @return double [] - array containing the data extracted from data
 */

  public static double[] fillArray(String data)
  {
    String[] answers = data.split(",");
    double[] values = new double[answers.length];

    for (int index = 0; index < answers.length; index++)
    {
        values[index] = Double.parseDouble(answers[index]);
    }

    return values;
  }

 /**
 * PURPOSE: given a an array of double values find the largest item
 *
 *  @param double[] items - an array of double data
 *
 *  @return double the largest item in the array
 */
 public static double findMax(double[] items)
 {
    double maxValue = items[0];

    for(int index = 0; index < items.length; index++)
    {
        if (items[index] > maxValue)
        {
            maxValue = items[index];
        }
    }

    return maxValue;
 }

 **
 * PURPOSE: given a value and a max as double type arguments,
 *          draws a bar using '*' representing the value, scaled
 *          so that max value would equal the constant MAX_STARS
 *
 * @param double value - the value to be displayed by the bar in the chart
 * @param double max   - the max value for the bar chart
 */
 public static void drawBar(double value, double max )
 {
    double correctRatio = (value / max) * MAX_STARS;

    if (correctRatio == MAX_STARS)
    {
        for (int index = 0; index < max; index++)
        {
            System.out.print(BAR_REP);
        }
    }

    else if (correctRatio < MAX_STARS)
    {
       for (int index = 0; index < max; index++)
       {
          System.out.print(BAR_REP);
       }
    }
 }

}

Output should be this...
 *
 ********
 *********
 ***************

1st one is 1. Got that by (5 / 46) * 15
2nd one is 8. Found by (25/46) * 15
And so on....
How can I fix my code to exactly that? I believe that the major problem lies in calling the drawBar method and within the drawBar method itself. I don't think that the other methods are improperly coded.

A: Why not provide a "star bar" constant that has the maximum number of stars present, and use a substring of that constant to get the number you want (  myStars = C_STARBAR.substring(0,n) where n is the number of stars .. account for not going over maximum stars of course!

A: Change the signature and code of drawBar method like below. You will get your expected output.
public class Stars {
  private static final int MAX_STARS = 15;
  private static String BAR_REP = "*";

  public static void main (String[] args){
     processQuestionData("5,25,30,36,46");
  }

  public static void processQuestionData(String data) {
     double[] values = fillArray(data);
     double max = findMax(values);

     drawBar(values, max);
  }

  public static double[] fillArray(String data) {
     String[] answers = data.split(",");
     double[] values = new double[answers.length];

     for (int index = 0; index < answers.length; index++) {
       values[index] = Double.parseDouble(answers[index]);
     }

    return values;
 }

 public static double findMax(double[] items) {
   double maxValue = items[0];

   for(int index = 0; index < items.length; index++) {
     if (items[index] > maxValue) {
        maxValue = items[index];
     }
   }
 return maxValue;
 }

 public static void drawBar(double[] values, double max ) {

 for(int count=0;count<values.length;count++) {
     double value = values[count];
     int correctRatio = (int)((value / max) * MAX_STARS);

     for(int stars=1;stars<=correctRatio;stars++){
         System.out.print(BAR_REP);
     }
     System.out.println();
 }
 }

}


text:
Q: How to change terminal font color in PyCharm? I want to set my terminal color scheme, such that I will have black text on light background (white or light yellow for example).
I changed "Console Colors" settings, such as Background, Standard output, and System output, under Editor > Colors & Fonts > Console Colors, but I keep running into the same problem.
If I change Background color to let's say white. It also changes text (Standard output and my user input to the same color). I can't figure out, which setting controls the color of the font, which appears in the terminal window. In fact, it appears that font color is the same as background color, which is confusing to me. I would expect to be able to independently control background color, and font color, which to me represents "Foreground".
<

A: Changing colour in

Preferences->Editor->Color Scheme->Console Colors->Standard Output

should change the terminal font's colour.

A: I suppose it happened on Windows. If yes then it is affected/controlled by Windows registry. Try one of the following method:

*

*Open Windows cmd and from drop down menu selects defaults. Then change the Text and Background colors to match your choice in PyCharm. The problem occurs if you have different color settings in Windows cmd instead of default.

*Delete HKEY_CURRENT_USER\Console key from Windows registry.

More information available on this link

A: To configure color and font scheme for consoles

*

*Make sure you are working with an editable scheme.

*Open the IDE Settings, and under Colors&Fonts, scroll through the list of components, and select the ones related to consoles:

*

*Console Colors

*Console Fonts

*In the right-hand pane, click the desired component in the list, and change color settings and font type:
See Image of how to do it


text:
Q: How to properly complete Completable inside flatMap chain? I have a task to connect to remote service. When it is not connected - fire up whole connecting procedure, if is already connected - just complete. For this purpose i wrote this method -
public Completable execute() {
        return fptrService.isConnected()
            .flatMap(isConnected -> {
                if (isConnected) return Single.never();
                else return bluetoothService.isBluetoothAvailable();
            })
            .flatMap(isAvailable -> {
                if (isAvailable) return bluetoothService.isBluetoothActivated();
                else throw new BluetoothNotAvailableException();
            })
            .flatMap(isActivated -> {
                if (isActivated) return bluetoothService.searchForFptr();
                else throw new BluetoothNotActivatedException();
            })
            .flatMapCompletable(fptrService::connect);
    }

In 1st case, when service is not connected - all works fine. But if on the first stage isConnected() returns TRUE all chain stalls and Completable not completes at all. What can i do to force complete on first stage?

A:

    .flatMap(isConnected -> {
        if (isConnected) return Single.never();
        else return bluetoothService.isBluetoothAvailable();
    })

What you have told by this, is that if isConnected is true, then never emit an item, thus this observable will never terminate.
Instead, you should pass downstream a Single of false:

    .flatMap(isConnected -> {
        if (isConnected) return Single.just(Boolean.FALSE);
        else return bluetoothService.isBluetoothAvailable();
    })
    // Will continue stream if `isConnected` is true
    .filter(isConnected -> isConnected)
    // if `isConnected` is false, then downstream operators won't be executed


text:
Q: Grounds state of carbon - Hunds Rule I have a question about Hund's second rule for the ground state of carbon. Why is it that when S=1, L has to be 1 instead of 2? I don't get the whole symmetric/ antisymmetric argument. Why is L=2 symmetric and L=1 antisymmetric?

A: The $1s$ and $2s$ levels are filled, giving $j=0$.  There remains two electrons to place in the $2p$ states.  By Hund's rule, they will have $S=1$, which implies the spin wave function for the pair is symmetric under exchange of the electrons.  This means the spatial part of the wavefunction must be antisymmetric for the total spatial$\times$spin wavefunction to be antisymmetric, as required by the fermionic nature of the electrons.
When combining two $\ell=1$ states, the states with total angular momentum $L=2$ and $L=0$ are symmetric, while states of total angular momentum $L=1$ are antisymmetric.
You can check the symmetries of the spatial part from the properties of the CG coefficients
$C^{LM}_{\ell_1m_1;\ell_2m_2}$ under exchange of $\ell_1=\ell_2=1$:
$$
C^{LM}_{1m_1;1m_2}=(-1)^L C^{LM}_{1m_2;1m_1}
$$
indicating that the even $L$'s are symmetric and the odd $L$ antisymmetric.


text:
Q: changing the color of the particular part of an image by using as3 I have to change the color of the particular part of an image dynamically without affecting the image design. Any idea how to do this?
I want to change the color like this
http://www.bmw.com/com/en/newvehicles/3series/sedan/2008/visualizer.html
Thanks in advance.

A: In example you provided there is no color manipulation on the picture. Every time you change the color — new .swf asset with car loaded into the app(example). in my opinion that's the easiest way to solve problem like this.
On other hand, if you really want to manipulate color channels of particular image, the ColorMatrix Class by Quasimondo is in my opinion the best tool to do this. The tricky(hardest, maybe in some cases impossible) part here will be to select particular part of the picture were you need to convert colors.
Update
the idea is that, you load your app, withh .swf asset only for the default color, and when user choose any other color you simply download additional .swf asset.
As for the second approach with color manipulation, I'm thinking, if you need this only for already predefined pictures, that you can cut out part of your picture which you want to manipulate, and convert it to .png with transparent background, and put it on top of your original picture. So you will have something that looks like original pic, but in reality it's to separated layers: one is your unchangeable part of the image, and other is the part that you want to manipulate. Here is the example with unicorns(because everybody love unicorns):

Now you can use ColorMatrix to manipulate color channels of unicorn, and all other parts of your picture will be unchangeable.


text:
Q: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding I am using MVC(ASP.Net + C#) based application. I have used Jquery DataTable to display records. Now issue is that for some records its working good and for some records it's giving me error like "Timeout expired" at front end side.
I am using Entity Framework & Stored Procedure to fetch records. For some values It's giving me Timeout Error. If I directly executed this Sp with those require parameters (in which it's giving me Timeout Error) then it's working fine(but taking bit time around 11 seconds in SQL Server.). I just getting Timeout error frond end side.
I am getting below error.

{"Timeout expired.  The timeout period elapsed prior to completion of
  the operation or the server is not responding."} {"The wait operation
  timed out"}

I have tried added in web.config

*

*Connection Lifetime=120;

*Min Pool Size=120;

*Connection Timeout=300;

*Max Pool Size=1000;Pooling=true;

*<httpRuntime  executionTimeout="180" maxRequestLength="2000000000"  />
But didn't workout.
My Web.Config as below.
<add name="TestEntities" connectionString="metadata=res://*/Test2.csdl|res://*/Test2.ssdl|res://*/Test2.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Test2;integrated security=True;multipleactiveresultsets=True;Connection Lifetime=120;Min Pool Size=120;Connection Timeout=300;Max Pool Size=1000;Pooling=true;App=EntityFramework"" providerName="System.Data.EntityClient" />

Please help.
Thanks
-Nimesh

A: SQL server creates an execution plan for stored procedures to optimize the performance for further executions (parameter sniffing). When you execute this stored procedure on SSMS, it works fine but when you try to execute the same stored procedure from your ASP.NET MVC application, you'd face the timeout issue.
You can fix this by re-creating/altering your stored procedure WITH RECOMPILE option (after your parameters). I faced this issue today; altered my stored procedure WITH RECOMPILE option and it worked like a charm. For more details, read about Parameter Sniffing.

A: I have solved issue by increasing CommandTimeout To 120
Db.CommandTimeout = 120;


text:
Q: facebook login but include error I have a facebook login code, but I want to integrate a php include code and every time after login if I refresh the page then it again say login
<?php include "info.php";?>
the code is given below

<button id="loginBtn" onclick="logIn();" value="Login">Login</button>
<button id="logoutBtn" onclick="logOut();" value="Logout">Logout</button>

now I need help to get this problem solved


text:
Q: Are backups secured per user when using Time Machine Server on OS X Server (Mountain Lion)? I have a simple Time Machine Server configuration with 1 destination. Users are defined in Open Directory (but the machines that will be backing up to TMS do not login via Open Directory).
Updated info:
Each user has their own machine and are administrators on their own machine. They will log into the Time Machine Server using their own Open Directory username and password. Encryption of TM backups will not be used.
Given this configuration, are backups secured per user when using Time Machine Server on OS X Server (Mountain Lion)?

A: It depends on what you mean by "per user". There are two layers of security for the backup, based on different users (plus a third layer if you enable encryption of the backup). When you configure a client to back up to a server with Time Machine, you authenticate to the server with a name and password. That client's backup is stored as a disk image on the server with the file permissions set to allow only that user (and root) access to it. The disk image can also, optionally, be encrypted. Within that image, the backed-up files' original permissions are copied, so that on the client, users can only recover files they'd normally have access to. Let me go over these in a bit more detail (in a different order) and explain the implications:
Permissions on the client: If you go into Time Machine's recovery mode on the client, it respects the original permissions of the backed-up files -- a user logged into the client will not be able to examine or recover files they wouldn't have had access to on disk. However, enforcement of these permissions is taking place on the client; if someone has admin acess (or subverts security) on the client, they'll be able to bypass permissions within the backup (just as they can on the client's own disk). Also, if someone gets direct access to the backup disk image on the server, they can mount it in any mode they want (e.g. with file ownership disabled), and get full access to the backup.
Permissions on the server: the TM service is basically AFP file sharing, with an added "use this to back up" advertisement. To back up, the client uses a memorized username and password to mount the Backup folder, then create/mount the disk image within it, and store files into the image. There are several security implications here:

*

*If for example Joe sets up his computer to back up using his server account, and then Bill also creates an account on Joe's computer, Joe would be able to get at Bill's backed up files by simply mounting the shared Backup folder, then mounting the image with file ownership disabled.

*Joe's server password is stored in the System keychain on his computer (so that it can reconnect to the server to make backups). This means that anyone with admin access (legitimate or otherwise) to Joe's computer can recover his server password.
Because of this, I tend to recommend that the server account used for Time Machine should not be a regular user account, but a seperate per-computer account used only for backup (and preferrably restricted to only Time Machine and File Sharing in the service access controls), and certainly not sharing a password with any other account.

*If the server account used for TM ever has its password changed, the client will not be able to back up or recover files until the entry in its System keychain is updated with the new password. This is another reason not to use a regular user account…
Encryption: If encryption is enabled when TM is set up, the disk image will be encrypted (in addition to the server-based file permissions). The encryption password is also stored in the client's System keychain, so anyone with admin access on the client can recover it (again, don't reuse passwords). This does mean that if the server's security is subverted, the contents of the backup image will remain secure. However, you should make sure that the encryption password is recorded and stored securely, because you're going to need it if the client is lost or its HD crashes or… Unlike the server filesharing password, there's no way to reset or bypass this layer of the security.
UPDATE: Given the added details, yes, each client's backup will be secured based on their Open Directory account. Caveats: anyone with admin access to the server will be able to get at everyone's backups, and the OD account's password will be stored in the client Mac's System keychain (recoverable by anyone with admin access to the client).


text:
Q: characterize a family of functions parametrized by maximal monotone sets To start, a set $G\in \mathbb R^2$ is called maximal monotone if it is not a strict subset of a monotone set. For each maximal monotone set $G$, we can define a function
$$u_G(x_1,x_2)=\inf_{y\in G} \{(x_1-y_1)(x_2-y_2)\}-x_1x_2$$
The collection of all such functions will be denoted by $\mathcal U$. It is easy to see that every $u\in\mathcal U$ is concave, and $u(x)\leq -x_1x_2$. Heuristically, if we apply envelope theorem to differentiate $u$,we should expect
$$ \partial_{x_1}u(x)=-y_2\\
   \partial_{x_2}u(x)=-y_1    $$
where $(y_1,y_2)$ is a point such that the infimum is attained. It follows by plug such $y$ into the infimum that
$$ u(x)= \partial_{x_1}u(x)\partial_{x_2}u(x)+x_1\partial_{x_1}u(x)+x_2\partial_{x_2}u(x)$$
My question: Is there a characterization of the family $\mathcal U$, which is independent of the notion of maximal monotone set? (For example, I want to say $\mathcal U$ contains all concave functions bounded from above by $-x_1x_2$, such that some differential(sub-differential) equations/inclusions is satisfied.)


text:
Q: Box Blur CGImageRef I'm attempting to implement a simple Box Blur, but am having issues. Namely, instead of blurring the images it seems to be converting each pixel to either: Red, Green, Blue or Black. Not sure exactly what is going on. Any help would be appreciated.
Please note, this code is simply a first pass to get it working, I'm not worried about speed... yet.
- (CGImageRef)blur:(CGImageRef)base radius:(int)radius {
CGContextRef ctx;
CGImageRef imageRef = base;
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width *4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

char red = 0;
char green = 0;
char blue = 0;
for (int widthIndex = radius; widthIndex < width - radius; widthIndex++) {
    for (int heightIndex = radius; heightIndex < height - radius; heightIndex++) {
        red = 0;
        green = 0;
        blue = 0;
        for (int radiusY = -radius; radiusY <= radius; ++radiusY) {
            for (int radiusX = -radius; radiusX <= radius; ++radiusX) {

                int xIndex = widthIndex + radiusX;
                int yIndex = heightIndex + radiusY;

                int index = ((yIndex * width) + xIndex) * 4;
                red += rawData[index];
                green += rawData[index + 1];
                blue += rawData[index + 2];
            }
        }

        int currentIndex = ((heightIndex * width) + widthIndex) * 4;

        int divisor = (radius * 2) + 1;
        divisor *= divisor;

        int finalRed = red / divisor;
        int finalGreen = green / divisor;
        int finalBlue = blue / divisor;

        rawData[currentIndex] = (char)finalRed;
        rawData[currentIndex + 1] = (char)finalGreen;
        rawData[currentIndex + 2] = (char)finalBlue;
    }
}

ctx = CGBitmapContextCreate(rawData,
                            CGImageGetWidth( imageRef ),
                            CGImageGetHeight( imageRef ),
                            8,
                            CGImageGetBytesPerRow( imageRef ),
                            CGImageGetColorSpace( imageRef ),
                            kCGImageAlphaPremultipliedLast );

imageRef = CGBitmapContextCreateImage (ctx);

CGContextRelease(ctx);

free(rawData);
[(id)imageRef autorelease];
return imageRef;
}

A: The char colors should be declared as int.
int red = 0;
int green = 0;
int blue = 0;

A: I just have a comment. I used this script and it really works well and fast. the only thing is that it leaves the frame with width of radius which is not blurred. So I have modified it a bit so that it blurs whole area using mirroring technique near the edges.
For this one needs to put the following lines:
// Mirroring the part between edge and blur raduis
if (xIndex<0) xIndex=-xIndex-1; else if (xIndex>width-1) xIndex=2*width-xIndex-1;
if (yIndex<0) yIndex=-yIndex-1; else if (yIndex>height-1) yIndex=2*height-yIndex-1;

after these lines:
int xIndex = widthIndex + radiusX;
int yIndex = heightIndex + radiusY;

And then replace the headers of for loops:
for (int widthIndex = radius; widthIndex < width - radius; widthIndex++) {
    for (int heightIndex = radius; heightIndex < height - radius; heightIndex++) {

with these headers:
for (int widthIndex = 0; widthIndex < width; widthIndex++) {
    for (int heightIndex = 0; heightIndex < height; heightIndex++) {


text:
Q: trim specific parts of a string and put it in a table I have managed to get data from table in the data base, something like this:
$s = explode("»;}i:1;a:2:{s:8: »field_id »;i:7;",$data);
a:7:{i:0;a:2:{s:8: »field_id »;i:6;s:10: »user_value »;s:4: »jack »;}i:1;a:2:{s:8: »field_id »;i:7;s:10: »user_value »;s:5: »david »;}i:2;a:2:{s:8: »field_id »;i:8;s:10: »user_value »;s:5: »45587″;}i:3;a:2:{s:8: »field_id »;i:9;s:10: »user_value »;s:3: »447″;}i:4;a:2:{s:8: »field_id »;i:10;s:10: »user_value »;s:3: »115″;}i:5;a:2:{s:8: »field_id »;i:11;s:10: »user_value »;s:6: »Agadir »;}i:6;a:2:{s:8: »field_id »;i:13;s:10: »user_value »;s:0: » »;}}

I want to trim this and send it to a table  to be like
jack // david // 45587 // 477 // 115 // agadir


text:
Q: How to search transitive pom dependencies (for snapshots in particular) and prevent releases with any snapshot dependencies? I'm currently running into issues with incorrectly build dependencies that although are said to be releases, are actually dependent on snapshots. To identify "snapshot dependencies" (both transitive and direct), I'm using this mvn dependency:tree command:
mvn dependency:tree -Dincludes=:::*-SNAPSHOT

This worked pretty well, until I hit the following scenario: Someone must have taken a snapshot, and without changing anything else manually uploaded it as a release. What they didn't do, is to change the version of the parent pom which - yes, you guessed it right! - is a snapshot.
What happened also, to make the situation even worse, that snapshot parent pom was then deleted, and the build was failing because of the missing transitive snapshot pom dependency. I didn't hit the problem locally because without noticing I had downloaded it to my local mvn repo, but the CI build on a new slave that had an empty maven repository couldn't pull it.
So, I'm wondering if there's any way for finding all snapshot dependencies (pom and jar), including the transitive ones.
There's a question here that somewhat looked similar at the first glance: Maven dependency tree and pom dependencies It says that you can't do this with the maven dependency plugin.
I also found that since v2.9 there's the dependency:display-ancestors goal, but it only works on ancestors of the current pom, not on ancestors of the dependencies.
So, is there any other way how to figure this out - if not with the maven dependency plugin, then maybe somehow else?
In this post, someone wrote a custom plugin to enhance the dependency:display-ancestors functionality: Maven dependency tree and pom dependencies Is writing another custom plugin the only way for how to do this?
Or is there any kind of check that can also be run when creating a release to make sure that it's not dependent on any snapshots (incl. pom snapshots) and fail the build / stop the release if anything like that is discovered?
Being dependent on bad releases like that is really annoying and it would be really good to be able to analyze your dependencies one way or another to prevent this before things actually break, or worse, suddenly start changing quietly without you recognizing the problem until you get weird runtime issues.


text:
Q: Unable to add SQL server and Java script component in logicapp I am using Consumption Logic App for which I want to add SQL Server Component and Java Script component. I am unable to that.

Here is the workflow created and unable to find required components

A: Yes, you can achieve adding SQL server component or java script component using Consumption Logic app

.
However, you can achieve it using Standard Logic app also.

Please refer the following Document


text:
Q: Css removes when user clicks on date of datepicker I am developing an app in which we are highlighting dates in different colors by dynamically applying css and are using jquery mobile datepicker but when user click on any date the dynamically applied css got removed.
Thanks in advance


text:
Q: Assign a list of items to a variable and iterate in cursor SQL I have a predefined list of items which I want to use in select query.
DECLARE @cur_emp CURSOR;
DECLARE @TEST_ID int
DECLARE @TEST_NAME varchar(100)
DECLARE @names table(name varchar(100))

--SET @TEST_NAME = 'Order not timely approved'
insert into @names(name) values ('a')
insert into @names(name) values ('b')

--SET @TEST_NAME = CURSOR FOR (select name from @names)
WHILE EXISTS (select * from @names)
BEGIN
SET @cur_emp= CURSOR FOR (select TEST_ID from CS_TEST_V2 where test_name = @name)

Error says: @name is an invalid column name
Can somebody please help.

A: You have syntax errors in your cursor part. Please try this.
DECLARE @TEST_ID INT
DECLARE @TEST_NAME VARCHAR(100)
DECLARE @names TABLE (NAME VARCHAR(100))

--SET @TEST_NAME = 'Order not timely approved'
INSERT INTO @names (NAME)
VALUES ('a')

INSERT INTO @names (NAME)
VALUES ('b')

DECLARE cur_emp CURSOR
FOR
SELECT NAME
FROM @names;

OPEN cur_emp

FETCH NEXT FROM cur_emp
INTO @TEST_NAME

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @TEST_ID = (
            SELECT TEST_ID
            FROM CS_TEST_V2
            WHERE test_name = @TEST_NAME
            )

    FETCH NEXT FROM cur_emp
    INTO @TEST_NAME
END

CLOSE cur_emp

DEALLOCATE cur_emp