text:
Q: Powershell: How to reduce my comparison time of two Arrays I am currently rather new to PowerShell and Programming in general. I am developing a tool in PowerShell that takes two CSV files with anywhere from 5,000-40,000 lines and 30+ headers per line. The tool takes these two files and finds matching lines based on a key (Symbol) and reports the differences in the corresponding fields.
The script takes in two arguments: the two CSV files to be compared. Represented below as gcFile1 and gcFile2
These CSV files will not have the same amount of lines or all the same symbols but are listed alphabetically.
I was able to match strings based on my desired key, perform the comparison and properly output the differences.
My problem is that it takes entirely too long, my assumption is that because I'm using two ForEach loops to compare the objects it basically does this for every single line, making it take much longer than allowed.
I am looking for a way for the line to be removed from the subsequent searches once it is used to make for a smaller array to search through each time.
Thank you so much for any help :)
Here is a snippet of code that contains the ForEach loops:
#For each line in the first file
ForEach($line1 in $gcFile1)
{

    #For Each line in the second file
    ForEach($line2 in $gcFile2)
    {

    #If the symbol from file one is like a symbol from file 2
    If($line1.Split(';').Get(0) -like $line2.Split(';').Get(0))
    {

        $Symbol1 = $line1.Split(';').Get(0)
        $Symbol2 = $line2.Split(';').Get(0)

        for($x=0;$x -lt $headerCount1; $x++)
        {
            If($line1.Split(';').Get($x) -like $line2.Split(';').Get($x))
            {
                $Version1 = $line1.Split(';').Get($x)
                $Version2 = $line2.Split(';').Get($x)

            } else {

                $Version1 = $line1.Split(';').Get($x)
                $Version2 = $line2.Split(';').Get($x)
                $headerName1 = $headerArray1[$x]
                $headerName2 = $headerArray2[$x]

                $bufferLength = 30 - $headerName1.Length
                $pad = " "

                for($y = 0;$y -lt $bufferLength; $y++){

                $pad += " "

                }

                Write-Host "[$headerName1]$pad[$Version1 / $Version2]"
                Add-Content $logfileBoth "[$headerName1]$pad[$Version1 / $Version2]"

            }
        }
    }
}
}

Example from the CSV:
Symbol;Validity;AnnualHighDate-Date;AnnualHighDate-Time;AnnualLowDate-Date;AnnualLowDate-    Time;AverageVolume100Day;AverageVolume22Day;Beta;ClosePriceMonth;ClosePriceQuarter;ClosePriceWeek;Clo sePriceYear;HighPriceCalendar;LowPriceCalendar;Mo12RateOfReturn;MovingAverage100Day;MovingAverage14Day;MovingAverage200Day;MovingAverage21Day;MovingAverage50Day;MovingAverage9Day;Volatility20Day;Volatility6Month;YTDRateOfReturn;AverageVolume250;HighDateCalendar;Size;AnnualHighDate;AnnualLowDate;CalcLastUpdate
A;valid;20140122;0;20130904;0;1.81273e+006;1.85068e+006;1.3787;57.16;57.44;57.16;57.19;61.22;51.96;0.2481;56.54;57.68;56.59;56.81;56.92;57.67;0.1804;0.1796;0.0198;2320468;20140122;248;1/22/2014;9/4/2013;9/3/2014
AA;valid;20140723;0;20130904;0;1.52891e+007;1.1017e+007;1.5202;16.61;14.89;16.61;10.63;17.22;9.82;1.2085;14.92;16.49;13.02;16.4;16.11;16.59;0.146;0.2494;0.6011;22428276;20140723;248;7/23/2014;9/4/2013;9/3/2014

For example I will find the Symbol A in file 1, search file 2 for Symbol A and compare the columns that correspond to the same header.
The desired result is an output with the Symbol and a list of what columns are different, with version 1 and version 2
Sample Output:
============================== A ==============================

[Header] [file1.txt / file2.txt]

[AverageVolume100Day]            [1.84354e+006 / 1.81273e+006]
[AverageVolume22Day]             [1.85629e+006 / 1.85068e+006]
[Beta]                           [1.5311 / 1.3787]
[Mo12RateOfReturn]               [0.2484 / 0.2481]
[MovingAverage100Day]            [56.4635 / 56.54]
[MovingAverage14Day]             [57.455 / 57.68]
[MovingAverage200Day]            [56.5412 / 56.59]
[MovingAverage21Day]             [56.7281 / 56.81]
[MovingAverage50Day]             [56.9214 / 56.92]
[MovingAverage9Day]              [57.7011 / 57.67]
[Volatility20Day]                [0.0508 / 0.1804]
[Volatility6Month]               [0.1285 / 0.1796]
[YTDRateOfReturn]                [0.02 / 0.0198]
[AverageVolume250]               [2325140 / 2320468]

============================== AA ==============================

[Header] [file1.txt / file2.txt]

[AverageVolume100Day]            [1.58983e+007 / 1.52891e+007]
[AverageVolume22Day]             [1.11858e+007 / 1.1017e+007]
[Beta]                           [1.6706 / 1.5202]
[LowPriceCalendar]               [9.825 / 9.82]
[Mo12RateOfReturn]               [1.1749 / 1.2085]
[MovingAverage100Day]            [14.8568 / 14.92]
[MovingAverage14Day]             [16.4471 / 16.49]
[MovingAverage200Day]            [12.9426 / 13.02]
[MovingAverage21Day]             [16.3967 / 16.4]
[MovingAverage50Day]             [16.0764 / 16.11]
[MovingAverage9Day]              [16.5478 / 16.59]
[Volatility20Day]                [0.0385 / 0.146]
[Volatility6Month]               [0.178 / 0.2494]
[YTDRateOfReturn]                [0.5767 / 0.6011]
[AverageVolume250]               [22544029 / 22428276]

A: The canonical answer to such a problem is to use a lookup table. There are many ways to create one. The general approach is as follows.
Calculate a hash for each data row from the first input. Store the hashes in a container. After you got the lookup table ready, read the second file row-by-row and calculate hash the same way. Check if the lookup table contains the hash. If it doesn't, you got a row that didn't exist in the first file. If it does, you got exact match.
One can calculate the hash by using, say, MD5. Store the hashes in a sorted list and use binary search to find matches in O(n log n). The more simple alternative is to use hash table (aka associative array) that does hash calculations behind the curtains.
In your case, a hash of entire data row doesn't seem to be feasible. It might be more suitable to generate a lookup table that uses hash only to find the relevant row for further processing.
As for how to create a lookup table, look at another a post.

A: You need at least PowerShell 3.0 for this to work. Although it can be changed to support 2.0
$firstData = Import-CSV C:\temp\sample.csv -Delimiter ";" | Group-Object -AsHashTable -AsString -Property Symbol
$secondData = Import-CSV C:\temp\sample2.csv -Delimiter ";" | Group-Object -AsHashTable -AsString -Property Symbol

$firstData.GetEnumerator() | ForEach-Object{
    If ($secondData.ContainsKey($_.Key)){
        $symbol = $_.Key

        [PSCustomObject]@{
            'Symbol' = $symbol
            'AverageVolume100Day' = "$($firstData[$symbol].AverageVolume100Day) / $($secondData[$symbol].AverageVolume100Day)"
            'AverageVolume22Day' = "$($firstData[$symbol].AverageVolume22Day) / $($secondData[$symbol].AverageVolume22Day)"
        }
    }
}

The solution is not completly built but enough to show you what i was trying to do. You could make this so that all the parameters you are interested in are stored seperately instead of spelling the all out like I have done with AverageVolume100Day and AverageVolume22Day. Also, I do not have enough sample data to get this going
What this does is import both samples of data as CSV's and converts the data into a hash table where the Name si the symbol and the rest of the data is the value.
Cycling through each symbol and verify if it has a match in the other sample data set. If a match is found build a custom object that has each value from each sample set of data compared with a backslash like in your data.
I ommited the Header from your output as having it repeated seemed repetative :). I have no idea if this will be more efficient but I would consider giving it a try.
Sample output.
Symbol                      AverageVolume100Day         AverageVolume22Day
------                      -------------------         ------------------
AA                          1.52891e+007 / 1.52891e+007 1.1017e+007 / 1.1017e+007
A                           1.81273e+006 / 1.81573e+006 1.85068e+006 / 1.85368e...

The output in powershell might not be as readable and some columns might be trucated. Having this all sent to Export-CSV would be an option.
Update from comments
This is a similar solution with the added bonus of having dynamic headers. I need to work on the output a little since I'm not happy with it yet.
$firstData = Import-CSV C:\temp\sample.csv -Delimiter ";" | Group-Object -AsHashTable -AsString -Property Symbol
$secondData = Import-CSV C:\temp\sample2.csv -Delimiter ";" | Group-Object -AsHashTable -AsString -Property Symbol
$propertyNames = @("AverageVolume100Day","AverageVolume22Day","AnnualHighDate-Date")
$properties = @{}

$firstData.GetEnumerator() | ForEach-Object{
    If ($secondData.ContainsKey($_.Key)){
        $symbol = $_.Key

        $properties.Symbol = $symbol
        ForEach($property in $propertyNames) {
            $properties.$property = "$($firstData[$symbol].$property) / $($secondData[$symbol].$property)"
        }
        New-Object Psobject -Property $properties
    }
} | Format-List

Use the array $propertyNames to fill in headers as needed. In a ForEach-Loop cycle through each and build the $properties. When you have many headers then Format-List will make the output readable.


text:
Q: Tomcat installation cannot specify JavaHome I am trying to write a powershell script to install Tomcat9 on a Windows 10 machine.
Here is the command line I created.
Reference: https://tomcat.apache.org/tomcat-9.0-doc/setup.html
Invoke-Expression "C:\installer\apache-tomcat-9.0.41.exe /C=C:\installer\install-config /S /D=C:\Tomcat"

