text:
Q: 1 dollar more vs. more than 1 dollar A friend of mine has been arguing over the truth statement of: "1 dollar more vs. more than 1 dollar".
I am the one implying they're the same statement and convey the same semantic and logic; n < 1.
He fully disagrees they're the same thing in both the semantic and logic. Maybe it's cognitive dissonance.
Edit 1:
Since the referral to context seems to be the current crux of the argument is being held into (which I get my argument does not stand that well on), then I might as well give what context these statements are used in; They're mostly for the field of machine learning and trying to extract value statements from the English language and reducing that to a comparative mathematical abstraction.
I'd also want to say me and my friend are trying not to look at this on contextual truths (but that is what he is I assume unconsciously doing) but more in the form devoid of higher level contextual truths. My erratic suggestion my friend is suffering from cognitive dissonance was not helpful without context. So apologies for that.
I want to re-iterate that I am not this forum bent on contextual functional truths. If that were the case then I would have used at least used the term "context" in my query. Apologies if this did not come off clear and if this question is fundamentally unanswerable when it comes to logical semantics.
I know some might not agree with me saying that semantics does not equal purely to just pragmatic or proper context use cases but to a more lower level abstraction of truth.
Edit 2:
I believe that there are more truths to what the statement was than just contextual truths.

A: They're (usually) different. For example, if you have 10 dollar, and I give you 1 dollar more, you now have 11 dollars. If I gave you more than 1 dollar instead, you would have had at least 12 dollars.

A: They are not the same.
More is a comparative; it can always be followed by than and the noun or noun-phrase being compared.
More than one dollar is an obvious comparison: whatever amount you are considering is larger than a dollar: x > $1.

*

*The money I have in my wallet is more than one dollar.

*The price of this rug is more than one dollar.

One dollar more is a comparison where the "noun-phrase being compared" is not stated. But it can be filled in:

*

*My wallet contains one dollar more than the amount yours holds.

*This rug costs one dollar more than that one does.

That is, one dollar more needs than in order to make the comparison explicit. Without it, the comparison is implied from the context:

My wallet contains one dollar more. (Context: discussing wallets)
  This rug costs one dollar more. (Context: discussing rugs)

Thus "My wallet contains one dollar more" is not the same as "My wallet contains more than one dollar."


text:
Q: Issue creating my own dataset for the object detection tutorial from Tensorflow I'm trying to build my own dataset for the object detection tutorial from tensorflow, my code is here:
import tensorflow as tf
import os
from PIL import Image
from resizeimage import resizeimage
from object_detection.utils import dataset_util

flags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS

def create_tf_example(label_and_data_info):
    # TODO START: Populate the following variables from your example.
    height = 200 # Image height
    width = 200 # Image width
    filename = 'asc.0.jpg' # Filename of the image. Empty if image is not from file
    encoded_image_data = None # Encoded image bytes
    image_format = b'jpg' # b'jpeg' or b'png'

    xmins = [] # List of normalized left x coordinates in bounding box (1 per box)
    xmaxs = [] # List of normalized right x coordinates in bounding box
         # (1 per box)
    ymins = [] # List of normalized top y coordinates in bounding box (1 per box)
    ymaxs = [] # List of normalized bottom y coordinates in bounding box
         # (1 per box)
    classes_text = ['Ascaris'] # List of string class name of bounding box (1 per box)
    classes = [1] # List of integer class id of bounding box (1 per box)
    # TODO END
    tf_label_and_data = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(filename),
        'image/source_id': dataset_util.bytes_feature(filename),
        'image/encoded': dataset_util.bytes_feature(encoded_image_data),
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
        }))
    return tf_label_and_data

def main(_):
    writer = tf.python_io.TFRecordWriter(FLAGS.output_path)

    # TODO START: Write code to read in your dataset to examples variable
    file_loc = 'NematodeConvImagesResimensionadas/train_images'
    all_data_and_label_info = LOAD(file_loc)
    # TODO END

    for data_and_label_info in all_data_and_label_info:
        tf_example = create_tf_example(data_and_label_info)
        writer.write(tf_example.SerializeToString())

    writer.close()

if __name__ == '__main__':
    tf.app.run()

But when I try to run the script, the following error appears:
NotFoundError                             Traceback (most recent call last)
<ipython-input-4-658e1dd88560> in <module>()
      14
      15 if __name__ == '__main__':
 ---> 16     tf.app.run()
/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py in run(main, argv)
      122   # Call the main function, passing through any arguments
      123   # to the final program.
 ---> 124   _sys.exit(main(argv))
      125
      126
<ipython-input-4-658e1dd88560> in main(_)
      1 def main(_):
----> 2     writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
      3
      4     # TODO START: Write code to read in your dataset to examples variable
      5     file_loc = 'NematodeConvImagesResimensionadas/train_images'
/usr/local/lib/python3.5/dist-packages/tensorflow/python/lib/io/tf_record.py in __init__(self, path, options)
      104     with errors.raise_exception_on_not_ok_status() as status:
      105       self._writer = pywrap_tensorflow.PyRecordWriter_New(
  --> 106           compat.as_bytes(path), compat.as_bytes(compression_type), status)
      107
      108   def __enter__(self):
/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
      471             None, None,
      472             compat.as_text(c_api.TF_Message(self.status.status)),
  --> 473             c_api.TF_GetCode(self.status.status))
      474     # Delete the underlying status object from memory otherwise it stays alive
      475     # as there is a reference to status from this from the traceback due to

NotFoundError: ; No such file or directory

I don't know how to solve this, I have tried to change the path of my images but still it doesn't seem to find the directory. Any help would be really appreciated.

A: The second argument in the flags.DEFINE_string('output_path', '', 'Path to output TFRecord') should point to the output folder on your machine. You left that empty.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android httpclient calling restfull web service according to following url I have created a requesthelper for calling a restfull webservice(.Net).
http://as400samplecode.blogspot.com/2011/09/android-asynctask-httpclient-with.html
every time I call it from Android device it give error. in one of the topic at stackoverflow I suggest add '/' character at the end of the URL. You can find my url formats and given errors as listed below.
http://domain.com/default.svc/start/4ef8e420-e6a2-49f5-b612-c0b2dced0920/
at web browser it returns "End point not found".
from the Android Log :
10-03 18:02:07.373: WARN/HTTP1:(3983): Not Found
10-03 18:02:07.383: WARN/HTTP3:(3983): java.io.IOException: Not Found
10-03 18:02:07.383: WARN/HTTP3:(3983):     at requestHelper.doInBackground(requestHelper.java:84)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at requestHelper.doInBackground(requestHelper.java:1)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
10-03 18:02:07.383: WARN/HTTP3:(3983):     at java.lang.Thread.run(Thread.java:1096)

http://domain.com/default.svc/start/4ef8e420-e6a2-49f5-b612-c0b2dced0920
at web browser it returns a JSONObject as I wanted.
from the Android Log :
10-03 18:03:41.683: WARN/HTTP1:(4023): Method Not Allowed
10-03 18:03:41.683: WARN/HTTP3:(4023): java.io.IOException: Method Not Allowed
10-03 18:03:41.683: WARN/HTTP3:(4023):     at requestHelper.doInBackground(requestHelper.java:84)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at requestHelper.doInBackground(requestHelper.java:1)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
10-03 18:03:41.683: WARN/HTTP3:(4023):     at java.lang.Thread.run(Thread.java:1096)


text:
Q: JPA Criteria: How to filter on multiple entity subclasses @Inheritance(strategy = InheritanceType.SINGLE_TABLE) I wonder if there is any elegant way, to filter on Employee entity following data model below.
So if i need to filter on "name", "hourlyRate" and "salary" i can't use jpa specification, i need write a raw sql
model
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
   @Entity
   @DiscriminatorColumn(name = "EMP_TYPE")
        JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "EMP_TYPE", visible = true)
        @JsonSubTypes({
          @JsonSubTypes.Type(value = FullTimeEmployee .class, name = "F"),
          @JsonSubTypes.Type(value = PartTimeEmployee .class, name = "P"),

        })

    public class Employee {
     @Id
     @GeneratedValue
     private long id;
     private String name;

    }

Type classes
    @Entity
@DiscriminatorValue("F")
public class FullTimeEmployee extends Employee {
  private int salary;
    .............
}

@Entity
@DiscriminatorValue("P")
public class PartTimeEmployee extends Employee {
  private int hourlyRate;
    .............
}

'SHOW TABLES'
[EMPLOYEE, PUBLIC]
'SHOW COLUMNS from EMPLOYEE'
[EMP_TYPE, VARCHAR(31), NO, , NULL]
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[HOURLYRATE, INTEGER(10), YES, , NULL]
[SALARY, INTEGER(10), YES, , NULL]

A: You can write a HQL query like the following:
from Employee e
where (type(e) = FullTimeEmployee and e.salary > 1000)
   or (type(e) = PartTimeEmployee and e.hourlyRate > 100)


text:
Q: Azure Function Trigger Name/Connections from App Configuration Is there now a way to set the Trigger Properties(Name/Connection) using the value from Azure App Configuration?.
I added a startup class that reads the data from Azure App Configuration but it seems the trigger set its properties earlier than that, therefore not able to bind the data that came from the app configuration.
I also found this thread about it but im not sure if there is a new update?:
https://github.com/MicrosoftDocs/azure-docs/issues/63419
https://github.com/Azure/AppConfiguration/issues/203

A: You can do this. The following code gets the name of the queue to monitor from an app setting, and it gets the queue message creation time in the insertionTime parameter:
public static class BindingExpressionsExample
{
    [FunctionName("LogQueueMessage")]
    public static void Run(
        [QueueTrigger("%queueappsetting%")] string myQueueItem,
        DateTimeOffset insertionTime,
        ILogger log)
    {
        log.LogInformation($"Message content: {myQueueItem}");
        log.LogInformation($"Created at: {insertionTime}");
    }
}

Similarly, you can use this approach for other triggers.


text:
Q: setting a variable with  from drop down list in Grails in Grails gsp ,
i what to assign a variable when the user makes a choice from drop down list , in another way when user chooses the value from :
<g:select name="patient.id" from="${patients}" optionKey="id" >

i want to set the patient's id to "pid" variable in the below :
<g:set var="pid" scope="request">

