text:
Q: How to get data on hourly basis for two days? (Google Analytics Reporting API v4, PHP library) I need to have report metrics on hourly basis in time period passing midnight. For example, starting at 20:00 and ending at 03:00. To do this I set date range where StartDate is 'yesterday' and EndDate is 'today':
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('yesterday');
$dateRange->setEndDate('today');

And to retrieve data on hourly basis I harnessed two segments. One is for the data before midnight (for example, 20:00 to 23:59) and another is for the data after midnight (for example, 00:00 to 03:00). In JSON request the segment looks something like this: sessions::condition::ga:hour<>20_23,ga:hour<>00_03:

https://support.google.com/analytics/answer/7331978?hl=en

Below is my code for the request with some dimension and metric filters (that is, I am requesting amount of page views from users being on a page more than 8 seconds, title of which contains word: 'portfolio'):
// How to create $client you can read in Google Analytics documentation
$analytics = new Google_Service_AnalyticsReporting($client);

// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('yesterday');
$dateRange->setEndDate('today');

// Create the Metrics object.
$metrics = new Google_Service_AnalyticsReporting_Metric();
$metrics->setExpression('ga:pageviews');

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId(VIEW_ID);
$request->setDateRanges([$dateRange]);
$request->setMetrics(array($metrics));

// Create the DimensionFilter.
$dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:pageTitle');
$dimensionFilter->setOperator('PARTIAL');
$dimensionFilter->setExpressions(['portfolio']);

// Create the MetricFilter.
$metricFilter = new Google_Service_AnalyticsReporting_MetricFilter();
$metricFilter->setMetricName('ga:timeOnPage');
$metricFilter->setOperator('GREATER_THAN');
$metricFilter->setComparisonValue('8');

// Create the DimensionFilterClauses
$dimensionFilterClause = new
Google_Service_AnalyticsReporting_DimensionFilterClause();
$dimensionFilterClause->setFilters($dimensionFilter);
$request->setDimensionFilterClauses(array($dimensionFilterClause));

// Create the MetricFilterClauses
$metricFilterClause = new
Google_Service_AnalyticsReporting_MetricFilterClause();
$metricFilterClause->setFilters($metricFilter);
$request->setMetricFilterClauses([$metricFilterClause]);

// Creating multiple segments with function createSegment()
$segments = [];
$segments[] = createSegment('15', '23', 'Before Midnight');
$segments[] = createSegment('00', '10', 'After Midnight');

//Create the hour dimension.
$hour = new Google_Service_AnalyticsReporting_Dimension();
$hour->setName("ga:hour");

// Create the segment dimension.
$segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
$segmentDimensions->setName("ga:segment");

// Set the Segment to the ReportRequest object.
$request->setDimensions(array($hour, $segmentDimensions));
$request->setSegments($segments);

// Get report request
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$report = $analytics->reports->batchGet($body);
$reports = $report->getReports();

function createSegment($min, $max, $name) {

    // Set a segment for hourly time range. For daily time range there is no neen id a segment.
    $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
    $dimensionFilter->setDimensionName('ga:hour');
    $dimensionFilter->setOperator('NUMERIC_BETWEEN');

    // $dimensionFilter->setExpressions($alert->get_expressions());
    $dimensionFilter->setMinComparisonValue($min);
    $dimensionFilter->setMaxComparisonValue($max);

    // Create Segment Filter Clause.
    $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
    $segmentFilterClause->setDimensionFilter($dimensionFilter);

    // Create the Or Filters for Segment.
    $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
    $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

    // Create the Simple Segment.
    $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
    $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

    // Create the Segment Filters.
    $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
    $segmentFilter->setSimpleSegment($simpleSegment);

    // Create the Segment Definition.
    $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
    $segmentDefinition->setSegmentFilters(array($segmentFilter));

    // Create the Dynamic Segment.
    $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
    $dynamicSegment->setSessionSegment($segmentDefinition);
    $dynamicSegment->setName($name);

    // Create the Segments object.
    $segment = new Google_Service_AnalyticsReporting_Segment();
    $segment->setDynamicSegment($dynamicSegment);

    return $segment;
}

You can see response from the request below:
Google_Service_AnalyticsReporting_GetReportsResponse Object
(
[collection_key:protected] => reports
[queryCost] =>
[reportsType:protected] => Google_Service_AnalyticsReporting_Report
[reportsDataType:protected] => array
[resourceQuotasRemainingType:protected] => Google_Service_AnalyticsReporting_ResourceQuotasRemaining
[resourceQuotasRemainingDataType:protected] =>
[internal_gapi_mappings:protected] => Array
    (
    )

[modelData:protected] => Array
    (
        [reports] => Array
            (
                [0] => Google_Service_AnalyticsReporting_Report Object
                    (
                        [columnHeaderType:protected] => Google_Service_AnalyticsReporting_ColumnHeader
                        [columnHeaderDataType:protected] =>
                        [dataType:protected] => Google_Service_AnalyticsReporting_ReportData
                        [dataDataType:protected] =>
                        [nextPageToken] =>
                        [internal_gapi_mappings:protected] => Array
                            (
                            )

                        [modelData:protected] => Array
                            (
                                [columnHeader] => Array
                                    (
                                        [dimensions] => Array
                                            (
                                                [0] => ga:hour
                                                [1] => ga:segment
                                            )

                                        [metricHeader] => Array
                                            (
                                                [metricHeaderEntries] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [name] => ga:pageviews
                                                                [type] => INTEGER
                                                            )

                                                    )

                                            )

                                    )

                                [data] => Google_Service_AnalyticsReporting_ReportData Object
                                    (
                                        [collection_key:protected] => totals
                                        [dataLastRefreshed] =>
                                        [isDataGolden] =>
                                        [maximumsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [maximumsDataType:protected] => array
                                        [minimumsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [minimumsDataType:protected] => array
                                        [rowCount] => 6
                                        [rowsType:protected] => Google_Service_AnalyticsReporting_ReportRow
                                        [rowsDataType:protected] => array
                                        [samplesReadCounts] =>
                                        [samplingSpaceSizes] =>
                                        [totalsType:protected] => Google_Service_AnalyticsReporting_DateRangeValues
                                        [totalsDataType:protected] => array
                                        [internal_gapi_mappings:protected] => Array
                                            (
                                            )

                                        [modelData:protected] => Array
                                            (
                                                [rows] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 00
                                                                        [1] => After Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 15
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                        [1] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 01
                                                                        [1] => After Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 3
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                        [2] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 15
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 3
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                        [3] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 16
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 7
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                        [4] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 19
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 5
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                        [5] => Array
                                                            (
                                                                [dimensions] => Array
                                                                    (
                                                                        [0] => 22
                                                                        [1] => Before Midnight
                                                                    )

                                                                [metrics] => Array
                                                                    (
                                                                        [0] => Array
                                                                            (
                                                                                [values] => Array
                                                                                (
                                                                                [0] => 4
                                                                                )

                                                                            )

                                                                    )

                                                            )

                                                    )

                                                [totals] => Array
                                                    (
                                                        [0] => Google_Service_AnalyticsReporting_DateRangeValues Object
                                                            (
                                                                [collection_key:protected] => values
                                                                [pivotValueRegionsType:protected] => Google_Service_AnalyticsReporting_PivotValueRegion
                                                                [pivotValueRegionsDataType:protected] => array
                                                                [values] => Array
                                                                    (
                                                                        [0] => 37
                                                                    )

                                                                [internal_gapi_mappings:protected] => Array
                                                                    (
                                                                    )

                                                                [modelData:protected] => Array
                                                                    (
                                                                    )

                                                                [processed:protected] => Array
                                                                    (
                                                                    )

                                                            )

                                                    )

                                                [minimums] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [values] => Array
                                                                    (
                                                                        [0] => 3
                                                                    )

                                                            )

                                                    )

                                                [maximums] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                                [values] => Array
                                                                    (
                                                                        [0] => 15
                                                                    )

                                                            )

                                                    )

                                            )

                                        [processed:protected] => Array
                                            (
                                                [totals] => 1
                                            )

                                    )

                            )

                        [processed:protected] => Array
                            (
                                [data] => 1
                            )

                    )

            )

    )

[processed:protected] => Array
    (
        [reports] => 1
    )

)