install-config file I created is like this:
JavaHome=C:\java
TomcatPortHttp=80
TomcatServiceName=My_Tomcat

TomcatPortHttp and TomcatServiceName work fine. However, instead of using the Java location I specified with JavaHome, Tomcat service uses the latest JRE it can find in Windows.

Is this a bug?
Does anyone know how to force Tomcat service to use the Java location in the config file?

A: I have not verified it, but judging by the Tomcat Windows Service Documentation I would try to set the Jvm parameter with the full path to the jvm.dll on your system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Fast Live Filter character issue HERE: http://jsfiddle.net/uo5ufobp/
When i use upper case letter "İ" for filtering , it is working.

But it is not working when i use lower case  i

my html page

<input id="search_input" placeholder="Sektör Ara"  class="filtrele_put" style=""  >

Alkollü İçecekler

Bahçe Ve Çocuk Firmaları

Çiçekciler

Yapay Çiçek

İç Dekorasyonr

İç Giyim

İç Giyim ve Çamaşır

İç Mimarlı

İçecek Sektörü

Yapay Çiçek/a>

this is  jQuery Fast Live Filter.js included..
jQuery.fn.fastLiveFilter = function (list, options) {
    // Options: input, list, timeout, callback
    options = options || {};
    list = jQuery(list);
    var input = this;
    var lastFilter = '';
    var timeout = options.timeout || 0;
    var callback = options.callback || function () {};

    var keyTimeout;

    // NOTE: because we cache lis & len here, users would need to re-init the plugin
    // if they modify the list in the DOM later.  This doesn't give us that much speed
    // boost, so perhaps it's not worth putting it here.
    var lis = list.children();
    var len = lis.length;
    var oldDisplay = len > 0 ? lis[0].style.display : "block";
    callback(len); // do a one-time callback on initialization to make sure everything's in sync

    input.change(function () {
        // var startTime = new Date().getTime();
        var filter = input.val().toLowerCase();
        var li, innerText;
        var numShown = 0;
        for (var i = 0; i < len; i++) {
            li = lis[i];
            innerText = !options.selector ? (li.textContent || li.innerText || "") : $(li).find(options.selector).text();

            if (innerText.toLowerCase().indexOf(filter) >= 0) {
                if (li.style.display == "none") {
                    li.style.display = oldDisplay;
                }
                numShown++;
            } else {
                if (li.style.display != "none") {
                    li.style.display = "none";
                }
            }
        }
        callback(numShown);
        // var endTime = new Date().getTime();
        // console.log('Search for ' + filter + ' took: ' + (endTime - startTime) + ' (' + numShown + ' results)');
        return false;
    }).keydown(function () {
        clearTimeout(keyTimeout);
        keyTimeout = setTimeout(function () {
            if (input.val() === lastFilter) return;
            lastFilter = input.val();
            input.change();
        }, timeout);
    });
    return this; // maintain jQuery chainability
}

some settings
 $(function() { $('#search_input').fastLiveFilter('#search_list');   });

What can i do for this isssue?
HERE: http://jsfiddle.net/uo5ufobp/


text:
Q: Process.Kill() doesn't seem to kill the process I am having trouble using Process.Kill(). I think I must be misunderstanding how it works. This is my test function. I start a long-running process (ping -t) and then kill it five seconds later.
I can see the ping process show up, but the process is still there after my program finishes. I have to kill it manually.
Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
Process process = new Process();

startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = "/c ping -t 8.8.8.8";

Console.WriteLine("Staring ping process");
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);
Thread.Sleep(5000);

Console.WriteLine("Killing ping process");
process.Kill();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);

What am I doing wrong here?

A: process.Kill() is working, just not on the process you think. What you're doing is actually starting 2 processes and only killing the first process, while the second process keeps running.
The code you have is starting a new command shell and saving that process info to process. When you call process.Kill() only the command shell is exiting You can run
Console.WriteLine(process.ProcessName);

before you process.Kill() to see which process is actually going to be killed. By setting \c ping -t 8.8.8.8 as arguments to the command shell, you're telling the command shell to start another process (in this case ping) and disjoin it from itself. Your program has no knowledge about the child process and will not kill it. If all you really want is to kill the ping process you can change your code to:
Console.WriteLine("Total number of ping processes is {0}",  Process.GetProcessesByName("ping").Length);

ProcessStartInfo startInfo = new ProcessStartInfo("ping");
Process process = new Process();

startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = "-t 8.8.8.8";

Console.WriteLine("Staring ping process");
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);
Thread.Sleep(5000);

Console.WriteLine("Killing ping process");
process.Kill();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);

If, however, you really need to start the command shell first you'll need to find the child processes and have logic to kill that. Something like:
foreach( var p in Process.GetProcessesByName("ping"))
{
  p.Kill();
}

[EDIT]
*Sorry, I didn't see the comments from @Adriano Repetti  at first. I didn't mean to be redundant.

A: You started cmd.exe, then cmd.exe starts child process ping.exe. To kill ping.exe you can kill all process hierarchy. For example with WMI(add System.Management reference):
private static void KillProcessAndChildrens(int pid)
{
    ManagementObjectSearcher processSearcher = new ManagementObjectSearcher
      ("Select * From Win32_Process Where ParentProcessID=" + pid);
    ManagementObjectCollection processCollection = processSearcher.Get();

    try
    {
        Process proc = Process.GetProcessById(pid);
        if (!proc.HasExited) proc.Kill();
    }
    catch (ArgumentException)
    {
        // Process already exited.
    }

    if (processCollection != null)
    {
        foreach (ManagementObject mo in processCollection)
        {
            KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.)
        }
    }
}

A: This is a patch for the @SulNR answer since its answer leak child processes of child processes.
private static void KillProcessAndChildrens(int pid)
{
    ManagementObjectSearcher processSearcher = new ManagementObjectSearcher
      ("Select * From Win32_Process Where ParentProcessID=" + pid);
    ManagementObjectCollection processCollection = processSearcher.Get();

    // We must kill child processes first!
    if (processCollection != null)
    {
        foreach (ManagementObject mo in processCollection)
        {
            KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.)
        }
    }

    // Then kill parents.
    try
    {
        Process proc = Process.GetProcessById(pid);
        if (!proc.HasExited) proc.Kill();
    }
    catch (ArgumentException)
    {
        // Process already exited.
    }
}

A: FWIW a VS2019 Visual Basic version of Julio's modification.
   Private Sub KillProcessAndChildrens(pintPID As Integer)

      Dim processSearcher As New ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pintPID.ToString)

      Dim processCollection As ManagementObjectCollection = processSearcher.Get()
      '     We must kill child processes first!
      If Not IsNothing(processCollection) Then
         For Each mo As ManagementObject In processCollection
            KillProcessAndChildrens(Convert.ToInt32(mo.Item("ProcessID")))
         Next
      End If

      '    // Then kill parents.
      Try
         Dim proc As Process = Process.GetProcessById(pintPID)
         If Not proc.HasExited Then
            proc.Kill()
         End If

      Catch ex As Exception
         '         Process already exited.
      End Try
   End Sub

A: It's very simple:
foreach (var process in Process.GetProcessesByName(processName))
{
    try
    {
       process.Kill();
    }
    catch { }
}

With this method, you can also kill processes with a higher protection level like taskmgr.exe. If you want to prevent a process from starting, here is a piece of code suitable for that, at least as long as the process running this code is active:
    private void Disable(string processName)
    {
        var timer = new Timer()
        {
            Interval = 1,
            Enabled = true
        };
        timer.Tick += (s, e) =>
        {
            foreach (var process in Process.GetProcessesByName(processName))
            {
                try
                {
                    process.Kill();
                }
                catch { }
            }

            GC.Collect();
        };
    }

A:
In order to kill a process you have to run under an administrative
  account. This means either that you are a 'true' administrator or you
  User Account Control (UAC) turned off.
Otherwise Process.Kill() will fail.

From here.


text:
Q: sending a single image to the server from android I am trying to post a single image to the server

*

*I am making a POST request

*When i make the post request, image is not sent to the server ( I
checked the server )

What i have tried::
MainActivity.java
public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();

            }
        });
    }

    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     */
    private void postImageData(){

        //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapdata = stream.toByteArray();
        String image_str = Base64.encodeToString(bitmapdata, Base64.DEFAULT);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("imageData", image_str));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.v("Response", response.toString());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            postImageData();

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

How can i resolve this ?

[EDIT]
I checked whether the server is running correctly or not for accepting the images, but it looks running perfectly fine ! when checked with postman-tool for uploading images, so problem has to be the client part
MainActivity.java
public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();

            }
        });
    }

    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException
     */
    public void postImageData() throws IOException
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId));

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                postImageData();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

A: You have to use MultipartEntity for upload Image to Server
  public void postImageData()
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId));

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

A: You can try out this.
public class MainActivity extends Activity {
        Bitmap bm;
        String url_path = "http://yoururl.php?";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            try {
                bm = BitmapFactory.decodeResource(getResources(), R.drawable.annag);

                // bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
                executeMultipartPost();
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }

        public void executeMultipartPost() throws Exception {

            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(url_path);
                ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
                                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("store_name", new StringBody("amazon"));
                reqEntity.addPart("file", bab);
                postRequest.setEntity(reqEntity);

                HttpResponse response = httpClient.execute(postRequest);

                String my_response = convertStreamToString(response.getEntity()
                        .getContent());
                Toast.makeText(getApplicationContext(), my_response,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public static String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }


text:
Q: How to get rejected promise from promise.all? I have written following code for uploading files on the server asynchronously with the help of promises. And we know that promise.all will fail once anyone of the promises will fail. So, i want to to know which promise is actually failed and in my case name of file for which the promise was failed. I am trying console.log(e1) but it is not giving me information about failed promise. Can anyone please help me do it?
uploadFilesAndSendStatus(stateType, notes, estimate, visibleToCustomer = null)
  {
    let filesPromise = Promise.resolve([]);

    const promises = this.state.files_to_upload.map((file) => {
      return this.uploadFilesOnServer(file);
    });

    filesPromise = Promise.all(promises).then((results) => {

      return [].concat(...results);
    }).catch((e1) =>{
      console.log(e1);
      this.setState({
         serverActionPending: false,
         serverActionComplete: false,
         file_upload_try_again: true,
      });
    });
}

UploadFilesOnServer code is:
uploadFilesOnServer(file) {
    let files=[];
    let file_id='';
    const image=file;
    const promise = getAttachmentUploadURL(this.props.task.id)
    .then((imageUrlResponse) => {
      const data = new FormData();

      data.append('file-0', image);

      const { upload_url }  = JSON.parse(imageUrlResponse);

      return uploadAttachment(upload_url, data);
    })
    .then ((updateImageResponse) => {
      file_id= JSON.parse(updateImageResponse);

      files.push(file_id);

      return files;
    });

    return promise;
  }

A: You can add that information to the error object:
const promises = this.state.files_to_upload.map((file, i) => {
  return this.uploadFilesOnServer(file).catch(err => {
    const e = new Error("upload failed");
    e.index = i;
    e.filename = file
    throw e;
  });
});

const filesPromise = Promise.all(promises).then(res => [].concat(...res)).catch(e1 => {
  console.log(e1);
  …
});


text:
Q: "Relative unsatisfiability" of SAT instances There's a natural way to view any SAT instance as a variety: just replace the Boolean algebra $2$ of truth values with the corresponding Boolean ring $\mathbb{Z}/2\mathbb{Z}$. (See my answer to Is there an equivalent concept of a "variety" for SAT?). A SAT instance is solvable iff the corresponding polynomial has a zero.
This raises a natural question: What happens when we extend the field?
Specifically, for a SAT instance $\varphi$, let $p_\varphi$ be the associated polynomial. For a field extension $F\supset \mathbb{Z}/2\mathbb{Z}$, we can ask whether $p_\varphi$ has a point over $F$.
In particular, take "nice" to mean "Galois." Then I'm interested in classifying the "relative unsolvability" of SAT instances. Formally, let $\varphi, \psi$ be SAT instances, presented using $\wedge$ and $XOR$ instead of $\wedge$ and $\vee$ (so that we can think of $\varphi$ and $\psi$ immediately as polynomials). Then say "$\varphi\le_G\psi$" if for every Galois extension $F\supseteq\mathbb{Z}/2\mathbb{Z}$, if $\psi+1$ has a zero over $F$ then $\varphi+1$ has a zero over $F$.
So, for example, $"(x\wedge x)+x"<_G "\perp"$ - the former corresponds to the polynomial $x^2+x+1$, the latter to $1$.
My question is:

What can we say about "$\le_G$?" In particular, how do I tell whether $\varphi\le_G\psi$?

My tags are somewhat speculative - feel free to alter them. In particular the "nonclassical logic" tag is purely a guess on my part.


text:
Q: Issue creating "custom" user URLs I am running into the following issue:
Our members have a desire for personalized sites directly from our primary domain in the form of http://www.example.com/membername. I am looking at possibly solutions in two ways but neither are ideal (will be explained below).
Method 1 - ?Member=
In this method, I simply create a custom URL and store the information in the member's database profile. For example: if I want my "custom" URL to be jm4, for a consumer to visit my site, they must type in http://www.example.com?Member=jm4.
The site, of course, does a $_GET['Member'] to lookup the member information, stores the primary data in Session from the index page, then redirects to a homepage. The consumer no longer sees the membername in the URL but instead sees all the page names for www.example.com as if they simply visited the parent domain to start (each member's page has custom information however).
While this method works it presents the following problems:

*

*The URL is not nearly as easy as /jm4
and any errors typing out the
wildcard ?Members= will result in
page error. Also, This method keeps
that particular member's information
in session (which is necessary
browing from page to page on that
particular member domain) and
prevents somebody from simply typing
http://www.example.com?Member=name2 to
visit another site without clearing
their session or closing the browser.

Method 2 - /membername
While the preferred method, currently the only way we know how to create is to manually generate an index file in a subfolder, redirect to the primary index then allow the consumer to view the member's personal site.
For example, if I visit www.example.com/jm4, I am hitting the /jm4 folder which contains index.php. Within this file simply contains:
<?php
session_start();
ob_start();

$_SESSION['AgentNumber'] = "779562";
header("Location: ../index.php");
exit;
?>

the primary index recognizes this with:
<?php
session_start();
ob_start();

if ($_SESSION['MemberNumber'] == NULL) {
     header("Location:ac/");
     exit;
}

$conn = mysql_connect("localhost", "USER", "PW");
mysql_select_db("DB",$conn);

$sql = "SELECT * FROM table WHERE MemberNumber = $_SESSION[MemberNumber]";
$result = mysql_query($sql, $conn) or die(mysql_error());
while ($newArray = mysql_fetch_array($result)) {
    $_SESSION['MemberName'] = $newArray['MemberName'];
    $_SESSION['MemberPhone'] = $newArray['MemberPhone'];
    $_SESSION['MemberMobile'] = $newArray['MemberMobile'];
    $_SESSION['MemberFax'] = $newArray['MemberFax'];
    $_SESSION['MemberEmail'] = $newArray['MemberEmail'];
    $_SESSION['MemberAddress'] = $newArray['MemberAddress'];
    $_SESSION['MemberCity'] = $newArray['MemberCity'];
    $_SESSION['MemberState'] = $newArray['MemberState'];
    $_SESSION['MemberZip'] = $newArray['MemberZip'];
    $_SESSION['MemberAltName'] = $newArray['MemberAltName'];
}
mysql_close($conn);
header("Location: home/");
exit;
?>

We would certainly prefer to use the second method in terms of 'ease' for the member but keep running into the following issues:

*

*We are forced to manually create a
sub-folder and unique index.php file
for each new member we onboard

*While the above probably could be
automated (when new member creates
profile, automatically generate php
file and folder) but this is more
complicated and we don't want to
have 3000 subfolders on the primary
domain.

Has anybody run into similar issues? If so, how did you go about solving it? What would you recommend based on my details above? Any advice is appreciated.
Also - using as subdomain (membername.example.com) is not preferred because our current SSL does not allow for wildcards.
EDIT 1 - EXISTING .HTACCESS FILE
My existing .htaccess file on the site looks like this for reference:
ErrorDocument 404 /404.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /?Member=$1 [L]

A: You can do your prefered method by just adding some lines to the .htaccess in your root directory:
This site should get you started
Or this one

A: If you are using apache, then you could use mod_rewrite to change urls like http://host/membername to http://host/memberpage.php?name=membername.

A: You could use this in a .htaccess file for your second method.  It will rewrite http://yoursite.com/membername to http://yoursite.com/?Member=membername
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /?Member=$1 [L]
</IfModule>


text:
Q: "Unspecified error" in sql that goes away after few seconds I built a parser that takes data stored in an xml file and sends it into a Microsoft Access database using linq-to-sql. I have the sql insert commands and they work... until they don't.
It's odd, I have each SQL command run (I keep them in a List and execute each command one at a time) and the first 40 or so run fine until they start hitting "unspecified error"s. The thing is, if I swallow the exception and instead have the exception catcher keep retrying, after a few seconds, they start working again.  This means it's not an error of the SQL query itself (or at least how it's written).
This pattern repeats (there are thousands of inserts) many times. If I do normal exception handling, the program will just skip a few records while the error happens and keep inserting when whatever causes it temporarily goes away. if I let it run it's course, it inserts some records, skips some, inserts, skips, repeat and eventually inserts less than 2/3 of the records.
Is there any reason why my computer would only run 40 or so Inserts and then refuse to run more for a random but short interval?
I'm at a loss on what could be causing this.
The application is natively run; it does not use any server/web communication and all I found when looking for "unspecified error" pointed me to occurrences in ADO.NET applications.
Here's the code the error happens in:
public static string insertQuery(string sql)
    {
        string connetionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Owner\Desktop\Arbeit\TrademarkParserproject1\TrademarkParserproject\bin\x86\Debug\Database.accdb";
        OleDbConnection connection;
        OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
        connection = new OleDbConnection(connetionString);

        string success = "false";

        try
        {
            connection.Open();
            oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
            oledbAdapter.InsertCommand.ExecuteNonQuery();

        }

        catch (Exception ex)
        {
            success = ex.ToString();
            return success;
        }

        success = "true";
        return success;
    }

Note, I have the application running in X86 mode to avoid errors with the ACE.OLEDB.12.0 adapter.

A: One thing that stands out, is you never close/dispose your SqlConnection. OleDbDataAdapter is also disposable and should be disposed. A 'using' statement is a convenient construct here:
public static string insertQuery(string sql)
{
    string connetionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Owner\Desktop\Arbeit\TrademarkParserproject1\TrademarkParserproject\bin\x86\Debug\Database.accdb";
    using(var oledbAdapter = new OleDbDataAdapter())
    using(var connection = new OleDbConnection(connetionString))
    {
        string success = "false";

        try
        {
            connection.Open();
            oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
            oledbAdapter.InsertCommand.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            success = ex.ToString();
            return success;
        }

        success = "true";
        return success;
    }
}


text:
Q: How to mock http request in sagas (black box testing approach) I am trying to take a black box approach and use sagaTester to test my sagas.
This is the saga.js from react-boilerplate:
export function* getRepos() {
  // Select username from store
  const username = yield select(makeSelectUsername());
  const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`;

  try {
    // Call our request helper (see 'utils/request')
    const repos = yield call(request, requestURL);
    yield put(reposLoaded(repos, username));
  } catch (err) {
    yield put(repoLoadingError(err));
  }
}

export default function* githubData() {
  // Watches for LOAD_REPOS actions and calls getRepos when one comes in.
  // By using `takeLatest` only the result of the latest API call is applied.
  // It returns task descriptor (just like fork) so we can continue execution
  // It will be cancelled automatically on component unmount
  yield takeLatest(LOAD_REPOS, getRepos);
}

This is my saga.test.js:
it('black box testing using sagaTester', async () => {
    const initialState = fromJS({
      home: {
        username: 'john',
      },
    });
    const sagaTester = new SagaTester({ initialState });
    sagaTester.start(githubData);

    sagaTester.dispatch(loadRepos());

    nock('https://api.github.com/repos?type=all&sort=updated')
      .get('/users/john')
      .reply(200, 'hello world');

    await sagaTester.waitFor(reposLoaded.type);
  });

This is the error that I've got:

Error: Timeout - Async callback was not invoked within timeout
  specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

All I am trying to do is to mock the response from this line:
const repos = yield call(request, requestURL);

What am I doing wrong????
Any help is appreciated!!!

A: The main 2 problems with yout code are:

*

*missing CORS header

*wrong waitFor call

Working example:
nock('https://api.github.com')
  .get('/users/john/repos')
  .query({ type: "all", sort: "updated" })
  .reply(200, [{ name: 'First repo', }, { name: 'Second repo', }], {'Access-Control-Allow-Origin': '*'});

await sagaTester.waitFor(reposLoaded().type);

A: I hope this will help others who stumble across this problem.
The problem here was whatwg-fetch which is the baked in library in react-boiler-plate.
I looked at the example here and I noticed that node-fetch was being used.
So I replaced this line:
const repos = yield call(request, requestURL);

with:
const repos = yield call(() => fetch(requestURL));

and my test worked.
Another thing, if you want to use axios instead of whatwg, then you better use axios-mock-adapter to mock the request. Finally got this working after hours of fiddling. Thanks for your help!


text:
Q: Change table cell from span to input on click I am trying to change the table cell from 'span' type to 'input' on click and then back to 'span' on blur but it isn't working as given in here:
Convert table cells to text-boxes with JQuery
here is the javascript code:

and here is the document body

                Name
                ast1
                Location
                Loc-1

                Name
                ast2
                Location
                Loc-2

using jQuery 1.7.2
What's wrong here ? Please help !
Thanks!!
Update: only need to change the cells with class='asset_value' and only one cell at a time not all. Also, it should change back to span on blur..

A: Try this :
$(document).ready(function() {
    $('#assets').on('click', 'span', function() {
        var $e = $(this).parent();
        if($e.attr('class') === 'asset_value') {
            var val = $(this).html();
            $e.html('<input type="text" value="'+val+'" />');
            var $newE = $e.find('input');
            $newE.focus();
        }
        $newE.on('blur', function() {
            $(this).parent().html(''+$(this).val()+'');
        });
    });
});

this will change single cell on click and revert back to span on blur.

A: You can use the replaceWith() method, html() method empties the selected element and appends html markup to it, try the following:
    $(document).ready(function() {
        $('#assets').click(function () {
            $('tr td:nth-child(3)').each(function () {
                var html = $(this).html();
                var input = $('<input type="text" />');
                input.val(html);
                $(this).replaceWith(input);
            });
        });
    });

DEMO

As the replaceWith method changes the structure of the markup, you should delegate the events for the generated markup, you can use the on method, try the following:

    $(document).ready(function() {
        $(document).on('click', '#assets td', function () {
                var html = $(this).text()
                var input = $('<input type="text" />');
                input.val(html);
                $(this).replaceWith(input);
                $('#assets input').focus();
        });

        $(document).on('blur', '#assets input', function(){
            $(this).replaceWith(''+this.value+'	')
        })
    });

DEMO

A: Hopefully, this will help you: http://jsfiddle.net/RBGME/19/
HTML:

            Name
            ast1
            Location
            Loc-1

            Name
            ast2
            Location
            Loc-2

Sample CSS:
td { border: 1px solid #aaa; height: 30px; text-align: center; width: 100px; }
input, input:hover, input:focus { width: 100px; height: 30px; box-sizing: border-box; outline: none; background-color: #eee; }

jQuery:
$(document).ready(function() {
    $('#assets tr td:nth-child(3)').click(function () {
        var html = $(this).html();
        var input = $('<input type="text" />');
        input.val(html);
        $(this).replaceWith(input);
    });
});?

A: I think you are on the right way
try this:
$(document).ready(function() {
   $('#assets').click(function () {
       $(this).find("span").replaceWith(input);
   });
});

A: $('td').click(function(){
$(this).children('span').html('<input type="text">');
})


text:
Q: Cache atime writes Is there a way to set atime writes to be cached for a very long time? I need atime (that is to say, relatime won't cut it), but I don't want it to effect performance so much. Data loss in of atimes (and atimes only) is acceptable in some cases (e.g. power failure).

A: I found lazytime, a mount option for ext4, that solves this satisfactorily for me.
https://lwn.net/Articles/620086/

This mode causes atime, mtime, and ctime updates to only be made to the in-memory version of the inode.  The on-disk times will only get updated when (a) when the inode table block for the inode needs to be updated for some non-time related change involving any inode in the block, (b) if userspace calls fsync(), or (c) the refcount on an undeleted inode goes to zero (in most cases, when the last file descriptor assoicated with the inode is closed).

This option is available since kernel 4.0.
As well, it is necessary to override the default of relatime, otherwise you get relatime functionality in addition to the caching functionality of lazytime. To do this, mount with strictatime AND lazytime.


text:
Q: Oracle APEX Field Validation I have a simple question regarding field validation on Oracle Apex. I am trying to put validation on the 'Work Package Name' text field to be either 'WP' followed by two digits or 'AM' followed by two digits e.g WP00 & AM01 would be accepted and WP000 & AN01 would not be accepted.
I was unsure of which validation option to choose therefore I decided to use PL/SQL returning a boolean. The code I have seems to be incorrect (see below).
If I was creating this in TOAD I would have declared the field name however I am presuming that by using the :P7_WP_NAME this is doing the same job.
IF :P7_WP_NAME = WP(2,0)
ELSE IF :P7_WP_NAME = AM(2,0)
THEN RETURN TRUE;
ELSE
  RETURN FALSE;
END IF;

The error I am receiving at present is below. I have tried reworking the code but keep getting different errors:

ORA-06550: line 2, column 1: PLS-00103: Encountered the symbol "ELSE" when expecting one of the following: . ( * % & - + / at mod remainder rem then <an exponent (**)> and or || multiset
ORA-06550: line 7, column 18: PLS-00103: Encountered the symbol ";" when expecting one of the following: if The symbol "if" was substituted for ";" to continue.
ORA-06550: line 7, column 54: PLS-00103: Encountered the symbol    "end-of-file" when expecting one of the following: begin case declare
end exception

I would be grateful if either you could tell me if this is the best validation option to use and where I am going wrong.

A: I'm not great with regular expression but have a go at this:
begin
   if regexp_like(:P7_WP_NAME,'^WP\d{2}$')
   or regexp_like(:P7_WP_NAME,'^AM\d{2}$')
   then
      return true;
   else
     return false;
   end if;
end;

The regexp probably be simplified to:
regexp_like(l_string,'^(WP|AM)\d{2}$'

to match both the WP and the AM in one expression.

A: Regarding the error

'ORA-06550: line 2, column 1: PLS-00103: Encountered the symbol "ELSE" when expecting one of the following: . ( * % & - + / at mod remainder rem then and or || multiset ORA-06550: line 7, column 18: PLS-00103: Encountered the symbol ";" when expecting one of the following: if The symbol "if" was substituted for ";" to continue. ORA-06550: line 7, column 54: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin case declare end exception'

you should have used ELSIF instead of ELSE IF.


text:
Q: Multiple rotations on UIButton I want to rotate a UIButton multiple times with the same degree every time (90°). The issue I'm having is that it performs one 90° spin then the next time I press the button it starts from 0 again and goes to the same, previous value. My code;
let rotateView = CABasicAnimation()

    rotateView.toValue = 90 * (M_PI) / 180

    rotateView.duration = 0
    rotateView.repeatCount = 0
    rotateView.removedOnCompletion = false
    rotateView.fillMode = kCAFillModeForwards
    rotateView.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    smile2.layer.addAnimation(rotateView, forKey: "transform.rotation.z")

I think the problem may be that I can't specify the fromValue as I use a random number to begin with - here is the code;
let value: NSArray = [90, 180, 270, 360]
    let range: UInt32 = UInt32(value.count)
    let randomNumber = Double(arc4random_uniform(range))

To make it extra clear: The button's fromValue is a random number in the let value. I want to make the button spin 90° from that random number continuously at every button press.

A: The problem is partly these lines:
rotateView.removedOnCompletion = false
rotateView.fillMode = kCAFillModeForwards

That sort of thing is just a crutch, and shows that you don't really understand how animation works. You are leaving out a crucial step, and covering up that failure with those lines. The crucial step is that you must set the view's transform to the same value that the animation is going to give it. Once you do that, those lines will be unnecessary, and successive animations will work correctly.
Also note that your life will be a lot simpler if you use additive animation, since you can then just rotate 90 degrees from wherever you are.


text:
Q: Google Maps places API to only return cities? I am trying to use Google's map API to only return cities from their json request:
 https://maps.googleapis.com/maps/api/place/autocomplete/json?input=green%20lanes&types=geocode&sensor=false&types=regions&key=*API KEY HERE*

The key being &types=regions but it still returns all results.
For example, I am searching for the street Green Lanes and rather than returning cities that might contain Green Lanes its returning the street in London as the top result.

A: This is an old question, but the accepted answer is not correct for the specific question.
The correct argument for the types parameter to return only cities is (cities). So the complete URL would be:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=green%20lanes&types=(cities)&key= API_KEY_HERE
You can see more information here. Also, I omitted the sensor parameter since it's not needed anymore.

A: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=green%20lanes&types=geocode&sensor=false&types=regions&key=API KEY HERE
should be
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=green%20lanes&sensor=false&types=(regions)&key=API KEY HERE
ZERO RESULTS, because regions does not search for street name:
the (regions) type collection instructs the Place service to return any result matching the following types:
locality
sublocality
postal_code
country
administrative_area1
administrative_area2

A: This is from the https://developers.google.com/maps/documentation/places/web-service/supported_types:
The (cities) type collection instructs the Places service to return results that match locality or administrative_area_level_3.


text:
Q: My angular expressions are not being rendered by the browser I am learning angular js from code school and this is their code. It wont display my products rather it shows the code exactly as in {{..}}. I have thoroughly checked for errors nothing seems to work. I have tried removing th alias of StoreController as store and used just StoreController, that doesn't work either. I enclosed my entire js code in a function but that didnt work too. I have attached the picture of my result too.
My Javascript Code in ang.js file
    var app = angular.module('GemsStore',[]);

    app.controller('StoreController',function(){
        this.products=gems;
    });

    var gems=[
        {
            name:'Diamond',
            price:100,
            description:'Shiny',
            canPurchase:true,
            soldOut:false
        },

        {
            name:'Sapphire',
            price:200,
            description:'Shiny',
            canPurchase:true,
            soldOut:false
        }
    ];

My html Code
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

{{store.product.name}}

{{store.product.price}}

{{store.product.description}}

        <button class="btn-default" ng-show="store.product.canPurchase">Add To Cart</button>

o

My result
edited code

A: JS code
app.controller('StoreController', function() {
  var gems = [{
      name: 'Diamond',
      price: 100,
      description: 'Shiny',
      canPurchase: true,
      soldOut: false
    },
    {
      name: 'Sapphire',
      price: 200,
      description: 'Shiny',
      canPurchase: true,
      soldOut: false
    }
  ];
  this.products = gems;
});

Your HTML code

{{product.name}}

{{product.price}}

{{product.description}}

        <button class="btn-default" ng-show="product.canPurchase">Add To Cart</button>


text:
Q: Console.ReadKey not returning correct value I made this code for keybind settings in my console application:
Console.Write("Awaiting input, press Esc to cancel");
ConsoleKeyInfo key = Console.ReadKey();
while (key.Key == ConsoleKey.Enter)
{
    // pressing Enter triggers this method, so we don't want the user to accidentally set a keybind to Enter
    key = Console.ReadKey();
}
if (key.Key != ConsoleKey.Escape)
{
    // set controls
}
Console.Clear();

But for some reason, when I press Enter, sometimes it returns the keypress before the user presses Enter. (e.g. Down Arrow)
But when you press enter again, it sometimes returns the keypress before the first Enter press.
Even if you press the desired value before you press Enter, sometimes it just returns a random key you have pressed before. (e.g. you press Z, then Enter, but then Console.ReadKey() returns UpArrow)
This is hurting my brain more and more, can anyone help me please?

A: I don't really understand these sentences:

But for some reason, when I press Enter, sometimes it returns the keypress before the user presses Enter. (e.g. Down Arrow)
But when you press enter again, it sometimes returns the keypress before the first Enter press.

But looking at your code, wouldn't this make more sense:
Console.Write("Awaiting input, press Esc to cancel");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey();

    if (key.Key != ConsoleKey.Enter && key.Key != ConsoleKey.Escape)
    {
        // set controls
        break;
    }
} while (key.Key != ConsoleKey.Escape);

Console.Clear();


text:
Q: Android Emulator RAM not extending for Google Play API 27 When I make create a Virtual Android Device on Android Emulator with Google Play API 27, it does not allow me to give a custom amount of RAM size. Instead it takes a default 1536 MB RAM and 800 MB of Internal Storage. I don't understand why....

A: I solved this issue by changing the value in the config file.
In the list of virtual devices (in android studio) click on the arrow on the right side of your device and click on "Show on Disk".
In the folder should be a config.ini file, open it and change hw.ramSize=1536 to Example: hw.ramSize=4092

A: I expirienced some problems with the Android Virtual Device (loading times) and I started using Genymotion. I suggest you to do so. It is easy to use and full compatible with Android Studio.

A: As per the update for Oreo 8.1 there might be a restrictions due the feature of Android Oreo (Go edition)
Features in the Android Oreo (Go edition) configuration include:
Memory optimizations. Improved memory usage across the platform to ensure that apps can run efficiently on devices with 1GB or less RAM.
Flexible targeting options. New hardware feature constants to let you target the distribution of your apps to normal or low-RAM devices through Google Play.
Google Play.While all apps will be available on devices running Android Oreo (Go edition), Google Play will give visibility to apps specifically optimized by developers to provide a great experience for billions of people with the building for billions guidelines.
this might be restricting the emulator to choose the best optimal option to run app on your virtual device.


text:
Q: SD probability problem involving chi-square distribution Preparing for an exam in statistics, I have been pondering the following problem:

Given that in country X 14% of people hold a university degree, find the probability that for a random sample of size 200 the standard deviation is less than 20.

Trying to compute this resulted in ridiculously high values for the chi-square-distribution.
Any input would be warmly welcomed.

A: Sometimes on exams you just have to answer them literally as written.  It helps to explain and justify your interpretation.  In this case presumably the question refers to the university degree as coded with a binary ($0/1$) variable.  Let's assume it really does ask about samples with a standard deviation less than $20$.
There are just $201$ possible samples, parameterized by their total, $k$.  The mean of such a sample is $k/200$ and therefore its variance (without assuming any bias correction factor) is the average squared deviation from this mean, equal to
$$V(k) = \frac{1}{200}\left(k(1 - k/200)^2 + (200-k)(0 - k/200)^2\right) = k - k^2/200.\tag{1}$$
This attains its maximum when $k=100$, at which point it equals
$$V(100) = 100 - 100^2/200 = 50.$$
Since a standard deviation of $20$ corresponds to a variance of $20^2 = 400$, it is certain that the standard deviation will be less than $20$.  The answer, then, is $1$.

Using $1/199$ instead of $1/200$ as the factor in formula (1), to correct for bias, will not change this answer.


text:
Q: Is it bad practice to have "generic" enums? I have a graphics program with a "BlockType" enum. Depending on the state, this might be one of several things: Wood, Stone, Grass, etc.
Originally, there were various texture operations that had to be done for each possibility, but thanks to some refactoring, the enum is only used as an integer, and is no longer needed for switch statements. I.e.:
BlockType someFoo = someObj.blockType;

Texture usedTexture = textureLookupArray[(int) someFoo];

But as a side effect of this, the Enum strings are entirely redundant! I could put the "Stone" Texture at position 5, even if BlockType 5 is defined as "Carpet", "Gravel", or "JQuery"!
My first thought was to simply rewrite BlockType to define "Material1, Material2, etc." instead of hardcoded (and potentially conflicting!) values, but does that actually serve a useful purpose?
Might there be some benefit I'm overlooking to keep BlockType as an enum, or should I just switch it over to a regular Int to reduce confusion?

A: Why use an array when a dictionary would be much, much better?
private Dictionary<BlockType, Texture> _textures =
    new Dictionary<BlockType, Texture>
    {
        { BlockType.Wood, new WoodTexture() },
        { BlockType.Metal, new MetalTexture() },
        //etc
    }

Much more elegant to use
var tex = _textures[someObj.blockType];


text:
Q: Javascript dynamicly change DOM using PHP PHP code
    <?php

    ...

    //Extract the data that was sent to the server
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

    $findemail = [
    "email" => $email,
    "password" => $password,
    ];

    $cursor = $collection->findOne($findemail);
    if($cursor){
    if($cursor['email'] == $email and $cursor['password'] == $password){

// I Know these two lines don't work but I want to show what I want to do
       echo "success";
        header('location: cms-view-products.html');
    }

else {
    echo "failed";
    header('location: login.php');
}

}

      ?>

AND this is my HTML code
  <?php include('demo2.php') ?>

<!DOCTYPE html>

        <form action="demo2.php" onsubmit="return false"; method="post">
            Email: <input type="email" name="email" required >
            name: <input type="password" name="password" required >
        <button type='submit' onclick="loadContent()">Load</button>
        </form>

Dynamically loaded content goes here

I've currently tried to echo the message via JS, the specific element

, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.


text:
Q: Windows phone 8.1 ApplicationData.Current.LocalFolder Size limit? I am developing windows phone 8.1 runtime application, I need to store mp3 files in local folder of app, to avoid access to user.
But to do this Is there any size restrictions or file count restriction to store files on local storage.
any suggestion is appreciated.
Thanks


text:
Q: Find all natural $n$ for which the integral is non-zero I have to find all natural $n$ such that
$$I=\int_{|z|=2}\frac{z^n}{z^{10} - 1}dz \neq 0$$
Since all the $10^{\text{th}}$ roots of unity lie in $|z|=2$, by residue theorem we have
$$\int_{|z|=2}\frac{z^n}{z^{10} - 1}dz = 2\pi i \cdot\sum_{k = 0}^{9}\ \text{Res}(f,e^{k\pi i/5})=\frac{2\pi i}{10} \cdot\left(\sum_{k = 0}^{9}z^{n-9}\rvert_{e^{k\pi i/5}}\right) = \begin{cases}0\quad n\not\equiv9\pmod {10} \\ 2 \pi i\quad n\equiv9\pmod {10} \end{cases}$$
Am I correct?

A: Another way is to use the substitution $w=1/z$. That gives
$$I=-\int_{|w|=1/2}\frac{w^{-n-2}}{w^{-10}-1}\,dw
=-\int_{|w|=1/2}\frac{w^{8-n}}{1-w^{10}}\,dw.$$
When $n\ge0$ the function
$$\frac{w^{8-n}}{1-w^{10}}=\sum_{k=0}^\infty w^{8-n+10k}$$
has a Laurent series about $0$, and the integral is nonzero
if its residue (the coefficient of $w^{-1}$) does not vanish. That's the
case iff $n$ is a positive integer congruent to $-1$ modulo $10$.


text:
Q: Gmail API sends email but some are never being received I recently tried my hands at the new Gmail API. And all seems to work fine except one thing. My issue is as follows:
I working on a receptionist project that may need to generate more than one email in less than a minute during busy hours. So just for testing purposes I run the following code which works fine:
if __name__ == '__main__':
  service = setup()      //Simply an helper function to do the basic credential check. Works fine!
  print('service:'+str(service))

  for counter in range(1, 10):
    print('Sending message '+ str(counter))
    message = create_message(<SENDER_EMAIL_ID>,<RECEIVER_EMAIL_ID>, "Email Number: "+ str(counter) , "Sample text")
    response = send_message(service, 'me' , message)
    print(response)

The setup() function is as follows:
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

Now, when I run the code say thrice consecutively in less than a minute, the code runs fine and I am able to see all the 27 emails in the sent folder of the SENDER_EMAIL_ID using a web browser. And thus Gmail API is sending all the messages through whenever a request is being made. However, only some of these emails are being received at the RECEIVER_EMAIL_ID and rest are just being dropped.
However, if I run the program with say 2-5 minutes delay then all the mails are being received.
I have no idea why this is.
Any help would be really appreciated. :)

A: To expound more on @ken-y-n's response in the comments section, GMail API has usage limits. Specifically for this product, Daily usage is about

*

*1 Billion quota units / day

*250 quota units / user / second

You may have encountered the rateLimitExceeded error during your tests.
Since you're sending emails thru a loop, it will cost you about 100 units when calling send (plus other costs depending on the methods you're calling). This is the reason why some emails seemed to be dropped. You can counter this by implementing exponential backoff on the messages that failed to send.
Another alternative instead of running it thru a loop, is to use Batch requests which groups your API calls together to reduce the number of HTTP connections your app making.


text:
Q: How do we construct the simple functions which approximate a random variable and are used to obtain the expectation (Lebesgue integral)? Let $(\Omega,\mathcal{F},\textbf{P})$ be a probability space and $X:(\Omega,\mathcal{F},\textbf{P})\to(\textbf{R},\mathcal{B}(\textbf{R}))$ be a non-negative random variable. In order to define the expectation of such random variable $X$, we need the definition of the corresponding Lebesgue integral, which can be defined as:
\begin{align*}
\int_{\Omega}X\mathrm{d}\textbf{P} = \sup\left\{\int_{\Omega}Y\mathrm{d}\textbf{P} : (0\leq Y\leq X)\wedge(Y \ \text{is simple})\right\}
\end{align*}
where a simple function $Y:(\Omega,\mathcal{F},\textbf{P})\to(\textbf{R},\mathcal{B}(\textbf{R}))$ is a measurable function which takes finite values.
Such definition is equivalent to say that
\begin{align*}
Y(\omega) = \sum_{k=1}^{n} y_{k}1_{D_{k}}(\omega)
\end{align*}
where each $D_{k}$ is measurable and $\{D_{1},D_{2},\ldots,D_{n}\}$ is a partition of $\Omega$. In such case, we define the integral of $Y$ as follows:
\begin{align*}
\int_{\Omega}Y\mathrm{d}\textbf{P} = \sum_{k=1}^{n}y_{k}\textbf{P}(D_{k})
\end{align*}
which can be thought as the center of mass of the distribution.
When studying the notion of Lebesgue integral, I have heard that we must partition the image of $X$ into intervals in order to build simple functions which approximate better and better the random variable $X$ as we "refine" the partition.
My question is: is such reasoning underlying the construction of the simple random variables that approximate $X$ correct? If it is not the case, how should I construct the simple random variables that are used to approximate the random variable $X$ and which are used to obtain the expectation?
Any help is greatly appreciated!


text:
Q: Screen scraping with HtmlAgilityPack in C#. Can not retrieve innertext I am trying to write an application that gets the xpath of a node in a web browser, and then stores it for scraping later.
I have this for getting the click event of the browser:
    private void htmlDocument_Click(object sender, HtmlElementEventArgs e)
    {
        HtmlElement element = this.wbrBrowser.Document.GetElementFromPoint(e.ClientMousePosition);

        var savedId = element.Id;
        var uniqueId = Guid.NewGuid().ToString();
        element.Id = uniqueId;

        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(element.Document.GetElementsByTagName("html")[0].OuterHtml);
        element.Id = savedId;

        var node = doc.GetElementbyId(uniqueId);
        var xpath = node.XPath;

        lblXpath.Text = xpath;
        lblPrice.Text = GetPrice(xpath);
    }

And it "seems" to work.  It does return an xpath of "/html[1]/body[1]/div[3]/div[2]/div[3]/div[1]/div[1]/ul[1]/li[2]/span[2]"
Now I have this to try and grab the innertext with the xpath that was stored:
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(lstURL.Text);
        XPathNavigator docNav = doc.CreateNavigator();

        XPathNavigator node = docNav.SelectSingleNode(xpath);

        if (node != null)
        {
            price = node.Value;
        }
        else
        {
            MessageBox.Show("Error: Node was Null!");
        }

        return price;
    }

But every time I try the 2nd method, the node is null.  I can't figure out if its a problem with the xpath im retrieving, or the xpath when it tires to scrape the info.  I am guessing the code in one of my methods is wrong but I am having trouble figuring out which one.


text:
Q: autorep command(belongs to autosys) not executing in crontab. Why? Below is my cron entry:
#!/bin/bash
09 01 * * * /home/c/charlesp/jobs.sh > /home/c/charlesp/jobs1.log 2>&1

which gives me only the error output, but not the actual output for which the script is written. The script is working fine and giving desired output when it is executed directly, but not in cron. When it is running in crontab, the error given is below. Please help. The errors are only coming when I run them in cron; not outside of cron.
Errors:
1.When i give autorep command directly in the script:
/home/c/charlesp/jobs.sh: line 3: autorep: command not found

2.When i give autorep command along with absolute path in the script:
/opt/CA/WorkloadAutomationAE/autosys/bin/autorep: error while loading shared libraries: libascmn.so: cannot open shared object file: No such file or directory

My script is below:
Only autorep command:
#!/usr/local/bin/bash
autorep -j ALL -L0 | grep -w RU > /home/c/charlesp/jobs.txt

With absolute path :
#!/usr/local/bin/bash
/opt/CA/WorkloadAutomationAE/autosys/bin/autorep -j ALL -L0 | grep -w RU > /home/c/charlesp/jobs.txt

A: As stated by Gordon, cron run with a minimal environment.
For Error 1:
First of all, we need to use absolute paths for everything in the script which we keep as cron entry. So complete path is given in the script like below.
/opt/CA/WorkloadAutomationAE/autosys/bin/autorep -j ALL -L0 | grep -w RU > /home/c/charlesp/jobs.txt
Got error 2 here.
For Error 2:
Since libascmn.so is unavailable, we need to export that path where libascmn.so is present to LD_LIBRARY_PATH like below.
-bash-4.3$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/CA/WorkloadAutomationAE/autosys/lib
Got error 3 here.
For Error 3:
Below is the error:
Resource bundle is not available while looking for key="CAUAJM_E_80003".
For this, we need to source the environment of autosys like below.
-bash-4.3$ . /opt/CA/WorkloadAutomationAE/autouser.TQ1/autosys.sh.automgmtq1
Now, even if it does not work with .sh script, change it to .csh script.
Now the script will work like a charm in Cron.
Thank You. :)


text:
Q: How to capitalize names Basically if I want to transform a name from
stephen smith

to
Stephen Smith

I can easily do it with come CSS on the page, but ideally I would like to catch it earlier on and change it when it comes out of the database. How can I get C# to capitalise a string?
Is there a function for this?

A: This is an extension method on the string class that capitalizes a single word. You can use it alongside a str.Split() and str.Join to capitalize every word of the str string. You can add checks for empty or one character length strings.
public static string Capitalize(this string word)
{
    return word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
}

A: You can do this using the ToTitleCase method of the System.Globalization.TextInfo class:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));

A: Note that the process will most likely be slow if you have many, many strings to change case...
string str = "to title case";
Char[] ca = str.ToCharArray();

foreach(Match m in Regex.Matches(str, @"\b[a-z]"))
{
    ca[m.Index] = Char.ToUpper(ca[m.Index]);
}
Console.WriteLine(new string(ca));

Or you could also use a custom evaluator to change the case like this:
string str = "to title case";
Console.WriteLine(Regex.Replace(str, @"\b[a-z]", delegate (Match m)
                                              {
                                                  return m.Value.ToUpper();
                                              }
                  ));

Note that in my test with 1,000,000 iterations the first method was only 0.48 seconds faster than the one with the evaluator (the first one took 6.88 seconds and the latter 7.36 seconds to complete the 1,000,000 iterations) so I wouldn't take speed into account to choose either...

A: Names are tricky. The simple rules of First Letters do not apply. The only sensible approach here is to ask your users how they want it. Anything else can cause offence.
If my name is MacPhearson, ODowel, or just simply marc, Marc or even mArC - then frankly: leave it alone. Trust the user to get it right. This gets even more tricky as you go between cultures.

A: No, there isn't. Providing you know the string you are handling is a name (or, better to say, a sequence of human names separated by spaces) you should be able to code it yourself within one for cycle and using Char.ToUpper. However, there a culture-specific cases like Arabian words "bin", "al", etc. used in names, which shall not be capitalized (providing a Latin transcription is used). The same holds for "von" or "van" in Western languages.
Please note that the TextInfo.ToTitleCase serves a different purpose — it's not intended to capitalize first letters of human names, but to provide proper casing of titles (like headlines of news articles to be clear).
Although the current implementation in .NET can easily serve the requested purpose, I'd avoid doing so. The reason is the implementation may change significantly in the future and hence it's safer to make a custom implementation for human names. Moreover, I doubt the method is really usable for title-casing of strings with respect to the given culture. For example, in Czech ("cs-CZ") the proper title-case should capitalize just the first letter of the first word only.

A: A slight extension on the answer offered by Pedro:
Regex.Replace(Name, @"(?:(M|m)(c)|(\b))([a-z])", delegate(Match m) {
    return String.Concat(m.Groups[1].Value.ToUpper(), m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value.ToUpper());
 });

This will correctly capitalize McNames in addition to title case. For example,
"simon mcguinnis" → "Simon McGuinnis"

*

*The first non-capture group will match any word-break character OR "Mc" / "mc".

*If it matches a word-break, then groups 1 and 2 are empty and group 3 contains that character.

*If it matches "Mc" or "mc" the groups 1 and 2 contain "m" and "c" and group 3 is empty.

*Group 1 (the "m" or "M") is capitalized.

*Group 2 (the "c") remains un-altered.

*Group 3 (the break character) remains un-altered.

*Group 4 (the first letter of the next word) is capitalized.
All four groups, empty or otherwise, are concatenated to generate the return string.

A: I use a single line:
string.Join(" ", str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(c => c.Substring(0, 1).ToUpper() + c.Substring(1).ToLower()));

A: This works for me with surnames that have a ' character in them.
        if (Surname.Contains("'"))
        {
           String[] Names = Surname.Split('\'').ToArray();
           Surname = textInfo.ToTitleCase(Names[0].ToString());
           Surname += "''";
           Surname += textInfo.ToTitleCase(Names[1].ToString());
        }


text:
Q: Java Servlet How to filter pages by User Role I'm coding a security web app. And I have a problem. For example , there is a pages called " Manager (JSP) " . I only want admins to see this page.
When user login the website , session create.
if(dao.check(uname, pass)) {
        UserAccount user = new UserAccount();
        user.setUsername(uname);
        HttpSession session = request.getSession();
        session.setAttribute("username", uname);
        response.sendRedirect("welcome.jsp");
    }

Heres the UserAccount Class :
public class UserAccount {
private String username;
private String password;
private List<String> roles;

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public List<String> getRoles() {
    return roles;
}
public void setRoles(List<String> roles) {
    this.roles = roles;
}

}
And i have a Filter class which implements Filter. How program get understand who is admin or not and let to see manager page?

A: You can use a boolean attribute in your UserAccount class , this attribute will hold a value of true if the use is an admin , and false if he is not
public class UserAccount {
private String username;
private String password;
private List<String> roles;
private boolean is_admin;
...}

The redirection to manager page will see first if the current user is admin or not , so he will be denied if he's not an admin

NB : i see that you are using a List of roles , so maybe you're using a Role-Based access control ( like RBAC or RABAC )
In that case maybe you're giving admin permissions through his roles , so here the Filter method will see the user's roles list and check if it contains the role of admin , and if yes it will redirect into the manager page


text:
Q: Pseudo code to correct Geographic points for UTM Easting distortion on Web Mercator Projection I have chosen to use a Web Mercator projection system for:

*

*Use of Tiling system for low memory usage

*Accessing only one site/area at a time

*Reuse of Google Tiles - for many sites

In some cases I will use high resolution UTM images, projected onto the tiled Web Mercator user interface. I suspect it is due to Easting distortion increasing in severity at greater distances from the central meridian.
see Calculating areal distortion outside UTM zone?
This is inaccessible to me as a Software Engineer with inadequate experience in GIS. Needing:

*

*To know if that linked answer has the full capability for my situation

*To know how to represent that as two Pseudo code functions: i) Point GeoToUTMPoint(Point Geo); and ii) Point UTMToGeoPoint(Point UTM).

You need to download the images and toggle between them to see the distortion. The site here is in Geelong, Australia with UTM Zone 55S. Markers placed on the map (see second UTM Tiled image) and have an assumed Geo-Coordinate. When those are placed in Google Maps there is an offset error. The top left and bottom right are quite stable, areas to the top right and bottom left increasingly shift the coordinates generally anti-clockwise but moreso shearing than fully rotating.
I know there's a reason Web Mercator is resisted being non-conformal. But I'm hoping there are some here who can at least point me in the right direction with a few pseudo code functions that I can use together.
I'll pay for the answer and keep it published for all: https://www.upwork.com/jobs/Function-for-Correcting-Distortions-from-UTM-Projection_~01661dc8f1a19fbb8c. If you want the money you need to prove you answered it of course, which can happen if you publishing a code (I supply from upwork chat) in a comment with your same StackExchange alias.

A: I don't know if you need to implement this distortion correction Calculating areal distortion outside UTM zone? specifically.  There are open source solutions to perform the conversion you asked for in your need #2: i) Point GeoToUTMPoint(Point Geo); and ii) Point UTMToGeoPoint(Point UTM). Here is one project in Javascript for lat/lon to UTM and vice versa.

*

*https://github.com/chrisveness/geodesy
For lat/lon to spherical mercator (web mercator) take a look at https://github.com/mapbox/node-sphericalmercator.

A: If the correct site boundary geo-coordinates are known and used to supply tiles, you'll find the top left and bottom right will have no distortion.
(When using such a TMS projection system designed for Web Mercator, you can't mix static UTM images with TMS Tiles.)
Because the correct boundaries are known you can use the same technique used for the tiles to also get the correct geo-coordinates. A user-input click yields a coordinate from the mapping control, with that coordinate you can find the ratio of the position relative to the image boundaries.
Then because you also know the UTM boundaries (in metres) you can deduce the Easting/Northing of the false supplied geo-coordinate, and then use a standard algorithm to convert from UTM Transversal to WGS84 Web Mercator Geo-coordinate.
Trust me, it worked for me after many hours of trying everything. I'm not saying that mixing UTM with a Web Mercator TMS system is a great idea, but it can be made to work, mainly with ratios.
Here's my C# source code for going in one direction:
private GeoPoint MapToGeo(Location location)
{
    //Top left is considered the origin

    //Geodetic boundaries and metrics of image
    var mapImageGetTopLeft = _SiteImage.GeoTopLeft;
    var mapImageGeoBottomRight = _SiteImage.GeoBottomRight;
    var mapImageGeoWidth = mapImageGeoBottomRight.Longitude - mapImageGetTopLeft.Longitude;
    var mapImageGeoHeight = mapImageGeoBottomRight.Latitude - mapImageGetTopLeft.Latitude;

    //Input point's offset from the origin
    Trace.WriteLine(string.Format("Before: http://maps.google.com/maps?q=loc:{0},{1}", location.Latitude, location.Longitude)); // new GeoPoint(location2.Latitude, location2.Longitude);
    var GeoWidthProgress = location.Longitude - mapImageGetTopLeft.Longitude;
    var GeoHeightProgress = location.Latitude - mapImageGetTopLeft.Latitude;

    //The magic ratio - this can be applied to both the image pixels or directly to the meters values (if already stored)
    var WidthRatio = GeoWidthProgress / mapImageGeoWidth;
    var HeightRatio = GeoHeightProgress / mapImageGeoHeight;

    //UTM Width and Height
    var mapImageUTMWidth = _SiteImage.EastingBR - _SiteImage.EastingTL;
    var mapImageUTMHeight = _SiteImage.NorthingBR - _SiteImage.NorthingTL;

    //Apply the ratios to the width and height
    var UTMWidthProgress = mapImageUTMWidth * WidthRatio;
    var UTMHeightProgress = mapImageUTMHeight * HeightRatio;

    //Add the UTM origin
    var UTMEasting = UTMWidthProgress + _SiteImage.EastingTL;
    var UTMNorthing = UTMHeightProgress + _SiteImage.NorthingTL;

    //Correction for datums
    UtmPoint utmPoint = new UtmPoint(UTMEasting, UTMNorthing, _SiteImage.ZoneTL, location.Latitude > 0);
    string datum = CurrentSite.Datum;
    // if datum is OSGB36 we need to convert the utmPoint to WGS84
    if (datum.Equals("OSGB36"))
    {
        utmPoint = CoordinateConverter.OSGB36toWGS84(utmPoint);
        datum = "WGS84";
    }

    //Final transversal to geodetic conversion
    GeoPoint finalGeo = CoordinateConverter.UtmToGeo(utmPoint, datum);
    Trace.WriteLine(string.Format("Final: http://maps.google.com/maps?q=loc:{0},{1}", finalGeo.Latitude, finalGeo.Longitude)); // new GeoPoint(location2.Latitude, location2.Longitude);
    return finalGeo;
}


text:
Q: Return points present in circle of particular radius from specified location I'm using PostgreSQL. I wish to return the points withing circle from particular point that is geocode. Now i have a geocode and radius of circle. From this data can i calculate the points present within the circle?
 Actually i have tried this with PostGIS and it's working fine but PostGIS deals with spatial data only and i have non-spatial data.
In PostGIS i have used following query :
select addressid,ST_AsText(geocode)geocode from aspatial_address as A where ST_Point_Inside_Circle(a.geocode,14.083333,19.583333,7)

my table structure is :
create table maddress
{
 addressid bigint(30) primary key;
 addressline varchar2(40) not null;
 geocode varchar2(20) not null;
}

and i wish to return the points present in circle whose radius is 7 km from geocode(14.083333,19.583333).
Now, hint me..how can i do this in PostgreSQL? Is it possible here? Is their any geometric function used in PostgreSQL? Please let me know..

A: PostgreSQL has a few geometry types that you can use:
SELECT addressid, addressline, geocode
FROM maddress
WHERE geocode::point <@ circle '((14.083333,19.583333), 7)';

Note that if geocode produces x and y with non-standard punctuation, you should use string function to parse geocode into a format that the point type will accept.
Keep in mind that if geocode and (14.083333,19.583333) are in long-lat coordinates you cannot use the PostgreSQL geometry types because the units are different (spherical long-lat in degrees for the geocode locations and center of the circle vs planar distance in km for the radius). In that case you have to use PostGIS to transform the long-lat coordinates to some planar coordinate reference system.


text:
Q: Git find modified files since  from a shallow clone I'm on a CI box running tests. To speed it up, I'm just doing a shallow clone:
git clone --depth 1 git@github.com:JoshCheek/some_repo.git

Assuming all the tests pass, I want to trigger the next step in the pipeline. What to trigger is based on which files changed between the last deployment (ref d123456) and the current ref I just tested (ref c123456). If I had done a normal clone, I could find out like this this:
git diff --name-only d123456 c123456

But my clone is shallow, so it doesn't know about those commits. I see that I can use git fetch --depth=n to get more of the history, but I only know the SHA, not the depth of the SHA. Here's a set of ways that could presumably answer this question:
# hypothetical remote diff
git diff --name-only origin/d123456 origin/c123456

# hypothetical ref based fetch
git fetch --shallow-through d123456
git diff --name-only d123456 c123456

# hypothetical way to find the depth I need
depth=`git remote depth-to d123456`
git fetch --depth "$depth"
git diff --name-only d123456 c123456

Otherwise it seems like I might have to write a loop and keep invoking --deepen until my history contains the commit. That seems painful (meaning annoying to write / maintain) and expensive (meaning slow, remember that the purpose of the shallow clone is to reduce this cost).

A:
Otherwise it seems like I might have to write a loop and keep invoking --deepen until my history contains the commit. That seems painful ...

It is painful (and slow, as you note a bit later).
Modern Git (since version 2.11) does have a new git fetch option:

--shallow-exclude=<revision>

* Deepen or shorten the history of a shallow repository to
   exclude commits reachable from a specified remote branch or tag.
   This option can be specified multiple times.

I have not tried this; it's not clear if it allows a hash ID (the tests use names) and in any case you would specify the parent(s) of the commit you want to deepen through, rather than the commit you want to obtain.  But it might suffice.
(I really think a better method is to keep reference clones you can borrow-from.)

A: There are several possible solutions to reduce the clone time and space besides shallow-clone.
1.git clone <url> -b <branch> --single-branch
This fetches only the data reachable by <branch>. Not so effective as --depth=1 but still better than a full clone. It works fine when the repo has many diverged branches.
2.git init;git fetch <url> <tag>
Similarily it fetches only the data reachable by <tag>.
3.Create and use a mirror repo.
git clone <url> --mirror -- /foo/mirror. /foo/mirror is the mirror repo. Suppose your CI system starts multiple instances simultaneously. Clone each via git clone <url> --reference=/foo/mirror -- <instanceN>. In each clone, only the data that can not be found in the mirror repo will be downloaded from the remote repo. You could delete instances to save the space when a job is done. But just keep and update the mirror repo by git fetch regularly based on the update frequency of the remote repo. Once a day in the mid-night, or once a week on Sunday for example.
4.Use git worktree.
Make a clone, keep it and update it first when each CI instance starts. Use git worktree to checkout revisions into different working trees for each instance.

A: I hit the same problem and used this
git clone --shallow-since=<date>
I had to store not only the SHA of my last deployment but the date of my last deployment, but otherwise worked great.


text:
Q: Difference between two python 2d array initialization methods What is the difference between the two arrays created with
array1 = [[0] * 2] * 3

and
array2 = [[0 for _ in range(2)] for _ in range(3)]

I'm asking because they display different behavior (such as, when I increment an integer in array1, it will increment every single value in that column).

A: array1 is making a list of references to a single list while array2 is constructing new lists by value. array1 = [[0] * 2] * 3 is saying "take 3 pointers to the same list (in our case [0,0]) and populate a new list with them." So really its the same list being represented at three different indices, therefore if you change any index of array1 all three values will change, as they are all the same list!
Meanwhile, array2 = [[0 for _ in range(2)] for _ in range(3)] is making three distinct lists all with the same values, in our case [0,0].

A: Check this out: https://riptutorial.com/python/example/12259/list-multiplication-and-common-references
Basically, when you multiply a list (as a commenter noted, they are technically lists in Python, not arrays) by an integer, python will insert the same reference multiple times. That is, when [0]*2 is run, instead of creating an additional zero, it inserts an additional reference to that first zero.
The second version creates additional instances of numbers / lists each time it loops, which is why (even though it's the same expression being evaluated for the content of the list) the references are independent.
Hope this helps!


text:
Q: Association rule lift ratio converging to 0.5, is it not independent? As far as I know, lift is a measure used in association rules to see whether there is a positive association between two items(instances?)
I've done a simple (possibly wrong) simulation with lift measure using 'arules' package in r.
My intention was to make two independent vectors and see if their lift values were close to 1
a <- sample(1:100,100000,replace = T)
b <- sample(1:100,100000,replace = T)

data <- data.frame(a,b)
data$id <- 1:nrow(data)

trans <- melt(data, id = "id") %>% select(-variable)
trans <- as(split(trans[,"value"], trans[,"id"]), "transactions")

lift <- crossTable(trans,measure='lift')
hist(lift)

I thought the result would be distributed around 1, but it was actually distributed around 0.5 and I've done this a lot of times with different values, still getting similar results.
What am I doing wrong here?
Why is the lift value distributed around 0.5?
Please help me out!

A: This is a very good demonstration of one important thing! People often think that association rules would express positive statistical dependencies, since in statistics, word 'association' refers to dependence between discrete variables.  However, traditional association rules per-se (without additional filters) do not select positive associations, you will find also negative associations and independence relations. They merely present frequently co-occurring attributes.
If you would like to find real positive associations, there are two ways. 1) Use the tool you have but add filters and select only rules with lift>1. You may also want to test statistical significance, since some associations deviate from independence only by chance. Note that you need to use minimal possible minimum frequency threshold to find all/the most significant associations (and your program may not be feasible). 2) Use programs that search directly positive dependencies and may also do statistical testing for you. They are more efficient and can work even without any minimum frequency constraints. See e.g. question  Interpreting association rules correctly?


text:
Q: Fragment Replacement Techniques I have three fragments which are bound to Tabs as you swipe from TabA to TabB to TabC and it respectively loads FragA, FragB and FragC using ViewPager(Hope you understand this part). This swipe Tabs works just fine but I have a few fixed buttons attached to the bottom of the layout and when each button is clicked i want to load a new fragment to replace any of the Fragment A, B or C. The replacement works fine but when i return to the replaced/previous Fragment all the UI components on that layout completely disappears and it does not indicate if it has been paused, stopped or destroyed. Heres the Code:
Replacing previous Fragment Code:
        if(actionBar.isShowing())
                {
                    actionBar.hide();
                }
                FragmentManager fms = getSupportFragmentManager();
                FragmentTransaction fts = fms.beginTransaction();
                search s = new search();
                if(getCurrentDisplayFragment() == Type1)
                {
                    setcurrentItem(viewPager.getCurrentItem());
                    Fragment frgs = mAdapter.getItem(viewPager.getCurrentItem());
                    viewPager.removeViewAt(viewPager.getCurrentItem());
                    frgs.setUserVisibleHint(false);

                    Log.i("if say", "Not Responding");
                }

                fts.replace(R.id.hoster, s);
                            fts.addToBackStack("search");
                fts.commit();
                setCurrentDisplayFragment(s,Type2);

The setCurrentDisplayFragment(s,Type2); i built that code to help indicate which fragment is being replaced and what measures to take. S is a Fragment and Type2 is a string
Thus when the back button is pressed i want to return back to any of the Fragments A, B or C  that was previously replaced.
Here is the code:
@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //super.onBackPressed();
        Log.i("event in back","I have been presssed ");
        if(getCurrentDisplayFragment() == Type2)
        {
            actionBar.show();
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            fm.popBackStack();
            ft.remove(getCurrentDisplayFragment(Type2));
            ft.commit();
            viewPager.setCurrentItem(getcurrentItem());
            actionBar.setSelectedNavigationItem(getcurrentItem());
            Fragment frags = mAdapter.getItem(viewPager.getCurrentItem());
            frags.setUserVisibleHint(true);
            setCurrentDisplayFragment(frags, Type1);
        }
        else
        {

        }

    }

Though some variable names and method declaration are not shown but you should get the picture of what am doing because all declarations have been done. its just The Replacement and retaining of their UI states thats giving me a problem.

A: Why are you complicating this so much? If you want to replace any of the fragments in the view pager, then just replace the view pager. It would be a lot easier if you would have a fragment holding the view pager with the tabs and when the bottom buttons are pressed, you just replace the fragment holding the view pager with the new fragment. In this way you won't need to do anything when the back button will be pressed.