the only way that succeeded with me is :
<g:set var="pid" value="${2}" scope="request">

but this is not dynamic way .
how can i achieve that ?
thanks
Sherif

A: g:set is actually not an html field and you are trying to assign an java object from html/js code.
You can't assign any Java Object a js variable from client side scripting.If you need a workaround to achieve this only then the max you can do is:
$('#your_select').on('change',function(){
if($('this').val()=="bingo"){
var X="${pid="bingo"}" //if will assign pid a string "bingo" and X(a js var) value "bingo"
}
}

See the code between ${} is server side code and you can't write any client side code into it so basically you can't just do something like "${pid=$(this).val()}".

If you wonder why we can't do this is because there  is no need to do this and it does not make sense too as described in Igor Artamonov's comment.

A: In you don't need some workaround as i described in my another answer then the optimum solution for sort of requirements is:

*

*Get the value of select in some js variable.

*Make an AJAX call to server action that will send data according to request parameters so in this case one parameter will your selected value.

*Receive the AJAX response and set the html elements based on response.

So the example would be:
var selected = $('#your_select_id).val();
jQuery.ajax({
                    type: 'POST',
                    url: 'your action url that will render response',
                    data: "selected="+selected,
                    async: false,
                    success: function(response,textStatus){
                        json= JSON.parse(response);
                        $('#some_textBox).val(json.somevalue);
                     },
                    error:function(XMLHttpRequest,textStatus,errorThrown){}
                });


text:
Q: How does this code work? Is there a different way to write it to make it more readable? I am learning python and I found out you can use .apply() to apply a function to a column. I am confused as to why you can use cols[0] in this scenario. When I try running df[0] I get an error. However, with the way I am passing data to the function, I'd expect to get a result. Why is cols[0] acceptable but df[0] is not?
def fills_na(cols):
    Age = cols[0] # i dont understand why this works. When running df_new[0] I get an error
    Pclass = cols[1]
    if pd.isnull(Age):
        if Pclass == 1:
            return 37
        elif Pclass == 2:
            return 29
        else:
            return 24
    else:
        return Age
# then this baby calls it
df['Age'] = df[['Age','Pclass']].apply(fills_na, axis = 1)


text:
Q: How to return a table along with 2 varchar values from a Postgres function
Currently migrating Oracle database to Postgres and I have come across an use case where I am stuck.
In Oracle I have a procedure which returns 3 values

*

*The resultset from a SELECT query (This is an Oracle ref_cursor)

*A message

*A status

This is the procedure in Oracle

CREATE OR REPLACE PROCEDURE ORA_TEST (
        I_EMP_ACTIVE IN VARCHAR2,
        O_RESULTSET OUT SYS_REFCURSOR
        O_MESSAGE OUT VARCHAR2
        O_STATUS OUT VARCHAR2)
AS
        V_COUNT NUMBER;
BEGIN
        SELECT COUNT(*) INTO V_COUNT FROM EMPLOYEE WHERE EMP_ACTIVE=I_EMP_ACTIVE;
                IF V_COUNT>0
                        OPEN O_RESULTSET FOR SELECT * FROM EMPLOYEE WHERE EMP_ACTIVE=I_EMP_ACTIVE;
                        O_STATUS := 'SUCCESS';
                        O_MESSAGE := 'Search Results found';
                ELSE
                        O_STATUS := 'FAILURE';
                        O_MESSAGE := 'No Search Results found';
                END IF;
END;

Now when I try to create this Procedure in Postgres as a Function, I can return the resultset as a TABLE or SETOF RECORD, but I am not able to return the O_MESSAGE and O_STATUS along with the resultset.
Please note that I cannot return the resultset using a Postgres ref_cursor (This is because we have some issues accessing ref_cursor from APIs, which is why we return the resultset using TABLE, SETOF RECORD or SETOF TYPE).
If there any way to achieve this type of resultset (with a TABLE as well as 2 varchar columns)?

A: You can convert it like below...(I am not sure whether it will work with your API or not...)
create or replace function ORA_TEST(I_EMP_ACTIVE varchar)
returns table(O_RESULTSET refcursor, O_MESSAGE varchar, O_STATUS varchar) as

$$
declare
V_COUNT int;
ref refcursor := 'mycursor';
begin
SELECT COUNT(*) INTO V_COUNT FROM EMPLOYEE WHERE EMP_ACTIVE=I_EMP_ACTIVE;
                IF V_COUNT>0 then
                        OPEN ref FOR SELECT * FROM EMPLOYEE WHERE EMP_ACTIVE=I_EMP_ACTIVE;
                        O_STATUS := 'SUCCESS';
                        O_MESSAGE := 'Search Results found';
                ELSE
                        O_STATUS := 'FAILURE';
                        O_MESSAGE := 'No Search Results found';
                END IF;

return query

select ref, O_STATUS, O_MESSAGE;

end;
$$
language plpgsql;

And call it like below:
BEGIN;
select * from ora_test('1');
FETCH ALL from "mycursor";
COMMIT;

DEMO


text:
Q: Phone number recognition in sms body in android I want to study how android works when sms sends. More precisely - I want to know how android recognizes phone number in sms body, like in the next photos:
For example, somebody sent me sms with the next text: You can use the next phone number: 0673452345

2) Then I opened this sms

3) And after this, I clicked on the recognized phone number

So I want to know what class or couple of classes does (do) this recognition. May be someone knows where I can find this in android sources.
Help please!

A: This is it  click here this site has all things you want to know about sms please have a look at it. It contains sending and receiving  of sms and all about it...

A: I guess this is done within the application. Any sequence of successive digits (maybe within some bounds, at least x at most y digits) is interpreted as a phone number.

A: For This you can simply check for any 5 or more successive digits in string.
If found then replace number by something like this. number and at time of show parse that and make a link for that.


text:
Q: How to write a RuboCop Cop to prevent writing Sidekiq workers using keyword arguments? Not too long ago, I've found out that you can't use keyword arguments when defining Sidekiq workers. Since it only raises an exception after it gets enqueued, I want to prevent this from reaching production for good. And for that, I'd like to add a cop that checks the arguments for #perform and raises an error if there's a keyword argument being used. This is my failed attempt so far:
module RuboCop
  module Cop
    class SidekiqDontUseKeywordArguments < RuboCop::Cop::Cop
      MSG = "Don't use keyword arguments in workers".freeze
      OBSERVED_METHOD = :perform

      def on_def(node)
        return if node.method_name != OBSERVED_METHOD

        node.arguments.each do |argument|
          if keyword_argument?(argument)
            add_offense(node, location: :expression)
          end
        end
      end

      private

      def keyword_argument?(argument)
        # detect if the argument is a keyword
      end
    end
  end
end

I'm missing two things here. The first and most important is that I don't know how to tell whether an argument is a keyword or not. The second is that I'd like to apply this cop only for Sidekiq workers. Am I following the right approach here? Is there a better way of doing this?

A: You can enable specific cops for only your Sidekiq workers by using inheritance. For example, if your workers live in app/workers then you can create a new ruleset there that inherits from your project's root and then enables your custom cop:
# app/workers/.rubocop.yml
inherit_from:
  - ../../.rubocop.yml
require:
  - ../lib/rubocop/cop/custom/sidekiq_dont_use_keyword_arguments.rb
Custom/SidekiqDontUseKeywordArguments:
  Enabled: true
# For validation of this theory only; do not use this
Lint/DuplicateMethods:
  Enabled: false

To make your custom cop detect keyword arguments use the node.type method. The elements of node.arguments are themselves nodes and support the same methods, and reading the type of an argument will return one of four values:
# Standard argument: perform(foo)
:arg

# Optional standard argument: perform(foo = 1)
:optarg

# Keyword argument: perform(foo:)
:kwarg

# Optional keyword argument: perform(foo: 1)
:kwoptarg

So check for :kwarg and :kwoptarg (and note the path change and additional Custom module to define this cop's department):
# app/lib/rubocop/cop/custom/sidekiq_dont_use_keyword_arguments.rb

module RuboCop
  module Cop
    module Custom
      class SidekiqDontUseKeywordArguments < RuboCop::Cop::Cop
        MSG = "Don't use keyword arguments in workers".freeze
        OBSERVED_METHOD = :perform

        def on_def(node)
          return if node.method_name != OBSERVED_METHOD

          node.arguments.each do |argument|
            if argument.type == :kwarg || argument.type == :kwoptarg
              add_offense(node, location: :expression)
            end
          end
        end
      end
    end
  end
end

Let's use this as an example worker:
# app/workers/example_worker.rb
class ExampleWorker
  # Standard argument; this will not trigger the cop
  def perform(foo); end

  # Optional standard argument; this will not trigger the cop
  def perform(foo = 1); end

  # Keyword argument; this will trigger the cop
  def perform(foo:); end

  # Optional keyword argument; this will trigger the cop
  def perform(foo: 1); end
end

Running Rubocop will return the following output:
rubocop app/workers
Inspecting 1 file
C

Offenses:

app/workers/example_worker.rb:9:3: C: Custom/SidekiqDontUseKeywordArguments: Don't use keyword arguments in workers
  def perform(foo:); end
  ^^^^^^^^^^^^^^^^^^^^^^
app/workers/example_worker.rb:12:3: C: Custom/SidekiqDontUseKeywordArguments: Don't use keyword arguments in workers
  def perform(foo: 1); end
  ^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 2 offenses detected


text:
Q: my Css code for navigation menu not working in Wordpress theme while making my custom navigation menus for my own Worpress theme, navigation menu's css code's some codes are working, some are not working while entering php navigation code for Wordpress theme.
This my php code for wordpress navigation menu
    <?php   wp_nav_menu( array(
                                'theme_location'    => 'primary',
                                'depth'              => 2,
                                'container'         => 'ul',
                                'container_class'   => '',
                                'menu_class'        => 'nav-link',
                                'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
                                'walker'            => new WP_Bootstrap_Navwalker())
                                 );?>

so i am having so many classes in navigation menu so my css code is very long that's why i am adding my html code for my navigiation bar. this my html code for navigation menu.

                       Home

                       Categories

                                   Motivation

                                   Health

                               Science & Technology

                                   Finance

                                   Random

                       Archives

`enter code here`enter code here`

                                   Contact us

`enter code here`

                                   Privacy Policy

                                   Terms & Condition

                                   Disclaimer

                       About

something wrong in my php code. can you give correct code for my navigation bar.

A: We don't see you code in context, but your 'container' element has wrong. You must set a nav or div, not ul (i suggest nav tag). Remember define 'container_class' too.
Then you must define your CSS rules including your container_class in spreadsheet. If is necessary, you must use !important.


text:
Q: Best way to handle large PHP page loading with Jquery/Ajax/HTML etc Happy New Year, Hope you are well.
I am working on a project which generates a "league table" based on a lot of data, similar to the ones used in various sports (namely football). I have built the backend in PHP which processes the data and outputs the results, however it can take about 6-9 seconds per user, with an average of 10-20 users in a group the page load would take over a minute. To be honest, I expected it to take longer than that as the script has to loop through about 10,000 records per user and do quite a bit of arithmetic.
My question is, what is the best way to load this data into a page? The way I had done it was by having a div the size of the page, on top of all other content, which simply said loading in the middle - this would then make it's self hidden once the page had loaded. This approach was fine but i think it is leaving the door open for various issues - one could be the page timing out or the user thinks it has crashed etc.
What I have been advised to do is have a lightweight page, that calls a api on the server to initiate the request. The api responds with a request id (or something to identify the request anyway), then starts to generate the data. The page would query the api every say 15 seconds to see how its doing, eventually the api would respond saying its complete - then the user would be redirected to view the report.
Any advise/suggestions would be much appreciated.
Thanks in advance,
Smithey.

A: You should use AJAX to load the data into a div in the page, example code (this code uses jQuery) :
HTML :

Please wait, loading data...

Javascript :
$(function(){ // This is so that it executes only once the document is loaded
    $("#data").load("/script.php", function(response, status, xhr) {
        if(status == "success") {
            // On success
            $('#loading').hide(); // Hides the "please wait" text
        } else if (status == "error") {
            // Do something on error
            alert("Could not load data, please refresh the page."); // Example alert
        }
    });
});


text:
Q: Azure Pipeline Publish: task DotNetCoreCLI with specific folder or project I'm having a problem (unwanted behavior) when running an Azure Build Pipeline with the following project/folder structure.
My repository's root folder has two main folders:

*

*frontend (ASP.Net Core 2.x & Angular 7 project)

*backend (ASP.Net Core 2.x)

I'm trying to build two separate Azure Pipelines one for the backend and one for the frontend, so I use the projects: parameter to specify the correct path.
The build and test commands are running fine and are only restoring/building/testing the backend folder, but the publish command is running for both folders: backend & frontend.
This is my yaml file:
 #build backend project
 task: DotNetCoreCLI@2
   displayName: dotnet build --configuration $(buildConfiguration)
   name: BuildBackendProject
   inputs:
     command: build
     projects: '**/backend/**/*.csproj'
     arguments: '--configuration $(buildConfiguration)'

 ... #run some tests

 #publish backend project
 task: DotNetCoreCLI@2
   displayName: dotnet publish backend --configuration $(buildConfiguration)
   name: PublishBackendProject
   inputs:
     command: publish
     projects: '**/backend/**/*.csproj'
     publishWebProjects: True
     arguments: '--configuration $(BuildConfiguration) --output
     $(Build.ArtifactStagingDirectory)/backend'
     zipAfterPublish: True

I tried different folder paths but it's always running two publish commands.
If I run locally in CMD dotnet publish backend (from repo's root folder) it works fine but apparently that doesn't work with the Azure Pipeline.
Any ideas or fixes greatly appreciated.

A: The trick is in using the publishWebProjects/projects properties. Those are actually mutually exclusive. If the publishWebProjects is used, the projects property value is skipped.
From the documentation:

Publish Web Projects*: If true, the task will try to find the web
  projects in the repository and run the publish command on them. Web
  projects are identified by presence of either a web.config file or
  wwwroot folder in the directory.

So you could try the following code for publishing:
task: DotNetCoreCLI@2
  displayName: dotnet publish backend --configuration $(buildConfiguration)
  name: PublishBackendProject
  inputs:
    command: publish
    projects: '**/backend/**/*.csproj'
    publishWebProjects: false
    arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)/backend'
    zipAfterPublish: true


text:
Q: Propagating FormArray validators from child component to parent component in Angular 8 EDIT : I managed to get data passthrough and validation working perfectly, by rewriting the email-phone-input.component.ts to use ControlContainer, get the FormGroup from the parent, along with FormArray controls.
Will update the repo with working code and answer the question.
I am trying to get validators working for Form Group containing objects sent from a child component with Form Arrays.
Current hierarchy - Individual email component, individual phone component (that utilises an external package), then an email + phone component containing FormArray for both email and phone, and then a master form with a single formcontrol that gets the data from the email + phone component.
I've got the data coming through all the way, but I can't figure out how to get the validators to the master form.
Link to stackblitz containing the code + demo. https://stackblitz.com/github/rushvora/nested-form-playground
Side note - Validators.required isn't working for the email input, when adding a new Form Control to the Form Array.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'nested-form-playground';
  form: FormGroup;
  emailsAndPhones: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      notifications: this.fb.group({
        emailsAndPhones: []
      })
    });
    this.emailsAndPhones = this.form.get('notifications.emailsAndPhones') as FormGroup;
  }

  submit() {
    console.log(this.form.valid, this.form.status);
  }
}

app.component.html

    <form [formGroup]="form" (ngSubmit)="submit()">

Nested Form Testing.

        <app-email-phone-input formControlName="emailsAndPhones"></app-email-phone-input>

        <button>Submit</button>

    </form>

email-phone-input.component.ts
import { Component, OnInit, OnDestroy, forwardRef } from '@angular/core';
import {
  FormGroup, FormBuilder, FormArray, FormControl, ControlValueAccessor,
  Validator, NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators, AbstractControl
} from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-email-phone-input',
  templateUrl: './email-phone-input.component.html',
  styleUrls: ['./email-phone-input.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => EmailPhoneInputComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => EmailPhoneInputComponent),
      multi: true
    }
  ]
})
export class EmailPhoneInputComponent implements OnInit, ControlValueAccessor, Validator, OnDestroy {
  emailsAndPhonesForm: FormGroup;
  emails: FormArray;
  phones: FormArray;
  private destroy$ = new Subject();

  constructor(private fb: FormBuilder) { }

  ngOnInit() {

    this.emailsAndPhonesForm = this.fb.group({
      emails: this.fb.array([]),
      phones: this.fb.array([])
    });
    this.emails = this.emailsAndPhonesForm.get('emails') as FormArray;
    this.phones = this.emailsAndPhonesForm.get('phones') as FormArray;
  }

  public onTouched: () => void = () => { };

  writeValue(val: any): void {
    val && this.emailsAndPhonesForm.setValue(val, { emitEvent: false });
  }

  registerOnChange(fn: any): void {
    this.emailsAndPhonesForm.valueChanges
      .pipe(takeUntil(this.destroy$))
      .subscribe(fn);
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  validate(_: AbstractControl) {
    let emailsValidity = {};
    let phonesValidity = {};
    this.emails.valid ? emailsValidity = null : { invalidForm: {valid: false, message: `Email is invalid.`}};
    this.phones.valid ? phonesValidity = null : { invalidForm: {valid: false, message: `Phone is invalid.`}};
    console.log('Emails and Phones Form in validate: ');
    console.log(this.emailsAndPhonesForm);
    console.log('Emails in validate: ');
    console.log(this.emails);
    console.log('Phones in validate: ');
    console.log(this.phones);
    if (emailsValidity && phonesValidity) {
      const combinedValidity = { invalidForm: {valid: false, message: `Email & phone are invalid.`}};
      return combinedValidity;
    } else if (emailsValidity) {
      return emailsValidity;
    } else if (phonesValidity) {
      return phonesValidity;
    } else {
      return null;
    }
  }

  addEmail() {
    this.emails.push(new FormControl('', Validators.email));
  }

  addPhone() {
    this.phones.push(new FormControl('', Validators.required));
    console.log('Emails and Phones Form in addPhone: ');
    console.log(this.emailsAndPhonesForm);
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

}

email-phone-input.component.html

<ng-container [formGroup]="emailsAndPhonesForm">
  <ng-container formArrayName="emails">
    <ng-container *ngFor="let email of emails.controls; index as i">

        <app-email-input [index]="i+1" [formControlName]="i"></app-email-input>

    </ng-container>
    <button type="button" (click)="addEmail()">Another Email</button>
  </ng-container>
  <ng-container formArrayName="phones">
    <ng-container *ngFor="let phone of phones.controls; index as i">

          Phone {{ i + 1 }}
          <app-phone-input [formControlNameCustom]="i"></app-phone-input>

    </ng-container>
    <button type="button" (click)="addPhone()">Another Phone</button>
  </ng-container>
</ng-container>

    {{email?.email }}

    {{phone?.internationalNumber }}

A: I fixed the issue by using ControlContainer to get the parent form group from the parent/master component. In this manner, I was able to update the validity, set the validators in the child component for the parent form controls directly.
The base components still need to be implemented using CVA, here the email input and the 3rd party phone package does use CVA to implement their controls, but the layers above them all the way to the top layer just need to use ControlContainer, in order to pass the master form group/controls between components.
Thanks to this answer for leading me to the solution - Create a reusable FormGroup
Updated code - https://github.com/rushvora/nested-form-playground


text:
Q: Hosted Mercurial with Project Management tools I have used a couple of the hosted SCM's like Unfuddle and Codespaces before and I like that they have Project Management tools built in.  I've started using Mercurial and really like it, I would like to make the switch to it, but I can't seem to find any hosted mercurial solutions that contain project management tools.
Does anyone know any hosted solutions that have mercurial repositories with project management solutions?  Similar to Aseembla, CodeSpaces, Unfuddle, etc.
I know there is BitBucket, but I don't see any project management tools.
EDIT: Details about the types of tools I'm looking for.
It is for a very small team, 2-5 people.  Looking for Agile (or close to Agile) tools.  For example, in CodeSpaces there is a card wall, Assembla has a robust ticketing system that you can create swim lanes in, etc.

A: FogBugz (Project Management) and Kiln (Mercurial Repository). Both made by Fog Creek. Some would say that FogBugz is only a bug tracking software but it is actually a PM tool if used correctly. There is actually a book on how to use it as a PM tool. The title of the book is Painless Project Management.
The nice thing about these two tools is that they are completed integrated so that you can tie cases to check-ins, etc.

A: Bitbucket is the de facto option for hosted mercurial, the most you have for project management is a ticketing system you must enable in your repository's admin panel.
Alternatively, you could try setting up mtrack or Redmine (recommended) in your own box, both of them are full-fledged project management tools. Having your own deployment of a project management app can be the best on the long run.

A: Almost any bug-tracking/project-management tool I know does allow sources to be in a mercurial repository :

*

*http://bitbucket.org : built around Mercurial, does provide an issue system, a wiki etc. in fact all the others does too.

*http://code.google.com : does manage multiple Mercurial repostories for the same project, but is equivalent in some aspects to BitBucket (in the current implementations).

*Sourceforge : don't know much but it's an old one that was already there when mercurial wasn't born yet.

*TRAC (on your own server - python) : nice, main problem is lack of multi-projects

*Redmine (on your own server - ruby) : nice, more flexible than TRAC but have some minor youngness lacks;

*JIRA (on your own server - java) : nice, more complete than Redmine but not as flexible as TRAC - but does manage multiple projects

*Fogbugz : really nice but with a price if your project is commercial (and other conditions).

*etc.

If you don't choose one of the 3 first, then don't think about the repository type (git, mercurial, svn, whatever), the ticket management system is then more important.
If you have no clue and just want something to setup fast: if you want to have your sources available only by your team, use bitbucket. If you want to be opensource, flip a coin for bitbucket or google code.


text:
Q: Nginx Echo Subrequest not working I am new to Nginx.
My requirement is I need to make a service call but along with proxy passing that request, I need to make call to another service/servlet. For this I decided to use Echo module to use the echo_subrequest_async option.
However the subrequest is not working and even simple echo print is not working. Where does echo "hello" supposed to go? to the client side (my guess)
Below is my configuration (some notes):

*

*Both the servers are java servers which are running on my local box

*my os is mac osx version 10.9.5
3, I compile nginx 1.6.2 from source and with modules pcre and http echo

nginx version: nginx/1.6.2
built by clang 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
configure arguments: --with-pcre=/Users/xxxx/project/pcre-8.35 --add-module=/Users/xxxx/project/echo-nginx-module-0.57 --with-cc-opt=-Wno-deprecated-declarations
nginx config I have used is as follows
http {
server {
   listen 80;
   server_name localhost;

    # this will handle the initial request
    location /messaging-service {
        default_type "text/plain";
        echo "in the messaging service call";
        echo_flush;
        echo_subrequest_async GET '/mywebapp/second';
        proxy_pass http://localhost:8090/messaging-service/;
    }

    # this is where the sub request should go,note its different service
    location /mywebapp/second {
        echo "Going to make another call on different server !!";
        echo_flush;
        proxy_pass http://localhost:8080/mywebapp/second/;
    }

}

}


text:
Q: How to debug Laravel Site show HTTP ERROR 500? I'm on Laravel 5.7, and my app loading fine on my local Mac OSX.
But on my production Ubuntu Server, I kept getting 500

permissions
I've already chmod R 777 storage/ bootstrap/ vendor/

.env
I also check my .env file, everything seem to be in place proper configured.

nginx
I checked in cd /var/log/nginx/ I see nothing there.

laravel
I checked /home/forge/bheng/storage/logs - nothing there also.

composer.json
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "5.7.*",
        "intervention/image": "^2.3",
        "laravelcollective/remote": "5.7.*",
        "doctrine/dbal": "^2.3",
        "league/flysystem-sftp": "^1.0",
        "laravelcollective/html": "^5.4.0",
        "phpseclib/phpseclib": "~2.0",
        "htmlmin/htmlmin": "^5.0",
        "league/flysystem-aws-s3-v3": "~1.0",
        "vinkla/instagram": "^8.0",
        "php-http/message": "^1.6",
        "php-http/guzzle6-adapter": "^1.1"
    },
    "require-dev": {
        "phpunit/phpunit": "~7.0",
        "phpspec/phpspec": "~5.0",
        "symfony/dom-crawler": "~3.1",
        "symfony/css-selector": "~3.1",
        "filp/whoops" : "~2.0"
    },
    "autoload": {
        "classmap": [ "database" ],

        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
        ]
    },
    "scripts": {
        "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
        ],
        "post-update-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
        ],
        "post-create-project-cmd": [
        "php -r \"copy('.env.example', '.env');\"",
        "php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

How would one go about debugging this further?

A: Check if the php version is correct, to know PHP version your Apache server is using use phpinfo(),php version check but you might get a different version in php -v. if that is the issue use
    $ sudo a2dismod php5.6
    $ sudo a2enmod php7.1
    $ sudo service apache2 restart

To switch php versions and then goto bootstrap/cache folder and clear the folder.

A: Your laravel.log file has only root lavel write permission, however it seems your webserver using www-data as a group and maybe a user too. You can change group and owner of laravel.log file.
chown  www-data:www-data /home/forge/bheng/storage/logs/laravel.log

after this it will start logging.
For file permission in Laravel 5 you can check this How to set up File Permissions for Laravel 5 (and others)


text:
Q: Selecting events using Kal calendar I'm adding a calendar view to my app using Kal Calendar but am having problems implementing a didSelectRowAtIndexPath method on the event list.  I would like to push a view controller when the user selects an event for any given day.  I've tried putting the method in "KalView.m", "KalViewController.m", and "KalDataSource.m", but none are recognized.  Where is the appropriate place to call such a method?

A: I had similar issue once, Here is how I implemented it.
#import <MTDates/NSDate+MTDates.h>
#import <ObjectiveSugar/ObjectiveSugar.h>
#import <UIImageView+WebCache.h>

#import "EventsViewController.h"
#import "EventDetailsViewController.h"
#import "EventCell.h"
#import "Event.h"

#import "KalViewController.h"
#import "CalendarViewController.h"

@implementation EventsViewController

- (id)initWithEvents:(NSArray *)_events {
    self = [super init];
    events = _events;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self listUpdated];
    [self addCalendarView];
}

- (void)listUpdated
    {

        NSMutableArray *allEvents = [NSMutableArray array];
        [allEvents addObjectsFromArray:events];

        NSArray *sortedArray = [allEvents sortedArrayUsingComparator:^NSComparisonResult(Event *obj1, Event *obj2) {
            return [obj1.date compare:obj2.date];
        }];

        _allEvents = sortedArray;
    }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_allEvents count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//custom table cell (EventCell is a view I'm initialising my rows with)
    Event *event = _allEvents[indexPath.row];
    NSString *reuseIdentifier = [NSString stringWithFormat:@"Cell%@%@", event.venue.identifier, event.identifier];
    EventCell *cell = (EventCell*) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [EventCell createDetailedCellWithReuseIdentifier:reuseIdentifier];
        cell.nameLabel.text = event.name;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Event *event = _allEvents[indexPath.row];
    EventDetailsViewController *controller = [[EventDetailsViewController alloc] initWithEvent:event];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void) addCalendarView{
    _calenderView = [[KalViewController alloc] initWithSelectedDate:[NSDate date]];
    [[self.view viewWithTag:2] addSubview:_calenderView.view]; /* depends on your requirements*/
    _calenderView.view.tag = 200; /* not necessary */
    [_calenderView.view setFrame:self.view.bounds];
    _calenderView.dataSource = self;
    _calenderView.delegate = self;
}

- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate {
    //NSLog(@"%@, %@", fromDate, toDate);
    // filter and pass the array to the events tableview
    [self filterByDateSelected:toDate];
}

-(void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
   /** when selecting a different month **/
}

- (void)removeAllItems
{
    NSLog(@"Items Removed");
    // remove all the previous items from the tableview
}

-(void) filterByDateSelected: (NSDate *)selectedDate
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    NSString *theDate = [dateFormat stringFromDate:selectedDate];
    NSDate *_date = [NSDate dateFromString:theDate usingFormat:@"yyyy-MM-dd"];

    // filter table by selectedDate
    NSArray *_dateFilteredEvents = _allEvents;

    _dateFilteredEvents = [_allEvents filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Event *evaluatedEvent, NSDictionary *bindings) {
        if ([evaluatedEvent.date isEqualToDate:_date]) {
            return YES;
        }
        return NO;
    }]];
    NSLog(@"%@", _dateFilteredEvents);

     //  uncomment the following line if you want to display list in another controller
    //[self showEventsByDate:_dateFilteredEvents];

   // or else refresh table after updating the list
  _allEvents = _dateFilteredEvents;
        [_tableView reloadData];
}

- (void) showEventsByDate:(NSArray*)events
{
    if (events.count > 0) {
        CalendarViewController *_controller = [[CalendarViewController alloc] initWithEventArray:events];
        [self.navigationController pushViewController:_controller animated:YES];
    }
}

- (void) removeCalenderView{
    [_calenderView.view removeFromSuperview];
}

@end


text:
Q: Comparing two tables and get the values that dont match I have two tables with articles.
table 1 article and table 2 articlefm
both tables have one field with artnr.
'table 1' has 2192 artnr and 'table 2' has 2195 artnr.
I want in my query to find out whats the artnr of the 3 articles that is not matched.
If 'table 2' has more articles then 'table 1' then I need a list with those artnr.
How can I make this?

A: You can do this using a FULL JOIN:
SELECT  COALESCE(t1.Artnr, t2.Artnr) AS Artnr,
        CASE WHEN t1.Artnr IS NULL THEN 'Table1' ELSE 'Table2' END AS MissingFrom
FROM    Table1 AS t1
        FULL JOIN Table2 AS t2
            ON t1.Artnr = t2.Artnr
WHERE   t1.Artnr IS NULL
OR      t2.Artnr IS NULL;

Note, that just because there is a difference in the count of 3, it does not necessarily mean that there are only 3 records in one table missing from the other. Imagine the following:
Table1          Table2
------          -------
1               2
2               4
3               6
4

The difference in count is 1, but there are actually 2 records present in table1 that aren't in table2, and 1 in table2 that isn't in table1. Using the above full join method you would get a result like:
Artnr | MissingFrom
------+-------------
  1   |  Table1
  3   |  Table1
  6   |  Table2

A: In most databases you can use except (SQL standard) or minus (Oracle specific):
select artnr
from   articlefm -- table 2
except
select artnr
from   article -- table 1

Else you could try a not in:
select atrnr
from   articlefm -- table 2
where  atrnr not in
       ( select artnr
         from   article -- table 1
       )

This will give you the article numbers that exist in 2, but not in 1.


text:
Q: Random crashes after Nvidia instalation, even before boot! I've recently bought my desktop a PNY Geforce GTX 650 TI Boost so I could play Steam games on Ubuntu. I've also bought a brand-new 500 W power supply unit because my older one wouldn't be able to handle the extra work and didn't have a PCI-e plug.
After carefully installing the hardware, I proceded to install the drivers. In order to do so, I've followed Luis Alvarado's tips from here. Baiscally, it involved installing the nvidia-325 package from the xorg-edgers PPA then running sudo nvidia-xconfig to create a new xorg.conf.
The instalation seems to have gone without errors or even warnings, and my computer was finally able to run resource-intensive games. However, every now and then the computer freezes. To better describe the problem:

*

*The screen always freezes;

*The sound usually goes into a loop (rarely it keeps runnning, indicating that only the screen had freezed);

*There's absolutely no mouse or regular keyboard feedback. 90% of the time I have to Alt+PrtScrn+R+E+I+S+U+B my way through a restart, but sometimes not even that works;

*It seems to occur at random intervals, usually when I'm running Steam games, but sometimes when I'm on Unity, working on spreadsheets and statistics software. What intrigues me is that sometimes it occurs even before the system boots (at the first POST screen, which presents the Geforce card). This makes me wonder whether the problem isn't actually in the hardware itself (which would be a shame, because it costed me a small fortune and I can't return it anymore).

So far, none of these has solved the issue:

*

*Reinstalling the 325 driver;

*Installing older drivers;

*Installing nvidia-settings to see if there were any problems such as overheating (there isn't: the card runs at a comfy 45 Celsius even after extensive work);

*Installing steam-login in an attempt to bypass any issues the card might be having with my onboard Intel graphics.

Since the problem sometimes occur during POST, I guess configuring something on my My CMOS might help. The problem is I'm kind of lost. Here's some settings I think might help (from "Advanced Chipset Features"):

*

*Intel EIST: Enabled (GV3);

*Intel XD Bit: Enabled (when disabled, force the XD feature flag to always return 0)

*Intel VT: Enabled (when enabled, a VMM can utilize the additional HW Caps. provided by Intel Virtualization Tech)

*Memory Hole Remapping: Enabled (allow remapping of overlapped PCI memory above the total physical memory)

*Video Memory Size: 32MB (other options: 64MB and 128MB)

*DVMT Mode: DVMT (other option: fixed)

*DVMT/Fixed Memory Size: 256MB (other options: 128MB and Maximum)

My computer is plugged to a 24' LG TV through an HDMI cable, instead of a regular monitor. Could this be the source of the problem (or worsen it)? Unfortunately, I don't have a computer monitor here to test it. All I know is that even though I feel like I've already read all the "My computer is freezing" questions on Ask Ubuntu, I've run out of ideas on how to diagnose and fix the problem.

A: As you stated. The crashes even come in while booting. You clearly have a hardware problem.  You should fix those before trying anything on the software side.
I have never had trouble with HDMI or heard that this can cause crashes. You have already ruled out heating problem.
You should check if your graphics card and the power cables are all properly connected. Try switching one component after the other. Try a different old graphics card or, if available, the on-board graphics card.

*

*Maybe you can test the Nvidia graphics-card and the PSU in a different computer?

*Also, did you test the CPU temperature? Maybe your CPU heat-sink got a little lose and that is causing the unstable system?

*Did one of your RAM components turn bad? If you have more than one, try to remove one and test again.

*If all this still doesn't single out all the component that runs unstable you will finally have to test the motherboard, which will inevitably mean a lot a work.

Edit added the additional info from the comments.

A: So after 1,5 years of testing it seems I've finally solved this problem. All it took was sheding some light into the issue. Literally.
This is what I was only able to see after putting some bright, direct light into my PCIe slot:

I'm guessing this happened when I first inserted my video card into that slot. The card may have pushed a couple of pins upward, shorting the circuit and causing all those freezes.
The only tool I had to reach that narrow space and try to unjam those wires was a pocket knife. I was half desperate, half okay with the fact that I'd have to get another motherboard if I wanted to game in my machine, so I just went ahead and started shoving that knife in there and pushing those wires back and down, to see if I could put them back in their places. I do not recommend this technique.
My technique had everything to go wrong. However, it did work, and my system's been freeze-free for over a month.


text:
Q: Sample Pandas dataframe based on values in column I have a large dataframe that I want to sample based on values on the target column value, which is binary : 0/1
I want to extract equal number of rows that have 0's and 1's in the "target" column. I was thinking of using the pandas sampling function but not sure how to declare the equal number of samples I want from both classes for the dataframe based on the target column.
I was thinking of using something like this:
df.sample(n=10000, weights='target', random_state=1)

Not sure how to edit it to get 10k records with 5k 1's and 5k 0's in the target column. Any help is appreciated!

A: Also found this to be a good method:
df['weights'] = np.where(df['target'] == 1, .5, .5)
sample_df = df.sample(frac=.1, random_state=111, weights='weights')

Change the value of frac depending on the percent of data you want back from the original dataframe.

A: You can group the data by target and then sample,
df = pd.DataFrame({'col':np.random.randn(12000), 'target':np.random.randint(low = 0, high = 2, size=12000)})
new_df = df.groupby('target').apply(lambda x: x.sample(n=5000)).reset_index(drop = True)

new_df.target.value_counts()

1    5000
0    5000

Edit: Use DataFrame.sample
You get similar results using DataFrame.sample
new_df = df.groupby('target').sample(n=5000)

A: You can use DataFrameGroupBy.sample method as follwing:
sample_df = df.groupby("target").sample(n=5000, random_state=1)

A: You will have to run a df0.sample(n=5000) and df1.sample(n=5000) and then combine df0 and df1 into a dfsample dataframe.  You can create df0 and df1 by df.filter() with some logic.  If you provide sample data I can help you construct that logic.


text:
Q: Android onRequestPermissionsResult method, granResults method come empty I am developing android app and i want write event in Calendar Android.
I run app in Android Emulator with API 26.
I am calling ActivityCompat.requestPermissions method but in response grandResults parameter is empty.
RequestCode parameter is correctly.
This is my code. I am calling this method to request permission:
public void PermisoEscribirCalendario()
    {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_CALENDAR)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_CALENDAR)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, 123);
                }

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_CALENDAR},
                        1234);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }

And response code on callback:
@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1234: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

And I show with an image, how grandResult parameter is empty when come to callback:

I hope you can help me.
Thanks you so much!


text:
Q: Easy admin refuses entity update unless I edit image field I am fixing an existing Symfony 5.4 website running on PHP 8.0.18. The back office is handled by EasyAdmin 3.4.
I can't figure out what's wrong. Like the title says, when I go to edit an "Event" entity, the save buttons won't work at all unless I re-upload a different event picture. No amount of editing the other fields will work, and I can use the save buttons on other entities even if I have made no modification to the entity. I've looked though my configuration and entity setup but so far, I don't get it.
Edit: other entities with ImageField also refuse to be updated unless I've re-uploaded something. I found a temporaty fix by using setRequired(false) in the event crud conf, but an image is definitely required in this case, so I'm just setting myself up for a different kind of failure if I'm not mistaken. Is this really the only way?
Event entity:
<?php

namespace App\Entity;

use App\Repository\EventRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=EventRepository::class)
 */
class Event
{
    // ...

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $src;

    // ...

    public function getSrc(): ?string
    {
        return $this->src;
    }

    public function setSrc(string $src): self
    {
        $this->src = $src;

        return $this;
    }

    // ...
}

Event crud controller:
<?php

namespace App\Controller\Admin;

use App\Entity\Event;
use App\Entity\TranslationString;
use App\Entity\TranslationText;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;

class EventCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Event::class;
    }

    public function configureCrud(Crud $crud): Crud
    {
        return $crud
            ->setSearchFields([
                'date',
                'end',
                'title.fr',
                'title.en',
                'body.fr',
                'body.en',
                'alt.fr',
                'alt.en',
            ])
            ->setDefaultSort(['archived' => 'ASC','date' => 'DESC',]);
    }

    public function configureFields(string $pageName): iterable
    {
        return [
            DateField::new('date'),
            DateField::new('end'),
            TextField::new('titleFr'),
            TextField::new('titleEn')->hideOnIndex(),
            BooleanField::new('isShow'),
            BooleanField::new('archived'),
            TextareaField::new('bodyFr'),
            TextareaField::new('bodyEn')->hideOnIndex(),
            ImageField::new('src')
                ->setBasePath('img/events')
                ->setUploadDir('www/img/events'),
            TextareaField::new('altFr')->hideOnIndex(),
            TextareaField::new('altEn')->hideOnIndex(),
        ];
    }

    public function createEntity(string $Fqcn): Event
    {
        return (new Event)
            ->setAlt(new TranslationText)
            ->setTitle(new TranslationString)
            ->setBody(new TranslationText);
    }
}

A: I had the same problem and I think that the following code will help
public function configureFields(string $pageName): iterable {
    $imageField = ImageField::new('image', 'Image')->setUploadDir('public/uploads/images/')->setBasePath('uploads/images/');
    if ($pageName != 'new') {
        $imageField->setRequired(false);
    }

    return [
        TextField::new('title'),
        $imageField,
        TextEditorField::new('description')->setNumOfRows(20),
        UrlField::new('ticketOfficeLink'),
        AssociationField::new('eventStates')
    ];
}


text:
Q: Laravel 5.1: Relationships with SQLite rowid? I have a SQLite Database from another software wich I need to integrate into my own API. I started with that task (multiple databases) successfully by adding models and relations to my API in Laravel.
But now I came to an point where I cannot continue because I don't know how to build a relationship between 2 tables in that foreign DB by using the "rowid" as key.
What I've tried:
Added a usual relationship to both models like that:
Model A:
Has a column named "BU_ZIMMER" that stores the "rowid" of the other Model (B)
class LdBooking extends Model
{
    protected $connection = 'lodgitDB';
    protected $table = 'b_buchungen';
    protected $primaryKey = 'rowid';
    public $timestamps = false;

    public function rentalunit()
    {
      return $this->belongsTo('App\Models\LodgitDesk\LdRentalunit', 'BU_ZIMMER', 'rowid');
  }
}

Model B: Has the rowid that is linked by other models.
class LdRentalunit extends Model
{
    protected $connection = 'lodgitDB';
    protected $table = 'o_mieteinheit';
    protected $primaryKey = 'rowid';
    public $timestamps = false;

    public function bookings()
    {
        return $this->hasMany('App\Models\LodgitDesk\LdBooking', 'rowid', 'BU_ZIMMER');
    }
}

The Controller: Fetches all data by using the "with()" method. This works perfectly for all "normal links", but not for a link to a SQLite rowid.
public function show($id)
{
    return $this->respond( LdBooking::with('rentalunit')->with('category')->select('rowid', '*')->findOrFail($id) );
}

The Result:

The Problem:
I think the problem is, that the standard query doesn't SELECT the rowid from a table. That's why I usually add them manually to a Eloquent-Query ->select('rowid', '*'). But I don't know how to teach my relationship, that if it's joining the other table by the key "rowid" it needs to SELECT this "rowid" first.
Is there any way to do that? Maybe modify the model? Or is it possible to workaround this problem?
I could not find a valid solution to this yet.
A not so clean solution:
After digging more in the Laravel documentation I found a first solution. In the Controller I changed the query to:
public function show($id)
{
    $booking = LdBooking::with(['rentalunit' => function($query) {
                                        $query->select('rowid', '*');
                                    }])->select('rowid', '*')->findOrFail($id);
    return $this->respond($booking);
}

This fetched me the linked rentalunit and automatically pushed it to the returned result.
But like this it is a bit dirty to write the queries in the controller. I would like to solve this problem in the Model directly, so that in the controller i simply can write ->with('rentalunit'). Anyone knows how to solve this?
Is there a Way

A: Ok I have experimented mor to solve my issue and it looks like I've found a good solution that worked out the way as I wanted it:
Model A:
I changed the Model from my question above and simply added a ->select('rowid','*') there:
class LdBooking extends Model
{
    protected $connection = 'lodgitDB';
    protected $table = 'b_buchungen';
    protected $primaryKey = 'rowid';
    public $timestamps = false;

    public function rentalunit()
    {
      return $this->belongsTo('App\Models\LodgitDesk\LdRentalunit', 'BU_ZIMMER', 'rowid')->select('rowid', '*');
  }
}

Now the same Controller in my Question above returns the rentalunit within my booking without adding extra code! I didn't expect Laravel being so powerful!


text:
Q: How to write/save a lot of data to a node js server? I have a c# software that sends a lot of data stored in collections to a node.js backend, at the moment I encode the data to base64 on the c# end and send it with POST, stored in the body.
            {
                let buff = Buffer.from(req.body.systeminfo, 'base64');
                fs.writeFileSync(file, buff.toString('utf-8'));
            }

This is the code on node, but it messes up the data, at the end, especially larger files, become corrupted with characters like "�" instead of actual data, what should I do?
Also the server should be able to manage data send from multiple users at the same time.
EDIT: Should I convert the data into files and then send files instead?

A: Instead of sending the data as text, I've sent it all as an archive.
let mainFile = req.files.file;
mainFile.mv(path);

The C# end
using (WebClient client = new WebClient())
            {
                //Code
                client.UploadFile(url, filePath);
                client.Dispose();
            }


text:
Q: Is there a simplification for x power log to base (1/x)? Is there a simplification for x^(log base (1/x) of N)?

A: Yes, it's 1 / N (the reciprocal of N), provided of course that both N and x are positive and x != 1.

A: x^(log[1/x](n)) = e^(log[1/x](n)*ln(x)) = e^((ln(n)/ln(1/x))*ln(x)) = e^(ln(n)*ln(x)/(-ln(x)) = e^(-ln(n)) = 1/n


text:
Q: C# - Excel Application is only working on Visual Studio On my APP, when I press one button, my APP generate one excel file by:
Excel.Application xl = new Excel.Application();
Excel.Workbook wb = xl.Workbooks.Open(...);
Excel.Worksheet sheet = wb.ActiveSheet;

This code works when I compile it on Visual Studio. The problem is that, when I publish my code and I paste it on inetpub folder of my server, it doesn't work. When I press the button, the webpage doesn't do anthing (it doesn't show any error). But I know the code is failing on the first line I put above because I was studying it debugging.
I also tested it on my PC (installing IIS, etc) but it doesn't work neither...
Any idea? Thank you.
EDIT:
I saw the following error: Access denied:
The COM class generator for the component with CLSID {00024500-0000-0000-C000-000000000046} could not be retrieved due to the following error: 80070005 Access denied. (Exception of HRESULT: 0x80070005 (E_ACCESSDENIED)).

A: DocumentFormat.OpenXml provides more elegant API than Office excel COM library which requires configuring permissions and installing office on the server.
Add a reference to DocumentFormat.OpenXml Nuget package then add the bellow function in your project, pass your excel file path into it.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static void CreateSpreadsheetWorkbook(string filepath)
    {
        // Create a spreadsheet document by supplying the filepath.
        // By default, AutoSave = true, Editable = true, and Type = xlsx.
        SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

        // Add a WorkbookPart to the document.
        WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        // Add a WorksheetPart to the WorkbookPart.
        WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());

        // Add Sheets to the Workbook.
        Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
            AppendChild<Sheets>(new Sheets());

        // Append a new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
        sheets.Append(sheet);

        workbookpart.Workbook.Save();

        // Close the document.
        spreadsheetDocument.Close();
    }

A: you need to install excel application in your server.


text:
Q: Unbounded function on compact interval? So what are some unbounded function on compact interval, if there is any?
Also, is the function $f:[0,\infty) \to \mathbb R$, $f(x)=x$ continuous?

A: For instance, $f:[-1,1] \rightarrow \mathbb R$ defined as $f(x)=1/x$ if $x\neq 0$ and $f(0)=0$ is defined on a compact domain $[-1,1]$ but it is not bounded.
Recall the Weierstrass theorem:
"Every continuous function on a compact domain has at least one maximum and one minimum"
So negating the above statement we obtain that:
"No maximum or minimum and the function has compact support then it must be discontinuous"
In other words, if you look for an unbounded function (in particular, no maximum or minimum) defined on a compact domain then you must look for a discontinuous function.

A: consider for example
$$f:[0,1]\to \Bbb R\\
f(x) = \begin{cases}
\frac 1x &\text{if} & \frac 1x\in\Bbb N, x\neq 0 \\
0 &\text{otherwise}
\end{cases}$$
which is unbounded on $[0,1]$.


text:
Q: `docker images --digests` with and without tag give different answers I am trying to figure out how to determine the digest of an image on my local machine.
If I ask docker images to tell me about the digests for my image, it will happily tell me the correct answer:
rcv@mymachine:~$ docker images -a --digests docker.myregistry.net/myproject/myimage
REPOSITORY                                TAG          DIGEST                                                                    IMAGE ID       CREATED        SIZE
docker.myregistry.net/myproject/myimage   8.0.0-rc9    sha256:56993a4bdf42a6337c1e9a32603c8758d9a67b42b525c18c6d500b8688f50c47   2198f19aede7   3 days ago     1.84GB

However, if I try asking specifically about the tag I'm interested in it will tell me that there's no digest.
rcv@mymachine:~$ docker images -a --digests docker.myregistry.net/myproject/myimage:8.0.0-rc9
REPOSITORY                                TAG         DIGEST    IMAGE ID       CREATED      SIZE
docker.myregistry.net/myproject/myimage   8.0.0-rc9   <none>    2198f19aede7   3 days ago   1.84GB

I've been alternating between building this image locally, and just pulling it back down from the registry.  Is it possible that docker images is confused, or am I missing some subtle difference between the above two commands?
Thanks!

A: That appears to be a bug in the docker CLI. This shouldn't have any impact on the underlying digest. If you know the image you want to query, it's probably easier to inspect that image for the digest:
$ docker image inspect nginx:latest --format '{{index .RepoDigests 0}}'
nginx@sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36


text:
Q: ERROR - ORA-00907: missing right parenthesis I am new to SQL and i got an error "ERROR - ORA-00907: missing right parenthesis" when i try to run my query, Please do help me out in solving this problem,Please do find the query below
Thanks in advance!
(SELECT
        DISTINCT d.order_key ord,
        d.order_status stat,
        m.order_call_key,
        m.opr_no opr_no,
        m.opr_step_no opr_step_no
    FROM
        owi_order d,
        order_call m
    WHERE
        d.rev_status = 'Complete'
        AND d.order_type_cd <> 'ADPPO'
        AND UPPER(d.pgm_id) = UPPER ('777')
        AND (UPPER(m.init_callbrd_action_cd) IN ('MGWP', 'QWIP', 'RFI', 'RIOT', 'RIPI', 'RIR', 'RJSS', 'RNCR', 'RQAI', 'RSIR', 'RTQA')
        OR (UPPER(m.cmpl_callbrd_action_cd) IN ('MGWP', 'QWIP', 'RFI', 'RIOT', 'RIPI', 'RIR', 'RJSS', 'RNCR', 'RQAI', 'RSIR', 'RTQA')
        OR EXISTS  ( SELECT
            'x'
        from
            order_call_ack a
        where
            a.order_call_key=m.order_call_key
            AND UPPER(a.ackd_callbrd_action_cd) IN ('MGWP', 'QWIP', 'RFI', 'RIOT', 'RIPI', 'RIR', 'RJSS', 'RNCR', 'RQAI', 'RSIR', 'RTQA')
            AND a.active_ind <> 'N'))
        and m.order_key = d.order_key), related_query AS ((SELECT
            s.related_order_key ord,
            s.order_key parent,
            b.order_call_key call_parent,
            o.order_call_key call
        FROM
            related_obj s,
            owi_rep_query b,
            owi_order t,
            order_call o
        WHERE
            s.order_key=b.ord
            AND s.related_order_key = o.order_key
            AND b.stat  IN ('Enqueued','Scheduled','Pulled')
            AND s.related_obj_stat_cd <> 'DL'
            AND s.related_order_key = t.order_key
            AND t.rev_status IN ('Complete')
            AND b.order_call_key <> o.order_call_key
        UNION
        SELECT
            ord,
            to_number(null) parent,
            to_number(null) call_parent,
            order_call_key call
        from
            owi_rep_query)), related_call_query AS (SELECT
        distinct ord,
        parent,
        MAX(call_parent) call_parent,
        call,
        (SELECT
            CASE m.call_status_nm
                WHEN 'Completed' THEN m.cmpl_callbrd_action_cd
                ELSE (SELECT
                    DISTINCT ackd_callbrd_action_cd
                FROM
                    order_call_ack ock,
                    order_call ocaa
                WHERE
                    ock.order_call_key = r.call
                    AND ocaa.order_call_key = r.call
                    AND ocaa.call_status_nm <> 'Completed'
                    AND ock.ack_ts = (SELECT
                        MAX(ack_ts)
                    FROM
                        order_call_ack t
                    WHERE
                        t.order_call_key = ocaa.order_call_key
                        AND t.active_ind <> 'N'))
                END
            FROM
                Order_call m
            WHERE
                m.order_call_key = r.call) call_action
        FROM
            related_query r
        GROUP BY
            ord,
            parent,
            call),
            temp_rslt AS (SELECT
                RPAD(d.order_id,
                32,
                ' ') orderRecordIdTemp,
                TRIM(RPAD(m.acc_cd,
                3,
                ' '))||'/'||TRIM(RPAD(m.acc_pos_cd,
                3,
                ' '))||'/'|| RPAD(DECODE(m.work_loc_cd,
                '..',
                '',
                '...',
                '',
                m.work_loc_cd),
                3,
                ' ') accPosWl,
                LPAD(m.line_no,
                5,
                0) lineNumber,
                RPAD(m.call_id,
                8,
                ' ') callIdVal,
                RPAD(m.order_hld_ind,
                4,
                ' ') orderHldInd,
                RPAD(m.prty_no,
                4,
                ' ') prtyNo,
                RPAD(TO_CHAR(m.call_init_ts,
                'MM/DD HH24:MI'),
                11,
                ' ') callInitTs,
                RPAD(call_action,
                4,
                ' ') callAction,
                RPAD(TO_CHAR(m.ecd,
                'MM/DD HH24:MI'),
                11,
                ' ') ecdVal,
                RPAD(F_SUBPIPES(SUBSTR(REPLACE(NVL(m.remark_txt,
                TO_CLOB(' ')),
                '',
                ' '),
                1,
                40)),
                11,
                ' ') remarkTxt,
                LPAD(TRIM(m.order_call_key),
                40,
                ' ') orderCallKey,
                NVL(call_parent,
                0) call_parent,
                LPAD(a.parent,
                40,
                ' ') rel_key,
                d.order_key order_key,
                RPAD(m.prty_no,
                38,
                ' ') prty_no,
                RPAD(m.call_id,
                10,
                ' ') call_id,
                TRIM(RPAD(m.acc_cd,
                4,
                ' '))||'/'||TRIM(RPAD(m.acc_pos_cd,
                5,
                ' '))||'/'|| RPAD(DECODE(m.work_loc_cd,
                '..',
                '',
                '...',
                '',
                m.work_loc_cd),
                3,
                ' ') acc_pos_wl,
                RPAD(TO_CHAR(m.call_init_ts,
                'MM/DD/YYYY HH24:MI'),
                20,
                ' ') call_init_ts,
                m.opr_no opr_no,
                m.opr_step_no opr_step_no
            FROM
                owi_order d,
                order_call m,
                related_call_query a
            WHERE
                m.order_key=d.order_key
                AND a.ord = d.order_key
                AND m.order_call_key = a.call
                AND m.init_callbrd_action_cd <> 'WIP') SELECT
                RPAD(LPAD(' ',
                (level - 1) * 2) || orderRecordIdTemp,
                32,
                ' ') orderRecordId,
                accPosWl,
                lineNumber,
                callIdVal,
                orderHldInd,
                prtyNo,
                callInitTs,
                callAction,
                ecdVal,
                remarkTxt,
                orderCallKey
            from
                temp_rslt CONNECT
            BY
                PRIOR orderCallKey = call_parent
                AND PRIOR Order_key = rel_key START WITH orderCallKey IN (SELECT
                    b.orderCallKey
                FROM
                    temp_rslt b
                WHERE
                    NOT EXISTS (SELECT
                        'X'
                    FROM
                        temp_rslt v
                    WHERE
                        v.order_key = b.rel_key)
                    AND (SELECT
                        COUNT(g.orderCallKey)
                    from
                        temp_rslt g
                    WHERE
                        g.orderCallKey = b.orderCallKey) = 1)
                ORDER SIBLINGS BY
                    prtyNo,
                    callInitTs,
                    orderRecordIdTemp,
                    callIdVal,
                    orderCallKey

Edit 1: Added code tags !

A: @user2392549 : download and use SQLDeveloper from the Oracle site. Its a freeware and provides a good formatting option with various styles. The query needs be formatted properly and then debugged for the missing parenthesis. Also, SQL Developer gives you the advantage of indicating the line number where the issue is occuring during typo or execution.
Download link : http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html


text:
Q: Using jOOQ multiset or row instead of jsonObject I currently use the below approach to reuse select statement. This approach works really well, but this approach doesn't provide me type safety as it is json function. Therefore, I would like to introduce the same pattern to select query with multiset for nested collection and row for nested single object without jsonObject.
data class FoodRecord(
  val id: UUID,
  val createdAt: Instant,
  val createdBy: UserGeneralRecord,
  val lastModifiedAt: Instant,
  val lastModifiedBy: UserGeneralRecord,
  val name: String
  val synonyms: List<String>
)

data class UserGeneralRecord(
  val id: UUID,
  val nickname: String,
  val role: UserRole
) {

  companion object {
    private val user = JUser.USER

    val select = jsonObject(
      key("id").value(user.ID),
      key("nickname").value(user.NICKNAME),
      key("role").value(user.ROLE)
    )
  }
}

  private val food: JFood = JFood.FOOD
  private val foodSynonym: JFoodSynonym = JFoodSynonym.FOOD_SYNONYM
  private val user: JUser = JUser.USER

  override fun fetch(query: FetchFoodByIdQuery): FoodRecord {
    return ctx.getContext()
      .select(
        jsonObject(
          key("id").value(food.ID),
          key("createdAt").value(food.CREATED_AT),
          key("createdBy").value(
            field(
              select(UserGeneralRecord.select)
                .from(user)
                .where(user.ID.eq(food.CREATED_BY))
            )
          ),
          key("lastModifiedAt").value(food.LAST_MODIFIED_AT),
          key("lastModifiedBy").value(
            field(
              select(UserGeneralRecord.select)
                .from(user)
                .where(user.ID.eq(food.LAST_MODIFIED_BY))
            )
          ),
          key("name").value(food.NAME),
          key("synonyms").value(
            field(
              select(jsonArrayAgg(foodSynonym.SYNONYM))
                .from(foodSynonym)
                .where(foodSynonym.FOOD_ID.eq(food.ID))
            )
          ),
        )
      )
      .from(food)
      .where(food.ID.eq(query.id))
      .fetchOneInto(FoodRecord::class.java)
      ?: throw NoResultFoundException("Food is not found by id: ${query.id}")
  }

I'm looking for a possible approach without using jsonObject as below(the below is not working, but only for showing my idea.)
override fun fetch(query: FetchFoodByIdQuery): FoodRecord {
    return ctx.getContext()
      .select(
        food.ID,
        food.CREATED_AT,
        row(
          select( // This select should be reused (same as lastModifiedBy)
            user.ID,
            user.NICKNAME,
            user.ROLE
          ).from(user)
            .where(user.ID.eq(food.CREATED_BY))
        ).`as`("createdBy"),
        food.LAST_MODIFIED_AT,
        row(
          select( // This select should be reused (same as createdBy)
            user.ID,
            user.NICKNAME,
            user.ROLE
          ).from(user)
            .where(user.ID.eq(food.LAST_MODIFIED_BY))
        ).`as`("lastModifiedBy"),
        multiset(
          select(foodSynonym.SYNONYM).from(foodSynonym)
            .where(foodSynonym.FOOD_ID.eq(food.ID))
        ).`as`("synonyms")
      )
      .from(food)
      .where(food.ID.eq(query.id))
      .fetchOneInto(FoodRecord::class.java)
      ?: throw NoResultFoundException("Food is not found by id: ${query.id}")
  }

A: This may just be a matter of understanding how to compose different elements to achieve what you want. Probably, this would work for you?
field(
  select(
    row(
      user.ID,
      user.NICKNAME,
      user.ROLE
    )
  ).from(user)
   .where(user.ID.eq(food.CREATED_BY))
).`as`("createdBy")

Incidentally, this is also how you'd do this with native PostgreSQL. There's no ROW(SELECT ..) constructor in PostgreSQL or standard SQL, like there's a MULTISET(SELECT ..) constructor.
If you want to reuse the row() expression, just assign it to a local variable or method, like you did in the jsonObject() case.


text:
Q: Streamlit all buttons are the same import streamlit as st
import base64

def custom_button(text='button', bgpng=None, height='height: 225px;', width='width: 225px'):
    with open (bgpng, 'rb') as img:
        convert_img = base64.b64encode(img.read()).decode('utf-8')
    background_img = f"background-image: url('data:image/png;base64, {convert_img}');"

    st.markdown(f"""
    <style>
    div.stButton > button:first-child {{
        {background_img}
        {height}
        {width}
    }}
    </style>""", unsafe_allow_html=True)
    button = st.button(text)
    return button

button1 = custom_button(text='button', bgpng=r'data\pic1.png')
button2 = custom_button(text='button2', bgpng=r'data\pic2.png')

The problem is the following, the last button always determines the properties of the other buttons, in this case the background image of button2 determines the background image of button1. So all buttons have the same background image. How can i solve it?

A: You create x styles for x buttons so the last style is applyed since it's the same priority.
I don't use python but I guess you could set an id for your buttons and apply your styles to #{button_id} (or something like that), or apply inline style like below :

<button style="background-color:orange;">button</button>
<button style="background-color:grey;">button2</button>

A: I found a solution.
If the streamlit code is ready, in the browser, right click, inspect , copy the css selector, then we get the unique button css selector. We need to replace this piece of code:
"div.stButton > button:first-child"
Should be replaced with: "copied css selector"
We have to do it for each button.


text:
Q: how to organize code / when to use classes? The goal is to create a program which will effectively let the user create boolean logic statements (not started ), store those expressions, access them (expression_menu), build them (setup_table) and then evaluate them (truth) then finally test them (in another module).
Given all that, which is a fairly large project for my skills. I'm stuck on how to organize everything. I feel like i might want to be moving towards using classes because it might be easier to keep track of attributes...
Immediately however my problem is that how to transfer around the boolean logic statements, obviously on line 29 i'll get a syntax error because x is undefined (the snippet of code only makes sense in lines 11 through 15.
How can i organize my code here to better suit my goal
def setup_table(variables=2):
    return (list(itertools.product(range(2), repeat = variables)))

def truth(variables=None,expression=None):
    truth_table = []
    for x in setup_table(variables):
        if expression:
            x.append(1)
        else:
            x.append(0)
        truth_table.append(x)
    return truth_table

def expression_menu():
    expression = input('''
    choose your expression:
    1. if ((p and q) or (p or q)) and not(r or not q):
    2. if (p or r) or (q and s):
    3. if (p or r) and ( q or (p and s))

    Expression: ''')
    table = None
    if int(expression) == 1:
        table = truth(variables = 3, expression =((x[0] and x[1]) or (x[0] or x[1])) and not (x[
    print(table)

if __name__ == "__main__":
    import itertools
    expression_menu()

A: You could make your boolean expression into a function.
So:
table = truth(variables = 3, expression = lambda x: (x[0] and x[1]))

or:
def expression(x):
    return x[0] and x[1]
table = truth(variables = 3, expression = expression)


text:
Q: Android: Store data from MySQL Database in an ArrayList How can I retrieve data from MySQL database and store it in an ArrayList?
I have already used php scripts to connect to database and get all the data that I want. The data is sent to the webserver in Json format.
Let's say:
1) I have a table in my database based called users.
2) I have a class in Android Studio also called users that provides all the necessary fields for users. (such as id, name, surname, etc.)
3) I want to create an ArrayList (usersList< users>) that contains all the users from the database.
How can I do that?

A: Use json parsing to convert data from json to array list.
According to your requirement list will contain the different user object after parsing.
json parsing sample code


text:
Q: Show Sticky Post at the top but do not show again in the loop? Regarding wordpress.org - sticky posts are displayed at the top but they also appear again in the loop.
For the main loop on my homepage I want to display the sticky posts at the top BUT I don't want the post to appear again in the loop, otherwise it appears redundant to the visitor.
Problem with the below code is they remove the sticky post from the top.
I want to KEEP the sticky posts at the top
but REMOVE/EXCLUDE it from the loop. Is this possible?
CODE A: This removes sticky post from top
function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'ignore_sticky_posts', true );
    }
}
add_action( 'pre_get_posts', 'mango' );

CODE B: This removes sticky post from both the top AND loop
function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'post__not_in', get_option( 'sticky_posts' ) );
    }
}
add_action( 'pre_get_posts', 'mango' );

A: The sticky posts are prepended on the first paginated part of the home page, so try this:
add_action( 'pre_get_posts', function( $q )
{
    if ( $q->is_home() && $q->is_main_query() && $q->get( 'paged' ) > 1 )
        $q->set( 'post__not_in', get_option( 'sticky_posts' ) );

} );

to remove it from the other paginated parts of the home page.


text:
Q: Как нарисовать гексагон средствами css? Нужно нарисовать гексагон, внутри которого будут указаны контакты. Круг сделать легко - через border-radius, а как сделать гексагон?

A: Вариант 1 (c использованием псевдоэлементов):

.hexagon {
    width: 110px;
    height: 62px;
    background: #fe635e;
    color:#fff;
    position: absolute;
    z-index: 10;
    cursor: pointer;
    margin: 28px;
    text-align: center;
    line-height: 62px;
}

.hexagon:before,
.hexagon:after {
    content: "";
    position: absolute;
    left: 0;
    width: 0;
    height: 0;
}

.hexagon:before {
 top: -28px;
 border-left: 55px solid transparent;
 border-right: 55px solid transparent;
 border-bottom: 28px solid #fe635e;
}
.hexagon:after {
 bottom: -28px;
 border-left: 55px solid transparent;
 border-right: 55px solid transparent;
 border-top: 28px solid #fe635e;
}

hexagon

Вариант 2 (с использованием clip-path):

.hexagon {
    width: 110px;
    height: 110px;
    background: #fe635e;
    color:#fff;
    position: absolute;
    z-index: 10;
    cursor: pointer;
    margin: 28px;
    text-align: center;
    line-height: 110px;

  -webkit-clip-path: polygon(0 25%, 50% 0%, 100% 25%, 100% 75%, 50% 100%, 0 75%);
clip-path: polygon(0 25%, 50% 0%, 100% 25%, 100% 75%, 50% 100%, 0 75%);
}

hexagon

A:

.hexagon{
  width: 200px;
  height: 200px;
  background: #ccc;
  -webkit-clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
}


text:
Q: As a service provider; is SCIM a good replacement for ADFS using SAML We want to provide organisations the ability to integrate their internal Active Directory (AD) with our external cloud product.
Our client has a federation server using ADFS, we understand that for us to work with more than one client on this level, we need to have our own ADFS service. Does this mean we could use SCIM as a replacement?

A: You don't need an ADFS server on your side. Although you could use it, it has a few disadvantages: relatively complex deployment, complex automation, limited protocols support, etc. You will likely spend quite a bit of time tweaking it into doing what you need. Of course this is my own experience with it.
Conceptually, you are right. You need an intermediary (typically called an "Federation Provider" that brokers authentication transactions between your app and any system that knows about users like your customer's ADFS).
You might want to check an alternative that is lighter weight, cloud ready, and easier to extend. Fortunately you have many options:
1- You can use IdentityServer, an open source product that you could deploy next to your service. It's an open source product that you can extend and customize as you see fit; and gives you tons of flexibility. Since it is OSS you can "own" the stack and do whatever you want.
2- You can use Azure AD which is a hosted Federation Provider by Microsoft. It'll work with ADFS and other common providers; but has some limitations. (For example: it won't allow you to easily keep your own user database, it will not normalize user profiles, among some common things you are likely to need).
3- You can use Auth0 which is optimized for scenarios like yours. (Full disclosure: this is the product I work on).
In any case, you can read more about the architecture of scenarios like this here.

A: Chose to go with SimpleSAMLphp - we will accept the provisioning via the API Claims process.  We already have group policies in place which makes the task easier.


text:
Q: Debugging Nodal with VS Code Good afternoon!
I am starting a project with the Nodal.js framework and would like to take advantage of the Node debugging features in VS Code. I can't seem to figure out how to start the application using the debugger because the start command is 'nodal s' and I have tried following the instructions from this tutorial on attaching to process that is already running, but I can't seem to hit any of my break points. Any suggestions would be greatly appreciated.
Thanks!


text:
Q: How to detect the rowspan for same element values? I have the following input:
<input>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>5</cell>
  </row>
  <row>
    <cell>5</cell>
  </row>
  <row>
    <cell>5</cell>
  </row>
  <row>
    <cell>4</cell>
  </row>
</input>

and I would like to have the following output:
<output>
  <row>
    <cell rowspan="4">7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell>7</cell>
  </row>
  <row>
    <cell rowspan="3">5</cell>
  </row>
  <row>
    <cell>5</cell>
  </row>
  <row>
    <cell>5</cell>
  </row>
  <row>
    <cell rowspan="1">4</cell>
  </row>
</output>

It means I would like to add rowspan only if values are the same. But how to compute the value for rowspan?
I did the following:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/">

<output>
  <xsl:for-each select="//input/row">
    <row>
      <cell>
        <xsl:if test="not(preceding-sibling::row[1]/cell = cell)">
          <xsl:attribute name="rowspan">?</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="cell" />
      </cell>
    </row>
  </xsl:for-each>
</output>

</xsl:template>

</xsl:stylesheet>

But I don't know how to compute the number for rowspan.

A:
Maybe I will remove duplicate cells, this is not a problem...

Well, it makes a difference, as you will see.
Here's one way you could look at this:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/input">
    <xsl:variable name="total-rows" select="count(row)" />
    <output>
        <xsl:for-each select="row[not(cell=preceding-sibling::row[1]/cell)]">
            <row>
                <cell>
                    <xsl:if test="cell=following-sibling::row[1]/cell">
                        <xsl:variable name="p1" select="count(preceding-sibling::row)" />
                        <xsl:variable name="next-change" select="following-sibling::row[not(cell=current()/cell)][1]" />
                        <xsl:variable name="p2">
                            <xsl:choose>
                                <xsl:when test="$next-change">
                                    <xsl:value-of select="count($next-change/preceding-sibling::row)" />
                                </xsl:when>
                                <xsl:otherwise>
                                    <xsl:value-of select="$total-rows" />
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:variable>
                        <xsl:attribute name="rowspan">
                            <xsl:value-of select="$p2 - $p1" />
                        </xsl:attribute>
                    </xsl:if>
                    <xsl:value-of select="cell" />
                </cell>
            </row>
      </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

Result, when applied to your example input:
<?xml version="1.0" encoding="UTF-8"?>
<output>
   <row>
      <cell rowspan="4">7</cell>
   </row>
   <row>
      <cell rowspan="3">5</cell>
   </row>
   <row>
      <cell>4</cell>
   </row>
</output>

Note that this constant counting of preceding siblings is not very efficient; hopefully you won't have a very large number of rows.