The data I am interested in is located here: [modelData:protected] => [reports] => [0] => [modelData:protected] => [data] => [modelData:protected] => [rows] => [].
The problem is that, because the segments are applied to every day, I receive data 'before midnight' and 'after midnight' for both days. (I don't mention that the data is also sampled by hours). And there is no sign what day the values are related to.
So, the question is:
Is there a possibility to find what day the data is related to?

A: I finally solved the problem. I decided to analyze live data with different requests.
So it turns out that with one date range, like this:
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate('yesterday');
$dateRange->setEndDate('today');

the metric values are summed. That is, this metric value, which you can see below with [values] key, consists of values for 'today' and 'yesterday' of hour '19':
[4] => Array
  (
    [dimensions] => Array
      (
        [0] => 19
        [1] => Before Midnight
      )
    [metrics] => Array
      (
        [0] => Array
          (
            [values] => Array
              (
                [0] => 5
              )
           )
      )
   )

But if we set two date ranges:
$dateRange[0] = new Google_Service_AnalyticsReporting_DateRange();
$dateRange[0]->setStartDate('yesterday');
$dateRange[0]->setEndDate('yesterday');

$dateRange[1] = new Google_Service_AnalyticsReporting_DateRange();
$dateRange[1]->setStartDate('today');
$dateRange[1]->setEndDate('today');

$request->setDateRanges($dateRange);

one for 'yesterday' and another for 'today' the metric value with [values] key will have two elements of the array, where the first one with [0] index will be related to the date range set the first and the second one with [1] index will be related to the date range set the second:
[4] => Array
  (
    [dimensions] => Array
      (
        [0] => 19
        [1] => Before Midnight
      )
    [metrics] => Array
      (
        [0] => Array
          (
            [values] => Array
              (
                [0] => 2
                [1] => 3
              )
           )
      )
   )

So we can pick all values with [0] index where [dimensions] is 'Before midnight', and all values with [1] index where [dimensions] is 'After midnight', and sum them together. And the sum will be all pages view for the time frame starting at 20:00 and ending at 03:00. Voila!
Hope this my explanation will help someone looking for a solution.


text:
Q: How to manually acknoweldge offset after multiple commits I am working on a Spring kafka application.  I am sending a batch of records to it.  I only want to acknowledge the offset after all of the records have been sent rather than after each record.
I've tried the code below (copied from here https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/index.html#_usage_examples) but this acknowledges the offset after each record rather than the batch of records.  I set the following property first
spring.cloud.stream.kafka.bindings.input.consumer.autoCommitOffset=false
@SpringBootApplication
@EnableBinding(Sink.class)
public class ManuallyAcknowdledgingConsumer {

 public static void main(String[] args) {
     SpringApplication.run(ManuallyAcknowdledgingConsumer.class, args);
 }

 @StreamListener(Sink.INPUT)
 public void process(Message<?> message) {
     Acknowledgment acknowledgment =     message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
     if (acknowledgment != null) {
         System.out.println("Acknowledgment provided");
         acknowledgment.acknowledge();
     }
 }
}

How would I go about manually acknowledging after the batch of records?

A: As you can see here you can receive list of messages so your example would look like this:
@StreamListener(Sink.INPUT)
 public void process(List<Message<?>> messages) {
     Acknowledgment acknowledgment =     message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
     if (acknowledgment != null) {
         System.out.println("Acknowledgment provided");
         acknowledgment.acknowledge();
     }
 }

And after you are done with all records you can call acknowledgment.acknowledge();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve cookies from browser in stand alone app I want to access the cookies from my browser (for example firefox) IN my java stand alone app. Can I access the cookie database or is that generally a bad approach? Is there an API that might help be solving this problem?

A: The usual way how these kind of apps are implemented is by sending user to the 'connecting page' which then with javascript calls your own apps URI, such as myapp://auth?auth_code=XXXXXXXXXXXXXXX_XXXXXXXXXXXXXX_XXXXXXXXXXX
This requires you to make your Java application handle URIs and implement the cookie passing via URI on the page you're using, here's information how to perform this in Windows, I am not sure which platforms you're targeting, but I am sure there's also a general fit library that handles all the cases.
I didn't find any general resources targeting Java, but this is a much solved problem and there's various implementations.

A: Cookies are stored by the browser in it's own, proprietary form, i.e. each browser can store it in a different way. The format could even change between releases of the same browser. There are no public APIs available to ask a browser for it's cookie-db. Therefore it doesn't make sense to try to build a generic solution which tries to access a browser's cookie db.
If you want to create an application just for yourself and want to use the firefox cookies db, then this is not a problem and should work. Firefox is open source and you can see how it stores it's cookies in a its db. The more recent versions use a sqlite db, and the file is stored here https://superuser.com/questions/387372/where-does-firefox-keep-cookies


text:
Q: How to Deallocate memory from an object in Jupyter Notebook I am trying to figure out how to release the space occupied by a python object while working on jupyter notebooks.
In the specific scenario, i am working on multiple large dataframes and once I have finished doing some computations, i would like to load up a new dataframe.
However this always causes a memory error and my system starts freezing up.
So i figured I will try deleting the python object.
Things i have tried so far :
1. Using del and invoking garbage collector
del pyobject
import gc
gc.collect()

*Using ipython magic commands
%reset_selective -f pyobject
Both these approaches fail to actually release the memory. Looking at the htop command shows me that still 20GB of my RAM is being used up by the jupyter notebook. They memory is only deallocated when i restart the kernel (but then i end up losing all the other variables i require for my next stage of data analysis)

A: Make sure that no other references exist to your data. Are there no other views based on that array? You can get the objects that hold a reference to something using get_referrers
If there are any views you should promote those to copies.
In particular ipython tends to keep references to previous evaluations in variables named _, _1, _23 etc. %reset_selective should clear these though.


text:
Q: Select listbox item using the keyboard Could anyone please tell me what i should do programmatically to be able to select an item in a listbox using the keyboard when there are multiple items starting with the same character/s.
For eg,

*

*One

*Two

*Three

*Once

*Orange

If i want to get the focus on "Once" by typing o,n,c what should i do? Instead of jumping from one item to the other as opposed to the default behaviour.

A: Add a KeyPress event handler to the ListBox and track the keys that are pressed. Then compare the complete value that already has been typed to the values from the items in the ListBox. If there's a match, select the item.
Edit:
Here's a solution that I created that works. I also measure the time between keypresses. This way, if the time between to keypresses is more than 1.5 seconds, the search-string is emptied and re-filled with the last search-character. After that it's like I said: find a match and if there's a match, select that item. The two private fields are class-level fields to keep track of the time of the last keypress and the string is to store the search-string.
private DateTime _lastKeyPress;
private string _searchString;

private void ListBox1KeyPress(object sender, KeyPressEventArgs e)
{
    var newDate = DateTime.Now;
    var diff = newDate - _lastKeyPress;

    if (diff.TotalSeconds >= 1.5)
        _searchString = string.Empty;
    _searchString += e.KeyChar;

    for (var i = 0; i < listBox1.Items.Count; i++)
    {
        var item = listBox1.Items[i].ToString();
        if (item.ToLower().StartsWith(_searchString))
        {
            listBox1.SelectedItem = item;
            break;
        }
    }
    _lastKeyPress = newDate;
    e.Handled = true; //REALLY IMPORTANT TO HAVE THIS
}

And here's an example using LinQ to get a match for the searchitem:
private void ListBox1KeyPress(object sender, KeyPressEventArgs e)
{
    var newDate = DateTime.Now;
    var diff = newDate - _lastKeyPress;
    if (diff.TotalSeconds >= 1.5)
        _searchString = string.Empty;
    _searchString += e.KeyChar;

    var found = listBox1.Items.Cast<object>().Select(t => t.ToString()).Where(item => item.ToLower().StartsWith(_searchString)).FirstOrDefault();
    if(!String.IsNullOrEmpty(found))
        listBox1.SelectedItem = found;

    _lastKeyPress = newDate;
    e.Handled = true;
}

Hope this helps! ;)
Edit2:
I don't know if you noticed the comment with the imortance of the e.Handled. By default if you press a key in the ListBox, the control will select the first-found item with that key-character. But it has not the functionality that my code has. So, if you remote the e.Handled line, the code will work but the control will also process the keypress and you don't want that: items will not be correctly selected!

A: You want to use the LBS_SORT list box style.  This style cannot be applied after the control has been created and so to add this style you need to override the CreateParams property.  Create a class (lets call it SortedListBox) which derives from ListBox and override this property like so
public class MyListBox : ListBox
{
    protected override CreateParams CreateParams
    {
        get
        {
            var returnValue = base.CreateParams;
            returnValue.Style |= 0x2; // Add LBS_SORT
            returnValue.Style ^= 128; // Remove LBS_USETABSTOPS (optional)
            return returnValue;
        }
    }
}

This list box should now both sort the items in your list & support incremental searching (you can't turn the sorting off I'm afraid, if you need to control the sort order then you need to do the incremental searching yourself, as Abbas has suggested)
Update: If you additionally remove the LBS_USETABSTOPS style you even get an edit carret showing what character the incremental search is currently matching on

A: I just modified Abbas code for my case. This is my desktop program and using in one of the form which has ListBox control. This is working great for me. Thanks to Abbas
    private DateTime _lastKeyPress;
    private string _searchString;
    private void lstEmployer_KeyPress(object sender, KeyPressEventArgs e)
    {
        var newDate = DateTime.Now;
        var diff = newDate - _lastKeyPress;

        if (diff.TotalSeconds >= 2)
            _searchString = string.Empty;
        _searchString += e.KeyChar;

        lstEmployer.SelectedIndex = lstEmployer.FindString(_searchString);

        _lastKeyPress = newDate;
        e.Handled = true; //REALLY IMPORTANT TO HAVE THIS
    }


text:
Q: install4j - restrict access to installation folder in Windows We are using install4j v10.0.1.  I'm trying to restrict access to all of the files/folders within the Windows installation directory via use of a "Change Windows file rights" action.  I'm attempting to revoke all access to the installation directory from the "Users" trustee/group, but the Users group still seems to be inheriting "Read & Execute" permissions from a higher-level folder (e.g., C:\Program Files).  I want the Administrators group to have full access to the files/folders within the installation directory, but I don't want the Users group to have any access.  How can I meet this requirement?

A: In the "Change Windows file rights" action, setting the "Access mode" property to "Revoke access" deletes an existing ACE with the same specification.
In your case, you have to use "Deny access" instead.

A: The solution I came up with was to first use "Change Windows file rights" actions to Set and Revoke privileges to the installation directory as per my requirements.  Then I create a batch script which expects one parameter (the path to the installation directory) and utilizes the "icacls" command available in Windows to remove any privileges the installation directory might inherit from a parent folder.  A "Run executable or batch file" action is used to run the batch script. The contents of the script are as follows:
@echo off
set "install_dir=%~1"
icacls "%install_dir%" /inheritancelevel:r


text:
Q: How to use binary search on unsorted array with key and value in java? import java.util.HashMap;
import java.util.Map;

public class BinarySearchUnsorted {

    int binary(Map<Integer, Integer> map, int start, int end, int x) {
        if (end >= start) {
            int test=start+(end-start);
            int mid = test / 2;
            System.out.println(mid);
            System.out.println(map.get(mid));
            if (map.get(mid) == x) {
                return map.get(mid);
            }
            if (map.get(mid) > x) {
                return binary(map, start, mid - 1, x);
            }
            return binary(map, mid + 1, end, x);
        }

        return -1;
    }

    public static void main(String[] args) {
        int x = 3;
        int[] arr = { 2, 4, 3, 8 };
        int length = arr.length;

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < length; i++) {
            map.put(arr[i],i );

        }
        BinarySearchUnsorted ob = new BinarySearchUnsorted();
        int result = ob.binary(map, 0, length - 1, x);
        if (result == -1) {
            System.out.println("Element not present");
        }
        else {
            System.out.println("Element found at index " + result);
        }
    }
}

I have given array of integers added unsorted and integer that I want to find on which position it is. I want to use binary search which use only sorted arrays so I sort the numbers from the array and save their first position. Every help will be good.
Thanks in advance!

A: Here is the answer
public static class MyEntry {
        int key;
        int value;

        public MyEntry(Integer k, Integer v) {
            key = k;
            value = v;
        }

        public String toString() {
            return ("(" + key + "," + value + ") ");
        }
    }

    public static int BinSearch(MyEntry[] arr,int low, int high, int k) {
        int  mid;

        mid = (high + low) / 2;

        if (high >= low) {

            if (arr[mid].key == k) {
                return (mid);
            }
            if (arr[mid].key > k) {
                return BinSearch(arr, low, mid - 1, k);
            }
            return BinSearch(arr, mid + 1, high, k);
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = { 2, 4, 3, 8 };
        int len = arr.length;
        System.out.println(len + "dulj");
        MyEntry[] entry = new MyEntry[len];

        for (int i = 0; i < len; i++) {
            entry[i] = new MyEntry(arr[i], i);
        }

        for (int i = 0; i < entry.length; i++)
            System.out.print(i + ":" + entry[i]);
        System.out.println();

        int result = BinSearch(entry,0, len-1, 8);
        System.out.println(result);
    }


text:
Q: Downloading an .ico file from DuckDuckGo I'm currently using the DuckDuckGo icon utility to fetch the favicon's for certain webpages, although in order to fetch an icon it requires you to add ".ico" at the very end of the request, for example: https://icons.duckduckgo.com/ip2/www.google.com.ico
So, I'm using a WebClient to download the favicon, although; it doesn't seem to be downloading it completely since every time I open the file it appears corrupted and throws an error stating that "the file header can't be read".
I've tried the following so far (my WebClient is called client, the icon to set is called favicon and the path to the icon file is called favicon_path):
Uri favicon_url = new Uri(
    "https://icons.duckduckgo.com/ip2/" + gBrowser.Url.Host.ToString() + ".ico");
client.DownloadFile(@favicon_url, favicon_path);
favicon = new Icon(favicon_path);

and
Uri favicon_url = new Uri("https://icons.duckduckgo.com/ip2/"
    + gBrowser.Url.Host.ToString().Replace(".", "%2E") + ".ico");
client.DownloadFile(@favicon_url, favicon_path);
favicon = new Icon(favicon_path);

I'm guessing that the multiple periods ('.') in the favicon_url are responsible, so my question is: How can I download the favicon using a WebClient (or something similar) if it has multiple periods in its name? Or if not the periods, why can't I read the file downloaded from DuckDuckGo?

A: Okay, here's what you need to do (after the call to DownloadFile()):
using (Stream inputStream = File.OpenRead(favicon_path))
using (Stream gzipStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
    MemoryStream copyStream = new MemoryStream();

    gzipStream.CopyTo(copyStream);
    copyStream.Position = 0;

    favicon = new Icon(copyStream);
}

I noticed that the downloaded file was much smaller than the actual .ico file. That suggested the data was being compressed somehow. Gzip is the defacto cross-platform stream-compression format, so I made a guess and tried decompressing the data as if it were compressed with gzip. And sure enough, it was.
Note above that you need to decompress the data into an intermediate buffer first (I used a MemoryStream object). The Icon constructor will try to seek the stream, which is not supported on a GzipStream object (for obvious reasons). So, you need to decompress the data into a Stream object that is seekable.
Note also that there is an alternative solution using HttpWebRequest, which does support decompression during download. This is instead of using WebClient.DownloadFile(), not after as in the other example above.
You still have to copy to an intermediate buffer first (again, because Icon wants to seek the source stream, which is not seekable). But this approach allows the data to be read straight from the remote server into an Icon object, without requiring the intermediate file:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(favicon_url);

// You can also include `DecompressionMethods.Deflate` here, for a more general solution
request.AutomaticDecompression = DecompressionMethods.GZip;

MemoryStream copyStream = new MemoryStream();

request.GetResponse().GetResponseStream().CopyTo(copyStream);
copyStream.Position = 0;
favicon = new Icon(copyStream);


text:
Q: Over-use of aggregation in a class diagram? I tried to solve this problem:

Draw a UML class diagram of an Object-Oriented model for a car rental company that keeps track of cars, renters and renters renting cars. Create a UML class diagram to represent this information. Showing the correct classes and relationships is enough. Do not add attributes or methods to the classes.

I was thinking the that renters and car company should be association, and  car company and renters renting cars should be composition. However the proposed solution (simplified here), did not match my expectations:

The solution shows all the relationships as aggregation. Can someone help me understand why they all are aggregation and not association and  composition as I thought?

A: Comments on your own analyse

I was thinking the that renters and car company should be association

Yes, this makes sense: a renter may be a customer of a car company, and reciprocally, a car company could serve several renters.  Renters are not owned by a car company and reciprocally.

and car company and renters renting cars should be composition.

No: composition means exclusive ownership, and that the composed objects would in principle not survive the composite.  But here, if a car company is destroyed, the renters may stay and simply go to other car companies. So no composition.
Published solution's aggregation vs. your associations

solution shows all the relationships are aggregation.

The relations that you describe seem to correspond to UML associations. The fact that the published solution uses aggregation is not necessaritly false, but it's not recommended:

*

*From the point of view of the UML specifications, the semantics are not clearly defined. So there's no real benefit to use aggregation in a design model. See UML 2.5 p.110:

Sometimes a Property is used to model circumstances in which one instance is used to group together a set of instances; this is called aggregation. (...) Precise semantics of shared aggregation varies by application area and modeler.

*From the point of view of the designer, aggregation is a purely conceptual notation that does not fundamentally change the meaning of the diagram.  For this reason, James Rumbaugh, a founding father of UML, once called aggregation a "modelling placebo".  I found back the quote in the book "Unified Modeling Language Reference Manual", chapter 14:

Keep in mind that aggregation is association. Aggregation conveys the thought that the aggregate is inherently the sum of its parts. In fact, the only real semantics that it adds to association is the constraint that chains of aggregate links may not form cycle (...)  In spite of the few semantics attached to aggregation, everybody thinks it is necessary (for different reasons). Think of it as a modeling placebo.

*On the implementation side, object composition is one of the basics of OOP.  Some practitioners and academics tend to represent object composition with an UML aggregation to show that the the aggregated element is a part of a whole aggregate (the UML composition would be too restrictive, especially for languages in which classes have reference semantics, as Java or C#). This argument is however discussable because the design should not be driven by the implementation techniques.  Moreover, modern UML's dot notation expresses those semantics much more accurately.

*Some really discussable choices are made on the solution diagram: If we take the example of the Renter and the Rental, from a design point of a renter has some rental contracts and would probably need to find them back. After all, the rentals are a part the renter business role.  Conversely, from a contractual point of view, the renter is a party of the contract.  So one could defend an aggregation in both directions, but you cannot have an aggregation on both sides at the same time. The arbitrary choice to show only one side of the truth could be confusing. And adding two aggregations in the opposite direction would not appropriately show that in fact it's the same relation. Another argument to avoid aggregation whenever possible.
Conclusion: since there's no objective criteria to decide when to use aggregation, and in view of absence of other significant impact of using aggregation or association, just keep it simple:  ignore aggregation when you read it in a diagram, and yourself, avoid using it in your own diagram and prefer association instead.


text:
Q: Extend standard page with a picklist that contains data from an external system The requirement is to extend the Campaign page with a custom picklist field that shows data (select options) stored in a 3rd party system (accessible trough a rest endpoint).
I know there is the possibility to include a custom visualforce page in the page layout. But there are some limitations like the inlined visualforce page can't be used in the edit mode of the standard page.
This is a bit cumbersome and will also end up in an unfamiliar editing experience for the user.
What is the best/natural way to accomplish this?
Here are some (maybe strange) thoughts/hacks that i can image to get this working:

*

*Only override the getter method for the picklist options value from
the standard controller (combination of controller extension +
apex:detail page)?

*Add some custom java script that override the options in html?

This is the first time i use visualforce, so any recommendations and pointers to right direction are really welcome.

A: *

*is not an option as far as I know. You can't override that

*can be done, e.g. with some parts of this code https://developer.salesforce.com/forums?id=906F00000008kzBIAQ but then use your rest service as the data source. But it is seen as a hack, obviously, and requires you to include the Messages&Alerts on each page.

*The solution prescribed by SF will be to create a VF page from scratch to override the standard Edit page. You will lose the standard page layout assignment, though.
Ideally, there should be an apex:detail component that allows edit mode, so you can put your javascript there, but unfortunately that's not supported (vote here: https://success.salesforce.com/ideaview?id=08730000000BrQtAAK)


text:
Q: Error during only Debug of program. (In dll of Oculus HMD) I am using Oculus World Demo.
I can start it manually, but I have an internal error during "Debug"/"Release".
How to debug such errors?
Where can I see the command which runs the program.
Again:
It runs normally when I click on MyGreatestApp.exe in folder /Debug/.
It has an internal error of used DLL, when I start it in VS2103. (something like -3003 or fffff447)
P.S. I find it strange that I can debug in "Release" mode.(I mean step-by-step program execution.) Is it normal? Maybe I do it wrong? Thanks!

A: It could be useful if you say in what line the program crash.
Anyway you can use the Oculus Debug Tool: https://developer3.oculus.com/documentation/pcsdk/latest/concepts/dg-debug-tool/
To record logs and see at the Runtime side what is happening.
This is error -3003, check why your application is not connecting to Oculus. I should check if I running the 64 bit of my application or something like that.
ovrError_ServiceConnection          = -3003,   ///< Couldn't connect to the OVR Service.

Hope it helps


text:
Q: Dynamically hide table in JasperReports I have a Report, where i list the invoices & details between a particular date range. I have a table for Charges and i have to display it only for those invoices that have charges details.Otherwise it should not be displayed and the space has to be compacted.
I have tried the solutions given in this thread
I tried applying the "Print-when" condition both on the table and the band, but it is not working for me.
There is a huge space between records, that dont have the charges details.
Should i change it to a subreport instead?

A: I am not sure whether I have understood your question properly. If you do not want to display the records which does not have data for Charges, then I hope you can achieve this simply using a condition in your query to fetch the data.
For example where Charges != null condition in your table query. This should filter the invoices which does not have data for Charges.

A: I don't see why the print when expression on the band would not work.
Example: Print When Expression $F{CHARGES_FIELD_VARIABLE}!=null
This should only display the band if there is a value for charges.
If this does not work could you provide us with your xml?


text:
Q: Expand set of combinations in Python? I'm not even sure how to explain what I'm trying to do in words, so I shall use examples:
I want to take a set of options in a string, like this (the format can change if it's easier that way):
is (my|the) car (locked|unlocked) (now)?

And have it spit out the following list of strings:
is my car locked
is the car locked
is my car unlocked
is the car unlocked
is my car locked now
is the car locked now
is my car unlocked now
is the car unlocked now

I need to be able to do this for a an Alexa application since it doesn't accept regex for natural language processing (WHY!?).
Thanks in advance.

A: What you probably want is itertools.product(). For example, you might use it like this:
import itertools

# set up options
opt1 = ["my", "the"]
opt2 = ["locked", "unlocked"]
opt3 = [" now", ""] # You'll have to use an empty string to make something optional

# The sentence you want to template
s = "is {} car {}{}?"

# Do all combinations
for combination in itertools.product(opt1, opt2, opt3):
    print(s.format(*combination))

This prints:
is my car locked now?
is my car locked?
is my car unlocked now?
is my car unlocked?
is the car locked now?
is the car locked?
is the car unlocked now?
is the car unlocked?

A: You can use Spintax.

Spintax (also known as spin syntax) is a way to create random strings that have the same or similar meaning.
Simple example:
"{Hey|Hello|Hi} this is {spin syntax|spintax}{.|!|}" Can produce:
Hey this is spintax.
  Hi this is spin syntax
  Hello this is spintax
  Hi this is spintax!


text:
Q: Jmeter is not able to run as a background process while ssh I wrote a shell script , inside shell script I do ssh to jmeter master and execute jmeter command in background using nohup and "&" . Its throwing error :
An error occurred: Unknown arg: &
ssh $masterIP << EOF
nohup jmeter -n -t $JMETERWS/jmx/$jmxfilename -R $slavePrivateIP -GDISCOVERYURL=$domain -GREGION=$region -GDISCOVERYENV=$env -GSERVICE=$service -GRUNID=$runId -GTESTID=$testId -Gnumthread=$numthread -Gtime=$rampuptime -GSESSIONTIME=$sessiontime  \&
EOF

A: The issue seems to be related to your escaping of &:

\&

Try dropping the escape


text:
Q: PHPWord returns blank document [Laravel] I am trying to insert some data to the template however I keep getting a blank document with no data or template structure. It is just blank.
Here is the code:
    $path = public_path('documents/mailing/');

    $source = public_path('documents/default/main.docx');

    $sales = Sale::where('status', '=', '1')
        ->where('special', '!=', 1)
        ->orderBy('updated_at', 'asc')
        ->get();

    if( !File::exists($path) )
    {
        File::makeDirectory($path, 0775, true);
    }

        $phpWord = new \PhpOffice\PhpWord\PhpWord();

        $template = $phpWord->loadTemplate($source);

        foreach ($sales as $sale)
        {
            $template->addPage();
            $template->setValue('saleRef', htmlspecialchars($sale->SaleID));

        }

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $file = $path.'mailing_'.date("d-m-Y_H-i-s"). '.docx';
        $objWriter->save($file);

I have also tried saving the template like so:
        $file = $path.'mailing_'.date("d-m-Y_H-i-s"). '.docx';
        $template->saveAs($file);

But when I do that I am getting a corrupted document in return with some XML errors which cannot be open in MS Word. What I am doing wrong?


text:
Q: Cannot convert value of type 'DataResponse' to expected argument type 'Data' I'm making a simple post request to a site which sends back JSON that looks something like this:
{
    Account = "blah blah";
    Password = "blah blah";
}

This is the request.
@IBAction func submitButtonClicked(_ sender: Any){
                AF.request("https://companywebsite.com", method: .post, parameters: parameters, encoding:JSONEncoding.default)
                .responseJSON{ response in
                    let json = try? JSON(data: response)
                }
}

I'm getting the following compilation error:
Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

I'm using Alamofire to send the request and SwiftyJSON to parse it. I've never used Swift or either library before so I'm really struggling to see what I need to do to fix this.
I want to pull the account and password out to be stored in separate variables. I tried following other tutorials but I've had no success. If someone could help me out I'd really appreciate it.

A: You need responseData instead of responseJSON
AF.request("https://companywebsite.com", method: .post, parameters: parameters, encoding:JSONEncoding.default)
            .responseData { response in
   guard let data = response.data else { return }
   let json = try? JSON(data:data)
   if let acc = json?["Account"].string {
     print(acc)
   }
   if let pass = json?["Password"].string {
     print(pass)
   }
}

Other variant
Alamofire.request("https://companywebsite.com", method: .post, parameters: [:], encoding:JSONEncoding.default)
    .responseJSON { response in
    let json = try? JSON(response.result.value!)
}


text:
Q: How to write following code with Conditional(Ternary) Operator? I am just playing with my code. The code in if else block can be written with conditional operator (? :).
how to write following code with Conditional Operator.
  import com.itextpdf.text.Document;

public class TEst {
    public static void main(String[] args) {
        Document doc=null;
        try{
         doc=new Document();
        //some operation.
        }catch(Exception e){

        }finally{
            doc!=null? doc.close():"";

            //if(doc!=null){
            //  doc.close();
            //}
        }
    }

Eclipse suggestion :
Multiple markers at this line

*

*Type mismatch: cannot convert from null to boolean

*Syntax error on token "!=", invalid AssignmentOperator

A: You could use the ternary operator here (using a dummy boolean and not using it again):
boolean dummy = doc != null ? doc.close() : false;

But i would highly recommend not using this kind of code. If you think a "1-liner" might be readable here consider doing something like:
if (doc!=null) doc.close();

EDIT:
Explanation why not to use this kind of code:
You would create a boolean which is never used again without gaining anything.

*

*The ternary operator is not faster than an if condition

*The code becomes unreadable in this case

*the boolean dummy still contains a boolean value if doc was null

A: No. Ternary operator can't be used this way.
//if(doc!=null){
    //  doc.close();
    //}

If you closely look the code commented, there is no else part at all. You just have only if and ternary operator needs an else for sure. Hence not possible.


text:
Q: Is there any equivalent of `pwd -L` in perl? Is there an equivalent of shell's "pwd -L" in perl?
I want the current working directory with symlinks unresolved?
My current working directory is "/path1/dir1/dir2/dir3", and here dir1 is symlink to test1/test2. I want current working directory to be "/path1/dir1/dir2/dir3" via perl script. What I am getting is /path1/test1/test2/dir2/dir3.
How can I get the current working directory to be the path with no symlinks resolved? In other words, I would want to implement shell's pwd -L.

A: use the perl backtick operator to run the pwd -L command on your system and capture the output into a variable, this works on my system:
 perl -e 'chomp( my $pwdl = `pwd -L` ); print "$pwdl\n";'

A: An attempt to replicate the behavior of bash's pwd builtin using just perl (In particular, with the aid of the Path::Tiny and core Cwd modules):
First, from help pwd in a bash shell:

*

*-L        print the value of $PWD if it names the current working directory

*-P        print the physical directory, without any symbolic links

(The GNU coreutils version of pwd(1) also reads the PWD environment variable for its implementation of -L, which is why running it with qx// works even though it doesn't have access to the shell's internal variables keeping track of the working directory and path taken to it)
$ pwd -P # First, play with absolute path with symlinks resolved
/.../test1/test2/dir2/dir3
$ perl -MCwd -E 'say getcwd'
/.../test1/test2/dir2/dir3
$ perl -MPath::Tiny -E 'say Path::Tiny->cwd'
/.../test1/test2/dir2/dir3
$ pwd -L # Using $PWD to preserve the symlinks
/.../dir1/dir2/dir3
$ /bin/pwd -L
/.../dir1/dir2/dir3
$ PWD=/foo/bar /bin/pwd -L # Try to fake it out
/.../test1/test2/dir2/dir3
$ perl -MPath::Tiny -E 'my $pwd = path($ENV{PWD}); say $pwd if $pwd->realpath eq Path::Tiny->cwd'
/.../dir1/dir2/dir3

As a function (With some added checks so it can handle a missing $PWD environment var or one that points to a non-existent path):
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use Path::Tiny;

sub is_same_file ($$) {
    my $s1 = $_[0]->stat;
    my $s2 = $_[1]->stat;
    return $s1->dev == $s2->dev && $s1->ino == $s2->ino;
}

sub get_working_dir () {
    my $cwd = Path::Tiny->cwd;
    # $ENV{PWD} must exist and be non-empty
    if (exists $ENV{PWD} && $ENV{PWD} ne "") {
        my $pwd = path($ENV{PWD});
        # And must point to a directory that is the same filesystem entity as cwd
        return $pwd->is_dir && is_same_file($pwd, $cwd) ? $pwd : $cwd;
    } else {
        return $cwd;
    }
}

say get_working_dir;


text:
Q: How can I execute a C program on Qemu riscv and observe the output? What should be the best approach to run a C code in Qemu riscv and observe the output? I installed Qemu riscv following this link.What should I do now?
https://risc-v-getting-started-guide.readthedocs.io/en/latest/linux-qemu.html

A: You probably want to use the static user mode version of Qemu for most applications.
Then make sure to compile for RISC-V with the -static flag, and call qemu-riscv64-static [executable].
I highly recommend this, the system mode is a massive pain to handle if you don't need it
(have fun debugging the UART).

A: You can use libriscv to run RISC-V programs: https://github.com/fwsGonzo/libriscv
Inside the emulator folder there are 2 ways to build the emulator. build.sh produces emulators that run programs with no instruction listing. debug.sh produces debugging variant that shows the state of registers and instructions all the way through the program.
Building Qemu from sources is complete overkill.


text:
Q: Login Validation - Won't Connect To DB While Connecting In Other Scripts Works Fine I'm having several issues with my login coding, the biggest one being that I get a database connection error every time I run it. I don't know why because everything worked fine the first time I tried it out and connecting to the database any other time works no problem. Left it alone to work on some other stuff and now it doesn't seem to want to work all of a sudden.
Validation Scripts
I did not write these, I found them on w3schools.in and they were the only scripts the even worked out of the 20 or so I tried. Well, to begin with. The only thing I changed was the error messages and adding the $returnurl session variable but that's for a future question.
//LOGIN VALIDATION

if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) or strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') or empty($_POST)) {
    exit("Unauthorized Access");
}

require 'config.php';
require 'functions.php';

if (!empty($_POST) && $_POST['Action']=='login_form') {
    $Return=array('result'=>array(), 'error'=>'');

    $email=safe_input($db, $_POST['Email']);
    $password=safe_input($db, $_POST['Password']);
    $returnUrl=$_SESSION['Return_Url']=$_POST['Return_Url'];

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $Return['error']="Please enter your email/username.";
    } elseif ($password==='') {
        $Return['error']="Please enter your password.";
    }
    if ($Return['error']!='') {
        output($Return);
    }
    $result=mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' AND password='".md5($password)."' LIMIT 1");
    if (mysqli_num_rows($result)==1) {
        $row=mysqli_fetch_assoc($result);
        $Return['result']=$_SESSION['UserData']=array('id'=>$row['id']);
    } else {
        $Return['error']='Email/Password Is Invalid';
    }
    output($Return);
}

//REGISTRATION VALIDATION

if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) or strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') or empty($_POST)) {
    exit("Unauthorized Access");
}
require 'config.php';
require 'functions.php';

if(!empty($_POST) && $_POST['Action']=='registration_form') {
    $Return=array('result'=>array(), 'error'=>'');

    $name=safe_input($db, $_POST['Name']);
    $email=safe_input($db, $_POST['Email']);
    $password=safe_input($db, $_POST['Password']);
    $returnUrl=$_SESSION['Return_Url']=$_POST['Return_Url'];

    if ($name==='') {
        $Return['error']="Please enter your name.";
    } elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $Return['error']="Please enter your email address.";
    } elseif($password==='') {
        $Return['error']="Please enter a password.";
    }
    if($Return['error']!='') {
        output($Return);
    }

    $result=mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' LIMIT 1");
    if(mysqli_num_rows($result)==1) {
        $Return['error']='That email is already registered, please Login';
    } else {
        mysqli_query($db, "INSERT INTO tbl (user_GUID, email, password, entry_date) values(MD5(UUID()), '$email', '".md5($password)."' ,NOW() )");
        $id=mysqli_insert_id($db);
        mysqli_query($db, "INSERT INTO `tbl` (id,name) VALUES('$user_id','$name')");
        $Return['result']=$_SESSION['UserData']=array('id'=>$id);
    }
    output($Return);
}

Included Scripts
//config.php

session_start();
/*Connection vars here*/
$db=mysqli_connect($host, $user, $pass, $dbase);

//functions.php

function safe_input($db, $data) {
  return htmlspecialchars(mysqli_real_escape_string($db, trim($data)));
}
function output($Return=array()) {
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    exit(json_encode($Return));
}

Error Received
mysqli_connect(): (28000/1045): Access denied for user...

Yes, I know it's been a common issue and the error speaks for itself, but I don't understand why I would get this error when connecting with the same details in a different script has no problem.
As a side note, if someone could tell me what the deal is with that line at the top of both scripts. I looked around the web and found that it deals with ajax but I'm not submitting with ajax (for now, at least). Do I need that line or is it harmless and can stay for when I do use ajax?
As stated, I didn't write this code, only the login/registration forms, so I'm not entirely sure of how it works. I understand the mechanics like testing the data and checking for/adding it in the database. Anything, you can help me with would be greatly appreciated.


text:
Q: Differences between Google Play Installed Apps "UPDATES" list vs "MANUAL UPDATES" list? When I launch Google Play on the phone and I enter the "My Apps" section, I can see all my installed apps spread into three lists:

*

*Updates

*Manual Updates

*Up To Date

I published my app to Google Play and whenever I launch a new version, my app appears in the Manual Updates list. I want my app to appear in the Updates list and not Manual Updates.
How can I achieve that? What is the difference between Updates and Manual Updates on that list?

A: Your app will appear in the Updates list unless you change the permissions that you're requesting. If you add, say, the CAMERA permission at some point, then your app will appear in the Manual Updates list until your user accepts the new permission.


text:
Q: Keras and tensorflow conflict when transfer learning on MobileNetV3 I'm trying to do transfer learning with MobileNetV3 in Keras but I'm having some issues.
from keras.models import Model
from keras.layers import GlobalMaxPooling2D, Dense, Dropout
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from tensorflow.keras.applications import MobileNetV3Small
import numpy as np
from tqdm import tqdm
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

pretrained_model = MobileNetV3Small(input_shape=(224,224,3),
                                    weights="imagenet",
                                    include_top=False)

# freeze all layers except the last one
for layer in pretrained_model.layers:
    layer.trainable = False
pretrained_model.layers[-1].trainable = True

# combine the model with some extra layers for classification
last_output = pretrained_model.layers[-1].output
x = GlobalMaxPooling2D()(last_output)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(pretrained_model.input, x)

I get this error when I try to make the Dense layer:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

but it's fixed by adding the following code snippet:
from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

When I include the code fix above, I get this error when I call model.fit():
FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Could not find variable Conv_1_2/kernel. This could mean that the variable has been deleted. In TF1, it can also mean the variable is uninitialized. Debug info: container=localhost, status=Not found: Resource localhost/Conv_1_2/kernel/N10tensorflow3VarE does not exist.
     [[{{node Conv_1_2/Conv2D/ReadVariableOp}}]]
     [[_arg_dense_12_target_0_1/_100]]
  (1) Failed precondition: Could not find variable Conv_1_2/kernel. This could mean that the variable has been deleted. In TF1, it can also mean the variable is uninitialized. Debug info: container=localhost, status=Not found: Resource localhost/Conv_1_2/kernel/N10tensorflow3VarE does not exist.
     [[{{node Conv_1_2/Conv2D/ReadVariableOp}}]]
0 successful operations.
0 derived errors ignored.

How can I fix these issues and train the model?

A: From comments

Don't mix tf.keras and  standalone keras. They are not compatible. Only use one of them (paraphrased from Frightera)

Working code as shown below
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalMaxPooling2D, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.applications import MobileNetV3Small
import numpy as np
from tqdm import tqdm
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

pretrained_model = MobileNetV3Small(input_shape=(224,224,3),
                                    weights="imagenet",
                                    include_top=False)

# freeze all layers except the last one
for layer in pretrained_model.layers:
    layer.trainable = False
pretrained_model.layers[-1].trainable = True

# combine the model with some extra layers for classification
last_output = pretrained_model.layers[-1].output
x = GlobalMaxPooling2D()(last_output)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(pretrained_model.input, x)


text:
Q: redirect to a action that expects value in other controller I have a controller StepOfIdea,and this controller has a action like this :
 StepOfIdeaRepository objStepOfIdearepository=new StepOfIdeaRepository();
        public ActionResult Index(int ideaId)
        {
            return View(objStepOfIdearepository.FindBy(i=>i.IdeaId==ideaId));
        }

So i have another controller named idea and this controller has a view named index
@model IEnumerable<DomainClass.Idea>

@{
    ViewBag.Title = "Index";
}

لیست

    @if (User.IsInRole("User"))
    {

            @Html.ActionLink("ایده جدید", "Create", new {step = 1})

    }

        @if (User.IsInRole("Admin"))
        {

            @Html.DisplayNameFor(model => model.User.Name)

        }

            @Html.DisplayNameFor(model => model.IdeaPersion)

            @Html.DisplayNameFor(model => model.IdeaEnglish)

            @Html.DisplayNameFor(model => model.IdeaResult)

            @Html.DisplayNameFor(model => model.Date)

@foreach (var item in Model) {

         @if (User.IsInRole("Admin"))
        {

            @Html.DisplayFor(modelItem => item.User.Name) @Html.DisplayFor(modelItem => item.User.Name)

        }

            @Html.DisplayFor(modelItem => item.IdeaPersion)

            @Html.DisplayFor(modelItem => item.IdeaEnglish)

            @Html.DisplayFor(modelItem => item.IdeaResult)

            @Html.DisplayFor(modelItem => item.Date)

            @Html.RenderAction("ویرایش","index", stepofidea, new { id=item.Id }) |

            @Html.ActionLink("ویرایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("نمایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("حذف", "Delete", new { id=item.Id })

}

In this line
    @Html.RenderAction("ویرایش","index", ????, new { id=item.Id }) |

I want to redirect to index action of  stepOfIdea controller and pass a value .But the above line doesn't work .

A: I think you confused some terms in translation to English, and what you are actually looking for is to create an Link that also passes a variable.
You can do this very simply, by:
@Html.ActionLink("ویرایش", "Index", "StepOfIdea", new { id = item.Id }, null)

This will create the HTML:
ویرایش


text:
Q: VB.Net - Regex Issue I try to make a Regex pattern, that recognizes [== and ==] . It doesn't matter how much text is between [== and ==], also it should match it, if there are new lines between.
But It should always match to the next occurence that means if I have sth like this.
[== Cats and Dogs ==]  --> Match

or
[== fsdfd
sdfsdf

sdfsdf ==]             --> Match

[== ddasdas [== asdsd ==]  --> Match

from the first [== to the last ==]. It needs to ignore the second [== if there is no closing bracket.
How can I do this?

A: There are three possible approaches, none of which will work in all cases because your requirements are mutually exclusive.

*

*The solution that matches all the cases in your question (assuming you meant ==] where you wrote =]; I "fixed" those cases):
Dim RegexObj As New Regex("\[==.*?==\]", RegexOptions.Singleline)

This matches from the leftmost [== until the first ==]. It will not handle nested brackets correctly, as in my comment above where the result will be [== foo [== bar ==].

*The solution that matches all the cases, including the one in my comment, but only works if there is exactly one possible match in the entire input string:
Dim RegexObj As New Regex("\[==.*==\]", RegexOptions.Singleline)

This matches from the leftmost [== until the last ==] it finds.

*The solution that handles nested cases correctly, but fails on improperly nested cases (for example, matching only [== asdsd ==] when applied to [== ddasdas [== asdsd ==]:
Dim RegexObj As New Regex( _
    "\[==              # Match [==" & chr(10) & _
    "(?>               # Then either match (possessively):" & chr(10) & _
    " (?:              # the following group which matches" & chr(10) & _
    "  (?!\[==|==\])   # only if we're not before a [== or ==]" & chr(10) & _
    "  .               # any character" & chr(10) & _
    " )+               # once or more" & chr(10) & _
    "|                 # or" & chr(10) & _
    " \[== (?<Depth>)  # [== (and increase the nesting counter)" & chr(10) & _
    "|                 # or" & chr(10) & _
    " ==\] (?<-Depth>) # ==] (and decrease the nesting counter)." & chr(10) & _
    ")*                # Repeat as needed." & chr(10) & _
    "(?(Depth)(?!))    # Assert that the nesting counter is at zero." & chr(10) & _
    "==\]              # Then match ==].", _
RegexOptions.IgnorePatternWhitespace Or RegexOptions.Singleline)

Pick one :)


text:
Q: How can I force the user to save an excel file in excel? I am create an .xls file programatically and opening it in excel
for example:
Process.Start("c:/blabla.xls");

I am deleting the file when excel is closed, so I would like to prompt the user if he wants to save the file when excel before it is closed, and ideally make him save it to a new location.
I'm hoping there is an argument I can feed to excel during the Process.Start

A: Instead of opening Excel with an Excel file (.xls), you could open Excel with a Excel template (.xlt). This should open a new, unnamed file in Excel, using your xlt as the template. Since the file is unnamed, the user will be prompted to choose a location and file name if he made any changes.
(I'm not sure if renaming the file suffices; you might have to save the file as a template.)
EDIT: In fact, there is a command-line switch lets you do exactly that (open a normal Excel file as a template):
excel.exe /t C:\blabla.xls

A: Handle the BeforeClosed event.
This is assuming you are using Excel automation. Which, after reading your question again it appears you are not.
http://j-walk.com/ss/excel/tips/tip78.htm


text:
Q: How does performance of TCP and Unix Domain Sockets scale with number of processes and payload size? Say I've a server on the same machine as some workers, each of which is talking to it. They could be talking over TCP or Unix Domain Sockets. How does the performance scale with number of workers and message size?
When I speak of performance, I'm looking for not only mean latencies, but also p90 and p99 latencies.

A: As for TCP you can measure its performance youself (like this). Do a few tests.
Set the length of buffer to read or write and run iperf in server mode and also run a few iperf processes in client mode.  Then change the length of buffer to read or write.


text:
Q: How to upload image using MultipartEntity in Android HttpPost? Image not upload using MultipartEntity.
Gives status code 200 but image not updated on serverside.
 String responseBody;
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(
                    "http__zz/upload_picture?key=abc&property_id=10");

            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM).toString()
                    + "/Camera/Test.jpg");
            ContentBody encFile = new FileBody(file, "image/png");

            entity.addPart("picture", encFile);

            request.setEntity(entity);

            ResponseHandler<String> responsehandler = new BasicResponseHandler();
            responseBody = client.execute(request, responsehandler);

            if (responseBody != null && responseBody.length() > 0) {
                Log.w("TAG", "Response image upload" + responseBody);

            }

A: Try using a ByteArrayBody instead of a FileBody:
File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM).toString()
                    + "/Camera/Test.jpg");
Bitmap b = BitmapFactory.decodeFile(file;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, 100, bao);

ByteArrayBody body = new ByteArrayBody(bao.toByteArray(), "image/jpeg", "picture");
entity.addPart("picture", body);

A: Why don't you try to send it as base64 encoded string?

A: the best way to do this is to implement an IntentService and notify status with broadcast intents. please check out this code from git its work for me
https://github.com/alexbbb/android-upload-service


text:
Q: prorgress bar show half on some devices My progressbar shows a full circle in android 2.2 to 4.0, but in android version 4.1 is shows a half circle.
Below 4.0 device is show full progressbar (ex http://imgur.com/HyHRi5s) but when I test app on 4.1 is shows up like this: http://imgur.com/2n5ooo1
Both devices are the same height and width, so why is only half showing on 4.1 devices??
       <?xml version="1.0" encoding="UTF-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E5E5E5"
android:orientation="vertical" >

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/layoutbordercolor" >

    <ImageView
        android:id="@+id/btnback"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:paddingBottom="5dp"
        android:paddingLeft="3dp"
        android:paddingTop="10dp"
        android:src="@drawable/back" />

    <ImageView
        android:id="@+id/bitmap"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1.5"
        android:src="@drawable/logostar" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingTop="12dp"
            android:text="San Diego Unified"
            android:textColor="#603311"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="8dp"
            android:text="SCHOOL DISTRICT"
            android:textColor="#603311"
            android:textSize="10sp" />
     </LinearLayout>

     <ImageView
        android:id="@+id/options2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:paddingBottom="5dp"
        android:paddingTop="10dp"
        android:src="@drawable/options1" />
 </LinearLayout>

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#E5E5E5"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:paddingLeft="5dp"
        android:textStyle="bold" />
  </LinearLayout>
    <LinearLayout
    android:id="@+id/lytContent"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     android:orientation="vertical" >
<LinearLayout
    android:id="@+id/lytContent"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/layout_border"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listMainMenu2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dip"
        android:fadeScrollbars="true"
        android:listSelector="@color/listview_selector"
        android:paddingBottom="3dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:paddingTop="3dp"
        android:visibility="gone"

        />

</LinearLayout>

      <LinearLayout
        android:id="@+id/lytContent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
      android:layout_marginTop="20dp"
        android:orientation="vertical" >

   <ProgressBar
        android:id="@+id/prgLoading"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"

        android:paddingTop="100dp" />

    <TextView
        android:id="@+id/txtAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:paddingLeft="10dp"
        android:text="@string/alert"
        android:textColor="@color/text"
        android:textSize="14sp"
        android:visibility="gone" />
    </LinearLayout>

  </LinearLayout>

    </LinearLayout>


text:
Q: Mostar la fecha inicial y final Tengo una tabla cabecera y cabecera detalle, en mi cabecera tengo el id del cliente y en mi cabecera detalle tengo todos los meses que el cliente realizo un pago.
En mi Cabecera tengo el Id 1 y en mi detalle tengo los siguientes registros

Hasta ahí todo bien bonito,pero lo que tengo que hacer es  mostrar solo la tercera columna y en el caso que haya varios meses en un año y mes como por ejemplo el 2022  - 1 tiene varios meses que pago el cliente, en ese caso la tercera columna debería de mostrar solo el primer mes que pago y el ultimo mes como la siguiente imagen:

Yo he creado un store para poder hacer el agrupado pero lo hice con un ciclo while, el problema viene que yo tengo que hacer por cada cliente y son muchos clientes y esto hace que  el store tome mucho tiempo.

        SET LANGUAGE Spanish;

        INSERT INTO #PAGO (Ano, Mes, PeriodoCobertura)
        SELECT  YEAR(FechaOperacion), MONTH(FechaOperacion),    DescripcionPeriodoCobertura
        FROM    dbo.PAGO_MENSUALES
        WHERE   CodigoDocumento = @CodigoDocumento
                AND CodigoOperacion = 0 -- Pago de Cuota
                and MontoMovimientoCI >0
        ORDER BY 1, 2

            -- obtiene la fila inicial y final
        SET @Fila_Pago = 1
        SELECT  @Filas_Pago = ISNULL(MAX(NumeroRegistro), 0)
        FROM    #PAGO
        -- obtiene los datos iniciales
        SELECT  @AnoActual_Pago = Ano,
                @MesActual_Pago = Mes
        FROM    #PAGO
        WHERE   NumeroRegistro = @Fila_Pago
        SET @DescripcionActual_Pago = ''
        SET @DescripcionFechaInicial_Pago = ''
        SET @DescripcionFechaFinal_Pago = ''
        SET @DescripcionDefinida_Pago = ''

        BEGIN TRY
        WHILE @Fila_Pago <= @Filas_Pago
        BEGIN
            SELECT  @Ano_Pago = Ano,
                    @Mes_Pago = Mes,
                    @PeriodoCobertura = PeriodoCobertura
            FROM    #PAGO
            WHERE   NumeroRegistro = @Fila_Pago
            IF (@AnoActual_Pago = @Ano_Pago) AND (@MesActual_Pago = @Mes_Pago)
            begin
                SET @DescripcionActual_Pago = @DescripcionActual_Pago + @PeriodoCobertura + '/'
            end
            ELSE
            BEGIN
                SET @DescripcionActual_Pago = LEFT(@DescripcionActual_Pago, LEN(@DescripcionActual_Pago) - 1)

                IF CHARINDEX('/' , @DescripcionActual_Pago) > 0
                BEGIN
                INSERT INTO  #Pagos_No_PAGADOS(descFecha )
                SELECT Codigo FROM ufn_Split(@DescripcionActual_Pago, '/')

                UPDATE #Pagos_No_PAGADOS
                SET descFechaEdit ='1-' + descFecha

                UPDATE  #Pagos_No_PAGADOS
                SET descFechaEdit = replace(descFechaEdit,'set' , 'sep')

                UPDATE  #Pagos_No_PAGADOS
                SET valFecha = convert(DATETIME, descFechaEdit, 102)
                SELECT TOP 1 @DescripcionFechaFinal_Pago  =  descFecha   FROM #Pagos_No_PAGADOS ORDER BY valFecha DESC -- group by 1
                SELECT TOP 1 @DescripcionFechaInicial_Pago =  descFecha  FROM #Pagos_No_PAGADOS ORDER BY valFecha ASC -- group by 1
                SET @DescripcionActual_Pago = @DescripcionFechaInicial_Pago  + '/' +  @DescripcionFechaFinal_Pago
                SET @DescripcionDefinida_Pago =  @DescripcionFechaFinal_Pago
                DELETE FROM #Pagos_No_PAGADOS
            END
                declare @PagoObtenido varchar(25),
                @FechaGenerada varchar(40),
                @AnioCoberturaObtenido varchar(12)

                set @FechaGenerada = CONCAT( @AnoActual_Pago , '-', @MesActual_Pago , '-1')
                set @PagoObtenido =  substring(FORMAT(convert(datetime, @FechaGenerada, 102) , 'MMM') , 1 ,3 )
                set @PagoObtenido= UPPER(LEFT(@PagoObtenido, 1)) + LOWER(SUBSTRING(@PagoObtenido, 2, LEN(@PagoObtenido)))
                set @AnioCoberturaObtenido =  FORMAT(convert(datetime, @FechaGenerada, 102) , 'yy')
                set @DescripcionDefinida_Pago =  CONCAT( @PagoObtenido,'-', @AnioCoberturaObtenido)

                INSERT INTO #CoberturaConcatenado_Pago
                                (Ano, Mes,  PeriodoCobertura , PeriodoCoberturaModificada)
                VALUES      (@AnoActual_Pago, @MesActual_Pago, @DescripcionDefinida_Pago , @DescripcionActual_Pago)
                SET @AnoActual_Pago = @Ano_Pago
                SET @MesActual_Pago = @Mes_Pago
                SET @DescripcionActual_Pago = @PeriodoCobertura + '/'
                SET @DescripcionDefinida_Pago =''
        END
            SET @Fila_Pago = @Fila_Pago + 1
    END

A: No era necesaria tanta logica, elimine todo el ciclo while y lo trabaje con un insert a una tabla, despues lo agrupe por año y mes y solo quedo poner los maximos y minimos


text:
Q: Big O Complexity for Solving NP-hard Problem I have an NP-hard optimization problem that I formalized as mixed-integer linear program (MILP) and that I'm solving (for small inputs) with Gurobi.
I understand that NP-hard means that there's no polynomial time algorithm for solving the problem, unless P=NP.
Is there any more precise bound I can give on the time complexity for solving the problem (e.g., with Gurobi) using the Big O notation?
Any way of approximating the impact of the different input sizes on the complexity?

A: The field of mixed-integer programming is way too diverse to define a complexity rule depending on the number of variables or constraints. You need to check the literature concerning your specific problem or application - for many concrete problems, there are complexity results available. And this still does not necessarily carry over to the performance of a particular solver or whether you can actually solve a specific problem instance.


text:
Q: To @ or not to @ in Ruby on Rails Why do you have to refer to your class properties sometimes with @ and sometimes without it? If I were to remove the '@completed' and replace with 'completed', the test fails. But in the Project class the tasks property is set the same way but can be used without the @.
class Task
  attr_accessor :size, :completed

  def initialize(options = {})
    @completed = options[:completed]
    @size = options[:size]
  end

  def completed?
    @completed
  end

  def mark_completed
    @completed = true
  end
end

class Project
  attr_accessor :tasks

  def initialize
    @tasks = []
  end

  def done?
    tasks.reject(&:completed?).empty?
  end

  def total_size
    tasks.sum(&:size)
  end

  def remaining_size
    tasks.reject(&:completed?).sum(&:size)
  end
end

describe "estimates" do
    let (:project) { Project.new }
    let (:done) { Task.new(size: 2, completed: true) }
    let(:small_not_done) { Task.new(size: 1) }
    let(:large_none_done) { Task.new(size: 4) }

    before(:example) do
      project.tasks = [done, small_not_done, large_none_done]
    end

    it "can calculate total size" do
      expect(project.total_size).to eq(7)
    end

    it "can calculate remaining size" do
      expect(project.remaining_size).to eq(5)
    end
  end

A: attr_accessor :tasks is equivalent to:
def tasks
  @tasks
end

def tasks=(val)
  @tasks = val
end

When you call tasks, you are calling the tasks method, which just returns the value of the @tasks variable. The accessor method will always be used from outside of the class (since the instance variable isn't visible), but you can use either from within the class, since they're functionally equivalent for this implementation of the tasks method. However, you may want to use the tasks accessor if you may ever do something other than just returning @tasks - by hiding the variable access behind a method, you are free in the future to do more complex work in that accessor, without having to change the places that you use it.


text:
Q: More useful function for assigning new numbers I have a question about assigning a very wide range of numbers based on conditions in other columns.
In simple example I can describe my problem like this
df <- data.frame(col=rep(seq(0,3),each=4), row = c(seq(0,3)))

> df
   col row
1    0   0
2    0   1
3    0   2
4    0   3
5    1   0
6    1   1
7    1   2
8    1   3
9    2   0
10   2   1
11   2   2
12   2   3
13   3   0
14   3   1
15   3   2
16   3   3

I would like to create a new column based on the conditions in col and row column such that
assign_z <- function(col,row){

    ifelse(col==0&row<=0, 0, #0 is the assigned number to assign_z column
    ifelse(col==0&row>0&row<=2, 1, #1 is the assigned number to assign_z column
    ifelse(col==0&row>=3,2,        #2 is the assigned number to assign_z column

    ifelse(col==1&row<=0,3,        #3 is the assigned number to assign_z column
    ifelse(col==1&row>0&row<=2,4,  #4 is the assigned number to assign_z column
    ifelse(col==1&row>=3,5,        #5 is the assigned number to assign_z column

    ifelse(col==2&row<=0,6,        #6 is the assigned number to assign_z column
    ifelse(col==2&row>0&row<=2,7,  #7 is the assigned number to assign_z column
    ifelse(col==2&row>=3,8,        #8 is the assigned number to assign_z column

    ifelse(col==3&row<=0,9,        #9 is the assigned number to assign_z column
    ifelse(col==3&row>0&row<=2,10, #10 is the assigned number to assign_z column
    ifelse(col==3&row>=3,11,NA     #11 is the assigned number to assign_z column

    ))))))))))))

  }
}

and when I run my function I can get
library(dplyr)

df%>%
  mutate(assign_z=assign_z(col,row))

   col row assign_z
1    0   0        0
2    0   1        1
3    0   2        1
4    0   3        2
5    1   0        3
6    1   1        4
7    1   2        4
8    1   3        5
9    2   0        6
10   2   1        7
11   2   2        7
12   2   3        8
13   3   0        9
14   3   1       10
15   3   2       10
16   3   3       11

but assign_z function will be too long as I have 1000 col number in my real data. In addition, assign_z column should be increased in this systematical manner.
How can shorten the function to create same result even if I have 1000 columns ?

A: This performs a dense rank over the combination of col, row, but treats row = 2 as 1. I don't know what you are trying to achieve but it reproduces your output and would work with any length dataframe:
assign_z <- function(col, row){
  rank_over = paste0(col, ifelse(row == 2, 1, row))
  final_column = dense_rank(rank_over) - 1
  return(final_column)
}

df %>% mutate(assign_z=assign_z(col,row))
# col row assign_z
# 1    0   0        0
# 2    0   1        1
# 3    0   2        1
# 4    0   3        2
# 5    1   0        3
# 6    1   1        4
# 7    1   2        4
# 8    1   3        5
# 9    2   0        6
# 10   2   1        7
# 11   2   2        7
# 12   2   3        8
# 13   3   0        9
# 14   3   1       10
# 15   3   2       10
# 16   3   3       11

A: I don't use R, but based on what I see, can't you use a global counter
please forgive any syntax issues
    counter <<- 0

    assign_z <- function(col,row){
        #get current value
        returnValue<-counter

        #add to counter if row = 0 or 2 or 3
        if(row==0|row==2|row==3) { counter <<- counter + 1 }

        #return value before it was incremented
        return(returnValue)
    }

The pattern seems to be the number increment on row = 0, 2, 3


text:
Q: Are there any time-periodic solutions to Einstein's equations apart from black holes? Are there any solutions to Einstein's equations which are periodic in time?
A black hole only has mass, charge and angular momentum according to the no-hair theorem. (Although this might just mean in the limit as time goes to infinity because when two black holes collide the shape of their combined horizon would be extra information).
Would a binary black hole system be periodic? I'm not sure because it might give off gravitational waves and collapse. (But there is also the time reverse of this where a single black hole absorbs gravitational waves and splits in two!)
What about a pair of black holes in a Universe that is expanding so fast that they always stay the same distance apart?

A: In the paper Non-Existence of Time-Periodic Vacuum Spacetimes it is said that,

This paper addresses the question whether there exist asymptotically flat solutions of the Einstein vacuum equations which are "periodic in time" in a suitable
  sense. We show that any such solution must necessarily be stationary near infinity.
  Thus, genuinely "time periodic" solutions do not exist, at least in a neighborhood
  of (null) infinity.

Of course, in the general case, one can write down any time periodic metric, and compute the stress-energy tensor, thus offering a "solution" for that particular stress-energy, if physically sensible.
In the book, Exact Solutions to Einstein's Field Equations, there are plenty of solutions with a $\partial_t$ Killing vector which are thus technically periodic in time.

A: Extending @JamalS answer, the quoted result of Alexakis & Schlue means that any time-periodic solution must be non-asymptotically flat or non-vacuum.
For example, it is easy to construct a pp-wave solutions which would be periodic with a suitable choice of time coordinate.
The resonant properties of anti-de Sitter spacetime also provide possibility to construct time-periodic non-black hole solutions, which are asymptotically AdS. Though no explicit metrics for such spacetimes are known presently, a paper

*

*Horowitz, G. T., & Santos, J. E. (2014). Geons and the instability of Anti-de Sitter spacetime, arXiv:1408.5906.

provides us with a numerical construction of such solution, a geon, with a helical symmetry.


text:
Q: jQuery .html() removes all table related tags and breaking HTML I am fetching strange problem. I am using jQuery to execute AJAX request and trying to update a div content (bootstrap popover).
The AJAX is executed successfully and it is returning the HTML as output in debug.
<a href = "javascript:void(0);" data-toggle = "popover" title = "Line Details"  data-placement = "top" data-html = "true" data-content = "

        QTY
        DESC

        3
        <input type="text" size="8" id="itemDesc-job1-1" name="job1itemDesc" value="Test Desc" >

" > 157|999

Now, I am replacing the the div content (popover) like this:
$('#itemdetails-' + jobID).html(result.Data);

Surprisingly, it is removing all table related tags.
The page is the showing something else. Here is the code what is found in that div:
<a href="javascript:void(0);" data-toggle="popover" title="Line Details" data-placement="top" data-html="true" data-content="

                                     QTYDESCKG
                                    31
                            <input type="text" size="8" id="itemDesc-job1-1" name="job1itemDesc" value="1">

First time I am getting this type of wierd behavior of .html().
Is there anything I am missing?