text:
Q: BigQuery MERGE statement with NESTED+REPEATED fields I need to do a merge statement in BigQuery using a classic flat table, having as target a table with nested and repeated fields, and I'm having trouble understanding how this is supposed to work. Google's examples use direct values, so the syntax here is not really clear to me.
Using this example:
CREATE OR REPLACE TABLE
  mydataset.DIM_PERSONA (
    IdPersona STRING,
    Status STRING,
    Properties ARRAY<STRUCT<
      Id STRING,
      Value STRING,
      _loadingDate TIMESTAMP,
      _lastModifiedDate TIMESTAMP
    >>,
    _loadingDate TIMESTAMP NOT NULL,
    _lastModifiedDate TIMESTAMP
);

INSERT INTO mydataset.DIM_PERSONA
values
  ('A', 'KO', [('FamilyMembers', '2', CURRENT_TIMESTAMP(), TIMESTAMP(NULL))], CURRENT_TIMESTAMP(), TIMESTAMP(NULL)),
  ('B', 'KO', [('FamilyMembers', '4', CURRENT_TIMESTAMP(), TIMESTAMP(NULL)),('Pets', '1', CURRENT_TIMESTAMP(), NULL)], CURRENT_TIMESTAMP(), TIMESTAMP(NULL))
;

CREATE OR REPLACE TABLE
  mydataset.PERSONA (
    IdPersona STRING,
    Status STRING,
    IdProperty STRING,
    Value STRING
);

INSERT INTO mydataset.PERSONA
VALUES('A', 'OK','Pets','3'),('B', 'OK','FamilyMembers','5'),('C', 'OK','Pets','2')

The goal is to:

*

*Update IdPersona='A', adding a new element in Properties and
changing Status

*Update IdPersona='B', updating the existent element
in Properties

*Insert IdPersona='C'

This INSERT works:
MERGE INTO mydataset.DIM_PERSONA TRG
USING (
  SELECT
    IdPersona,
    Status,
    ARRAY(
      SELECT AS STRUCT
        IdProperty,
        Value,
        CURRENT_TIMESTAMP(),
        TIMESTAMP(NULL)
    ) Properties,
    CURRENT_TIMESTAMP(),
    TIMESTAMP(NULL)
  FROM mydataset.PERSONA
) SRC ON TRG.IdPersona=SRC.IdPersona
WHEN NOT MATCHED THEN
INSERT VALUES (IdPersona, Status, Properties, CURRENT_TIMESTAMP(), TIMESTAMP(NULL))

But I would like to build the nested/repeated fields in the INSERT clause, because for the UPDATE I would also need (I think) to do a "SELECT AS STRUCT * REPLACE" by comparing the values of TRG with SRC.
This doesn't work:
MERGE INTO mydataset.DIM_PERSONA TRG
USING (
  SELECT
    *
  FROM mydataset.PERSONA
) SRC ON TRG.IdPersona=SRC.IdPersona
WHEN NOT MATCHED THEN
INSERT VALUES (
  IdPersona,
  Status,
  ARRAY(
    SELECT AS STRUCT
      IdProperty,
      Value,
      CURRENT_TIMESTAMP(),
      TIMESTAMP(NULL)
  ),
  CURRENT_TIMESTAMP(),
  TIMESTAMP(NULL)
)

I get "Correlated Subquery is unsupported in INSERT clause."
Even if I used the first option, I don't get how to reference TRG.properties in the UPDATE..
WHEN MATCHED THEN
UPDATE
SET Properties = ARRAY(
  SELECT AS STRUCT p_SRC.*
    REPLACE (IF(p_SRC.IdProperty=p_TRG.id AND p_SRC.Value<>p_TRG.Value,p_SRC.Value,p_TRG.Value) AS Value)
  FROM SRC.Properties p_SRC, TRG.Properties p_TRG
)

Obv this is wrong though.
One way to solve this, as I see it, is to pre-join everything in the USING clause, therefore doing all the replacement there, but it feels very wrong for a merge statement.
Can anyone help me figure this out, please? :\

A: So, I wanted to share a possible solution, although I still hope there's another way.
As mentioned, I pre-compute what I need with a CTE and a FULL OUTER JOIN, therefore recreating the array of structs I need later on (tables will be relatively small so I can afford it).
MERGE INTO mydataset.DIM_PERSONA TRG
USING (
  WITH NEW_PROPERTIES AS (
    SELECT
      COALESCE(idp,IdPersona) IdPersona,
      ARRAY_AGG((
        SELECT AS STRUCT
          COALESCE(idpro,Id) IdProperty,
          COALESCE(vl,Value) Value,
          COALESCE(_loadingDate,CURRENT_TIMESTAMP) _loadingDate,
          IF(idp=IdPersona,CURRENT_TIMESTAMP,TIMESTAMP(NULL)) _lastModifiedDate
      )) Properties
    FROM (
      SELECT DIP.IdPersona, DIP.Status, DIP_PR.*, PER.IdPersona idp, PER.Status st, PER.IdProperty idpro, PER.Value vl
      FROM `clean-yew-281811.mydataset.DIM_PERSONA` DIP
      CROSS JOIN UNNEST(DIP.Properties) DIP_PR
      FULL OUTER JOIN mydataset.PERSONA PER
        ON  DIP.IdPersona=PER.IdPersona
        AND DIP_PR.Id=PER.IdProperty
    )
    GROUP BY IdPersona
  )

  SELECT
    IdPersona,
    'subquery to do here' Status,
    NP.Properties
  FROM (SELECT DISTINCT IdPersona FROM mydataset.PERSONA) PE
  LEFT JOIN NEW_PROPERTIES NP USING (IdPersona)
) SRC ON TRG.IdPersona=SRC.IdPersona
WHEN NOT MATCHED THEN
INSERT VALUES (IdPersona, Status, Properties, CURRENT_TIMESTAMP(), TIMESTAMP(NULL))
WHEN MATCHED THEN
UPDATE
SET
  TRG.Status = SRC.Status,
  TRG.Properties = SRC.Properties,
  TRG._lastModifiedDate = CURRENT_TIMESTAMP()

This works but I'm pretty much avoiding the syntax to update an array of structs, as what I'm doing is a rebuild and replace operation. Hopefully someone can suggest a better way.

A: Also, while you did not provide your desired output, I was able to create a query based on the objectives you described and your code and with the sample data you provided.
Following the below goals:

*

*Update IdPersona='A', adding a new element in Properties and changing Status

*Update IdPersona='B', updating the existent element in Properties

*Insert IdPersona='C'

Instead of doing a replace and rebuild operation, I used:

*

*MERGE;in order to perform the updates and insert the new rows, such as  IdPersona = "C"

*INSERT: within merge it is not possible to use INSERT with WHEN MATCHED. Thus, in order to add a new Property when IdPerson="A", this method was used after the MERGE operations.

*CREATE TABLE: after using INSERT, the new Properties when IdPersona="A" are not aggregated, since we did not use WHEN MATCHED. So, the final table DM_PERSONA is replaced  in order to aggregate properly the results.

*LEFT JOIN: in order to add the fields _loadingDate and *_lastModifiedDate *, which are not aggregated into the ARRAY<STRUCT<>>.

Below is the query with the proper comments:
#first step update current values and insert new IdPersonas
MERGE sample.DIM_PERSONA_test2 T
USING sample.PERSONA_test2 S
ON T.IdPersona = S.IdPersona

#update A but not insert
WHEN MATCHED AND T.IdPersona ="A" THEN
UPDATE SET STATUS = "OK"

#update B
WHEN  MATCHED AND T.IdPersona ="B" THEN
UPDATE SET Properties = [( S.IdPersona, S.IdProperty,TIMESTAMP(NULL), TIMESTAMP(NULL) )]

#insert what is not in the target table
WHEN NOT MATCHED THEN
INSERT(IdPersona, Status , Properties, _loadingDate, _lastModifiedDate ) VALUES (S.IdPersona, S.Status, [( IdProperty,Value, TIMESTAMP(NULL), TIMESTAMP(NULL))], CURRENT_TIMESTAMP(), TIMESTAMP(NULL));

#insert new values when IdPersona="A"
#you will see the result won't be aggregated properly
INSERT INTO sample.DIM_PERSONA_test2(IdPersona, Status , Properties, _loadingDate, _lastModifiedDate)
SELECT IdPersona, Status,[( IdProperty,Value, TIMESTAMP(NULL), TIMESTAMP(NULL))], CURRENT_TIMESTAMP(), TIMESTAMP(NULL) from sample.PERSONA_test2
where IdPersona = "A";

#replace the above table to recriate the ARRAY<STRUCT<>>
CREATE OR REPLACE TABLE sample.DIM_PERSONA_FINAL_test2 AS(
SELECT t1.*, t2._loadingDate,t2._lastModifiedDate
FROM( SELECT a.IdPersona,
       a.Status,
       ARRAY_AGG(STRUCT( Properties.Id as Id, Properties.Value as Value, Properties._loadingDate ,
Properties._lastModifiedDate AS _lastModifiedDate)) AS Properties
FROM sample.DIM_PERSONA_test2 a, UNNEST(Properties) as Properties
GROUP BY 1,2
ORDER BY a.IdPersona)t1 LEFT JOIN sample.DIM_PERSONA_test2 t2 USING(IdPersona)
)

And the output,

Notice that when updating the ARRAY<STRUCT<>>, the values are wrapped within [()]. Lastly, pay attention that there are two IdPersona="A" because _loadingDate is required, so it can not be NULL and due to the CURRENT_TIMESTAMP(), there are two different values for this field. Thus, two different records.


text:
Q: Differentiate static file and asp.net pages in httpmodule - IIS7 In IIS7 integrated mode, especially in ASP.NET MVC and .NET4, all modules run for all request. runAllManagedModulesForAllRequests="true". making runAllManagedModulesForAllRequests="false" give me headace and too many issue about this until I get confused.
So to make it simple, just let my module accept all request including static file but in the module like BeginRequest, I want to handle only if it is not static file. How to filter or check this condition in module?

A: This doesn't exactly answer your question, but since nobody else has answered, I have what could possibly be part of the solution.
If you split your module into two, one for managed handler requests, and one for everything else, then in your web.config, where you add your "managed handler request" module, you can add the attribute  preCondition="managedHandler".  So it would look like this:
    <system.webServer>
      <modules>
        <add name="DynamicRequestModule" type="..." preCondition="managedHandler" />
        <add name="StaticRequestModule" type="..." />

Given this configuration, the "DynamicRequestModule" module will execute only when the request is for a resource that has a managed handler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert multi select dropdown value into a var by jquery or javascript? I want to insert multi select dropdown value to a var by jquery or javascript.
for example:
<select class="form-control ltr input-md input-group-addon" id="tld" name="tld" multiple="multiple">
    <option value="com" selected="">.com</option>
    <option value="ir">.ir</option>
    <option value="net">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

any help?
Thank you

A: jQuery val() function returns an array when executed on a multiselect dropdown.

var tlds = $("#tld").val();
console.log(tlds);

<select class="form-control ltr input-md input-group-addon" id="tld" name="tld" multiple="multiple">
    <option value="com" selected="">.com</option>
    <option value="ir" selected="">.ir</option>
    <option value="net" selected="">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

A: Try with map().get() method for create the array from element  .Each time you change the selection array was created depend on the selected value.

$('select').change(function(){
var res = $(this).children('option:selected').map(function(){
 return $(this).val()
}).get()
console.log(res)
})

<select class="form-control ltr input-md input-group-addon" id="tld" name="tld" multiple="multiple">
    <option value="com" selected="">.com</option>
    <option value="ir">.ir</option>
    <option value="net">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

A: Iterate over the option and push the values in a array.

var tlds = [];
$("#tld > option:selected").each(function(){
   tlds.push(this.value);
});
console.log(tlds);

<select class="form-control ltr input-md input-group-addon" id="tld" name="tld" multiple="multiple">
    <option value="com" selected="">.com</option>
    <option value="ir" selected="">.ir</option>
    <option value="net" selected="">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

A: Call onChange function every time an option is selected or unselected and push the selected values to the tlds array.

//var tlds = ['info', 'com', 'net', 'org', 'co', 'biz'];
var tlds = [];

function selectTld() {
  tlds = [];
  var vals = $('#tld').val();
  tlds.push(vals);
  $("#selectedValues").html(tlds);
}

tlds.forEach(function(tld) {
  //some work
});

<select class="form-control ltr input-md input-group-addon" id="tld" name="tld" multiple="multiple" onChange="selectTld()">
    <option value="com" selected="">.com</option>
    <option value="ir">.ir</option>
    <option value="net">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

A: May this help you:

var tlds = (function(select) {
  var res = [];

  select.addEventListener('change', function(event) {
    var values = Array
    .prototype
    .map
    .call(event.target.selectedOptions, function(a) {
      return a.value;
    })
    ;

    var old = res.slice();
    res.length = 0;
    res.push.apply(res, values);
    res.onValuesChange && res.onValuesChange(event, old, res);
  });

  return res;
})(document.getElementById('tld'));

tlds.onValuesChange = function(event, oldValues, newValues) {
  console.log({oldValues, newValues});
}
<select id="tld" multiple>
    <option value="com" selected="">.com</option>
    <option value="ir">.ir</option>
    <option value="net">.net</option>
    <option value="org">.org</option>
    <option value="co">.co</option>
    <option value="xyz">.xyz</option>
    <option value="biz">.biz</option>
    <option value="info">.info</option>
    <option value="asia">.asia</option>
    <option value="club">.club</option>
    <option value="us">.us</option>
    <option value="mobi">.mobi</option>
    <option value="name">.name</option>
</select>

A: You can use this for javascript to get the value from the elementId:
var e = document.getElementById("tld");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

And then proceed with a loop, looping through all the options and adding it all to an array.


text:
Q: Issue while working with django ORM or raw sql query list_edit_drivers.html - this is html file for showing data at front end
    $(document).ready(function () {
        $.extend(true, $.fn.dataTable.defaults, {
            columnDefs: [
                {
                    targets: '_all',
                    defaultContent: ''
                }
            ]
        });
        var table = $('#drivers').DataTable({
            "pageLength": 100,
            "serverSide": true,
            "bSearchable":true,
            "dom": 'blfrtip',
            "ajax": "/fleet/dt/editdrivers/?format=datatables&city_id={{city_id}}",
            "columns": [
                 {
                    "data": "employee_id",
                    "mRender": function (data, type, full) {
                        return '' + full.employee_id + '';
123                     }
                },
                {
                    "data": "uber_name"
                },
                {
                    "data": "mobile"
                },
                {
                    "data": "uber_device_no"
                },
                {
                    "data": "aadhar_no",
                    "bVisible": false,
                },
                {
                    "data": "location.name"
                },
                {
                    "data": "status"
                },
                {
                    "data": "id",

                    "bSortable": false,
                    "mRender": function (data, type, full) {

                        return '' + 'Edit' + '';
                    }
                }]
        });
    });

urls.py - ajax call DriverViewSet url and html render list_edit_drivers url
router.register(r'dt/editdrivers', views.DriverViewSet)
path('driver/list_drivers', views.list_edit_drivers, name='list_edit_drivers')

views.py
@method_decorator(login_required, name='dispatch')
class DriverViewSet(viewsets.ModelViewSet):
    queryset = Driver.objects.filter(is_active=1)
    serializer_class = DriverEditListSerializer

    def get_queryset(self):
        queryset = Driver.objects.filter(is_active=1, city_id=self.request.GET.get('city_id'))
        return queryset

@login_required
def list_edit_drivers(request):
    driver = Driver.objects.filter(city_id=request.session['global_city_id'])
    context = {
        'menu_hiring': 'active',
        'submenu_driver_edit_list': 'active',
        'driver': driver,
        'city_id': request.session['global_city_id']
    }
    return render(request, 'hiringprocess/list_edit_drivers.html', context=context)

serializers.py
class DriverEditListSerializer(serializers.ModelSerializer):
    city = CitySerializer(read_only=True)
    location = LocationSerializer()
    class Meta:
        model = Driver
        fields = ( 'id','employee_id','employer', 'name','uber_name','uber_device_no', 'mobile', 'location', 'city','shift','status', 'aadhar_no')

I need to this sql query implement for change logic. i don't need to change existing field name and all, only change logic based on below sql query. raw query or ORM both okay.
    SELECT fleet_driver.id as driver_id, employee_id, uber_name,fleet_driver.city_id, fleet_driver.mobile,uber_device_no,
fleet_location.name as location_name,
fleet_driver.status as driver_status, fleet_hiring.status as hiring_status
from fleet_driver
left join fleet_hiring on fleet_driver.id=fleet_hiring.driver_id
left JOIN fleet_location on
fleet_driver.location_id=fleet_location.id
WHERE (fleet_driver.id<4253 )

sql query output ex.*
models.py
class Driver(BaseModel):
    employee_id = models.CharField(max_length=8,unique=True,null=True, default=True)  name = models.CharField(max_length=255)
    uber_name = models.CharField(max_length=255, null=True, blank=True)
    mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) uber_device_no = models.CharField(max_length=20,null=True,
    blank=True)
    city = models.ForeignKey(City,models.CASCADE,verbose_name='City',null=True, blank=True)
    location = models.ForeignKey(Location,models.CASCADE,verbose_name='Location',null=True, blank=True)
    status = EnumField(choices=['WORKING','ON_LEAVE', 'EXIT', 'REJOINED'], null=True)

class Hiring(BaseModel):
    STATUS_CHOICES = (('', 'Type...'),
                       ('HR Interview Pass', 'HR Interview Pass'),
                       ('HR Interview Fail', 'HR Interview Fail'),
                       ('Driving Test Pass', 'Driving Test Pass'),
                       ('Driving Test Fail', 'Driving Test Fail'),
                       ('Test Not Interested', 'Test Not Interested'),
                       ('Test Pending', 'Test Pending'),
                       ('Training Completed', 'Training Completed'),
                       ('Training Pending', 'Training Pending'),
                       ('Onboard', 'Onboard'),
                       ('Allocation Completed', 'Allocation Completed'))
    status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True)
    driver = models.OneToOneField(Driver,models.CASCADE,related_name='driver',verbose_name='Driver',null=True, blank=True)

A: There is a confusing code in your SQL query you provided.
The id<4253 and id>=4253 refers to all columns, just with an overhead.
I have omitted it.
orm = Driver.objects.filter(
     # because you have written reverse relation in hiring as driver it looks
     # confusing. You might want to refactor it to hriring
     driver__status__in=(
          'Allocation Completed',
          'Training Completed'
     ).filter(
          # id__lt=4253,
          # id__gt=4253
)
print(orm.query)

which spits the following query:
SELECT "drivers_driver"."id", "drivers_driver"."employee_id",
"drivers_driver"."name", "drivers_driver"."uber_name",
"drivers_driver"."mobile", "drivers_driver"."uber_device_no" FROM
"drivers_driver" INNER JOIN "drivers_hiring" ON
("drivers_driver"."id" = "drivers_hiring"."driver_id")
WHERE "drivers_hiring"."status" IN (Allocation Completed, Training Completed)


text:
Q: Trouble combining Two sql queries into one I have a table which contains due dates for individual member records. Each row contains four fields:
 ID     |    Next_Due    |    Next_Due_Missed    |    Amount
=============================================================
  123   |   2010-12-05   |        NULL           |    41.32
  456   |   2010-12-10   |       2010-12-05      |    21.44
  789   |   2010-12-20   |       2010-12-10      |    39.99

ID is the unique id of each MEMBER
Next Due - is the next due day of their regular subscription period
Next_Due_Missed is populated ONLY if there was an error collecting the first round of subscription payment.
Amount is amount owned for subscription.
My goal is to create a sql query that checks if next_due_missed exists and is not null. If it does, use that value as the '$date'. If not, set $date = value of next_due
this is done easily enough except my results are grouped by Next_Due in normal circumstances and will omit next_due_missed if I combine the way I currently am.
Every payment period, there may be 600+ records with next_due equal to the desired date (and 10-15 equal to next_due_missed).
My current query is:
$stmt = $db->prepare("SELECT next_due, next_due_missed FROM table_name WHERE (next_due > CURDATE() OR next_due_missed > CURDATE()) GROUP BY next_due ASC");

This only returns results for next_due however. Omitting the GROUP BY clause returns hundreds of results (while I need to group in this stage).
Similarly at a later point, I will need to break out those individual records and actually create payment records based on the 'next_due' and 'next_due_missed' values.
Any ideas what I am missing?

A: I am not sure the purpose of your GROUP BY other than to get DISTINCT values, but left it in in case you provided a partial query:
SELECT coalesce(next_due_missed, next_due) as EffectiveNextDue
FROM table_name
WHERE coalesce(next_due_missed, next_due) > CURDATE()
GROUP BY coalesce(next_due_missed, next_due)


text:
Q: Symfony2 getting config params in unit test I have a Symfony2 service that is constructed using a parameter from config.yml using dependency injection. I'm now trying to unit test it and find that the unit test does not have access to the container and therefore the service. So I should built one myself using mock data. It would make sense to me if I could now read the config parameter (going first to config_test.yml then config.yml etc etc) but it appears that isn't possible either. This appears to make unit testing a service cumbersome as I would need to code the initialisation parameters into the test instead of the config files.
If there really is no way to construct a service with parameters from config.yml during a unit test, does anyone know the logic as to why it is a Bad Thing™?

A: I found this post, because I needed config parameters in my tests myself. This was the first hit on Google.
However, this is a solution which works. There might be better ones.
<?php

...

require_once(__DIR__ . "/../../../../../app/AppKernel.php");

class MediaImageTest extends WebTestCase
{
    private $_application;
    private $storagePath;

    public function setUp() {
         $kernel = new \AppKernel('test', true);
         $kernel->boot();
         $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
         $this->_application->setAutoExit(false)

         $this->storagePath = $this->_application->getKernel()->getContainer()->getParameter('media_path');
    }

    ...
}

You might look in to this too: Access Symfony 2 container via Unit test?
Is a much cleaner solution accessing the kernel within unit tests.

A: Unit testing is about testing a class in isolation from other classes. To unit test your service you shouldn't need to read anything from the configuration. Just pass a value in your test. In the end, it could potentially work with other values, right?
Of course if there's some logic/validation around the accepted values, you should probably cover it by tests. Think how you'd do it if you were taking this value from the configuration. You simply wouldn't be able to test the behaviour with different values.
If you want to verify if your application is working correctly (your classes collaborate the way you expect), use functional tests or an acceptance testing tool (like Behat).

A: This works for me:
class MyServiceTest extends WebTestCase
{
    public function testCookies()
    {
        $client = static::createClient();

        $myParams = $client->getKernel()->getContainer()->getParameter('my_params');
    }
}

A: I'm using Symfony 3.2.2, but I think that this could work also for you.
It's simply a line:
$export_dir = static::$kernel->getContainer()->getParameter('export_dir');


text:
Q: Loop through ngFor and if the index mod(%) 10 is 0 show seperator I have a component called post and I'm looping through it to show all of the posts that are within an array.
What I'd like to do is separate the post so that after each 10th post it shows a "page separator", something that just says Page X. So like:
post
post
...
post #10
-- Page 2 --
post
post
...
post #20
-- Page 3 --

Here is my HTML:
<post *ngFor="let post of postFeed.reverse()" [postData]="post"></post>

Page {{(i/10)+1}}

but it seems like you cannot do i % 10 != 0 inside the HTML.. any ideas?
It seems like it would be simple, but I can't wrap my head around it.. Thanks!

A: There are several problems with the code.
First of all, you are calling reverse() twice in your template. The reverse method mutates the original array so you actually reverse what you have reversed - not sure if this is what you wanted.
Secondly your template code can result only in uninterrupted list of posts with displayed page indicators at the end, because you first iterate through the array and generate posts, and only after last iteration those page indicators start being iterated and generated.
You can choose easier approach in your template - come up with one container element on which the *ngFor iteration will happen and inside the posts will be with occasional page indicators.

  <post [postData]="post"></post>

 0 && i % 10 == 0">
    Page {{i / 10 + 1}}

If you don't want to use extra wrapping div, use ng-container - it will generated no element in the result document.
As you can see, you can use % in your templates. See more on what you can use in template expressions here in Angular docs.
If you want to see example I have compiled, have a look at it here.

A: You might try adding a function to your component that checks for mod = 0 and using an *ngIf to display result
Your component would have something like this:
isPageBreak(index) {
    if (index > 0 && index % 10 === 0) {
        return true;
    }
    return false;
}

and then your view would look something like this:

  <post [postData]="post"></post>

Page {{(i/10)+1}}

Note... I didn't test any of this code. Just typed it in, so it may not work without tweaks.


text: Q: Android Set links clickable in edittext after pasting I have a note application which supports clickable links. My problem is that links are clickable after I save the note and open it. How I can set the link clickable right after it's pasted? I'm trying to do that with the addTextChangedListener but I can't get it to work.


text:
Q: How to click elements in lightbox using python I'm trying to automate an e-commerce website, after i click 'add to cart' a lightbox will be displayed for user to proceed to view cart and to continue to check out.
Here is my sample code, i think my code doesn't find the button because the lightbox is still loading.
driver.find_element_by_id("qty").send_keys("4")
driver.find_element_by_class_name("add_to_cart_btn").click()

Lightbox loading here
driver.find_element_by_class_name("button_primary").click() #for clicking the view cart
driver.find_element_by_link_text("Proceed to Checkout").click()

A: use the explicit wait method
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.Classname, "add_to_cart_btn")))
element.click();


text:
Q: Spring Batch return is not working so logs and another code does not working I was working Spring Batch for inactive accounts. But the return type doesn't work. In inactiveMemberProcessor log.info("InactiveMemberProcessor execution") doesn't work.
Not only the log but also the code cannot be executed because the return is not possible.
Why does this happen?
package com.capston.chatting.config.batch;

import com.capston.chatting.entity.Member;
import com.capston.chatting.enums.MemberStatus;
import com.capston.chatting.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Configuration
public class InactiveMemberJobConfig {

    private final MemberRepository memberRepository;
    private final JobBuilderFactory jobBuilderFactory;
    private final StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job inactiveMemberJob() {
        return jobBuilderFactory.get("inactiveMemberJob3")
                .start(inactiveJobStep())
                .build();
    }

    @Bean
    public Step inactiveJobStep() {
        return stepBuilderFactory.get("inactiveMemberStep")
                .<Member, Member>chunk(10)
                .reader(inactiveMemberReader())
                .processor(this.inactiveMemberProcessor())
                .writer(this.inactiveMemberWriter())
                .build();
    }

    @Bean
    public ListItemReader<Member> inactiveMemberReader() {
        log.info("InactiveMemberReader execution");
        List<Member> oldMembers = memberRepository
                .findByUpdateDateBeforeAndStatusEquals(LocalDateTime.now().minusYears(1), MemberStatus.ACTIVE);
        for (Member oldMember : oldMembers) {
            log.info("oldMembers = {}", oldMember.getName());
        }
        return new ListItemReader<>(oldMembers);
    }

    @Bean
    public ItemProcessor<Member, Member> inactiveMemberProcessor() {
        log.info("test");
        return new ItemProcessor<Member, Member>() {
            @Override
            public Member process(Member member) throws Exception {
                log.info("InactiveMemberProcessor execution");
                return member.setInactive();
            }
        };
//        return member -> {
//            log.info("InactiveMemberProcessor execution");
//            return member.setInactive();
//        };
    }

    @Bean
    public ItemWriter<Member> inactiveMemberWriter() {
        log.info("InactiveMemberWriter execution");
        return ((List<? extends Member> members) -> {
            memberRepository.saveAll(members);
            log.info("Members : {}", members);
        });
    }
}

Output
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.2)

2022-08-21 20:31:27.400  INFO 10044 --- [  restartedMain] c.capston.chatting.ChattingApplication   : Starting ChattingApplication using Java 11.0.12 on DESKTOP-SHB62PK with PID 10044 (D:\chatting\chatting\build\classes\java\main started by user in D:\chatting\chatting)
2022-08-21 20:31:27.401  INFO 10044 --- [  restartedMain] c.capston.chatting.ChattingApplication   : The following 4 profiles are active: "google", "naver", "kakao", "local"
2022-08-21 20:31:27.423  INFO 10044 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-08-21 20:31:27.423  INFO 10044 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-08-21 20:31:27.799  INFO 10044 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-08-21 20:31:27.832  INFO 10044 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 29 ms. Found 4 JPA repository interfaces.
2022-08-21 20:31:28.160  INFO 10044 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-08-21 20:31:28.165  INFO 10044 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-08-21 20:31:28.165  INFO 10044 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-08-21 20:31:28.239  INFO 10044 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-08-21 20:31:28.239  INFO 10044 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 816 ms
2022-08-21 20:31:28.287  INFO 10044 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-08-21 20:31:28.445  INFO 10044 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-08-21 20:31:28.507  INFO 10044 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-08-21 20:31:28.529  INFO 10044 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-08-21 20:31:28.597  INFO 10044 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-08-21 20:31:28.649  INFO 10044 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-08-21 20:31:28.900  INFO 10044 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-08-21 20:31:28.904  INFO 10044 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-08-21 20:31:29.331  INFO 10044 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@e2a9a2e, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@8f52ad, org.springframework.security.web.context.SecurityContextPersistenceFilter@5d28bf88, org.springframework.security.web.header.HeaderWriterFilter@682aa17e, org.springframework.security.web.authentication.logout.LogoutFilter@4b700064, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@5266a5db, org.springframework.security.web.session.ConcurrentSessionFilter@5f76bf5b, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4a39d06c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6cc78b9b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4bed4ca2, org.springframework.security.web.session.SessionManagementFilter@34652a4a, org.springframework.security.web.access.ExceptionTranslationFilter@33fe6437, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5e47964]
2022-08-21 20:31:29.338  INFO 10044 --- [  restartedMain] c.c.c.c.batch.InactiveMemberJobConfig    : InactiveMemberReader execution
2022-08-21 20:31:29.355 DEBUG 10044 --- [  restartedMain] org.hibernate.SQL                        :
    select
        member0_.member_id as member_i1_3_,
        member0_.created_date as created_2_3_,
        member0_.login_id as login_id3_3_,
        member0_.login_pw as login_pw4_3_,
        member0_.name as name5_3_,
        member0_.role as role6_3_,
        member0_.score as score7_3_,
        member0_.status as status8_3_,
        member0_.update_date as update_d9_3_
    from
        member member0_
    where
        member0_.update_date<?
        and member0_.status=?
2022-08-21 20:31:29.397  INFO 10044 --- [  restartedMain] c.c.c.c.batch.InactiveMemberJobConfig    : oldMembers = resultMember
2022-08-21 20:31:29.398  INFO 10044 --- [  restartedMain] c.c.c.c.batch.InactiveMemberJobConfig    : test
2022-08-21 20:31:29.399  INFO 10044 --- [  restartedMain] c.c.c.c.batch.InactiveMemberJobConfig    : InactiveMemberWriter execution
2022-08-21 20:31:29.518  WARN 10044 --- [  restartedMain] o.s.b.a.batch.JpaBatchConfigurer         : JPA does not support custom isolation levels, so locks may not be taken when launching Jobs. To silence this warning, set 'spring.batch.jdbc.isolation-level-for-create' to 'default'.
2022-08-21 20:31:29.520  INFO 10044 --- [  restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: MYSQL
2022-08-21 20:31:29.529  INFO 10044 --- [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2022-08-21 20:31:29.608  INFO 10044 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-08-21 20:31:29.628  INFO 10044 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-08-21 20:31:29.629  INFO 10044 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : Starting...
2022-08-21 20:31:29.630  INFO 10044 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : BrokerAvailabilityEvent[available=true, SimpleBrokerMessageHandler [org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry@62c1be01]]
2022-08-21 20:31:29.630  INFO 10044 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : Started.
2022-08-21 20:31:29.635  INFO 10044 --- [  restartedMain] c.capston.chatting.ChattingApplication   : Started ChattingApplication in 2.448 seconds (JVM running for 3.017)
2022-08-21 20:31:29.637  INFO 10044 --- [  restartedMain] o.s.b.a.b.JobLauncherApplicationRunner   : Running default command line with: []
2022-08-21 20:31:30.054  INFO 10044 --- [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=inactiveMemberJob3]] launched with the following parameters: [{}]
2022-08-21 20:31:30.189  INFO 10044 --- [  restartedMain] o.s.batch.core.job.SimpleStepHandler     : Step already complete or not restartable, so no action to execute: StepExecution: id=2, version=3, name=inactiveMemberStep, status=COMPLETED, exitStatus=COMPLETED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0, exitDescription=
2022-08-21 20:31:30.255  INFO 10044 --- [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=inactiveMemberJob3]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 128ms
2022-08-21 20:31:30.634  INFO 10044 --- [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=simpleJob]] launched with the following parameters: [{}]
2022-08-21 20:31:30.759  INFO 10044 --- [  restartedMain] o.s.batch.core.job.SimpleStepHandler     : Step already complete or not restartable, so no action to execute: StepExecution: id=1, version=3, name=simpleStep1, status=COMPLETED, exitStatus=COMPLETED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0, exitDescription=
2022-08-21 20:31:30.824  INFO 10044 --- [  restartedMain] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=simpleJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 125ms

A: According to the log message Step already complete or not restartable, so no action to execute, your step does not seem to be executed. So probably that is the reason you are not seeing your log message.
You can set allowStartIfComplete to true on your step and that should work.


text:
Q: The library file name with "lib" head can't be recognized in codeblocks and vs9 compiler This environment is win7, codeblocks,vs9,boost1.52,
I have installed boost library with python library.It generates some library files.Such as "libboost_python-vc90-mt-gd-1_52.lib".
Then I write a test code to compile and link.But an error has occurred: can not open file "boost_python-vc90-mt-gd-1_52.lib".
The VS compiler don't recognized a library file name with "lib" head?How to do it better.

A: Adding a lib prefix at the start of the name is a Linux thing. On Windows there is a .lib at the end instead.
If the library is named "libboost_python-vc90-mt-gd-1_52", you have to give exactly that name to the linker.

A: First of all, Boost uses auto-linking under Windows. Thus, you only need to provide the location of the boost libraries, but not the names themselves.
Second, Boost uses different filenames for statically and dynamically linked libraries. The ones with lib prefix are for static linking, the ones without for dynamic linking.
By default, Boost uses static linking on Windows. Defining BOOST_ALL_DYN_LINK (there are library specific macros as well if you only want to dynamically link certain libraries) will enable dynamic linking.
From your error message, it seems that your project has BOOST_ALL_DYN_LINK enabled (either in the project settings, as a #define or in <boost/config/user.hpp>. If you prefer static linking, make sure to change/remove this setting.
Either way, make sure that the respective binaries are available and that their location (just the directory) is known to the linker.


text:
Q: Python implementation of LDA topic model with Gibbs sampling and burnin + thin options? I am trying to optimize an LDA topic model using collapsed Gibbs sampling. I have been using the ldatuning package in R to optimize the number of topics k:
controls_tm <- list(
  burnin = 1000,
  iter = 4000,
  thin = 500,
  nstart = 5,
  seed = 0:4,
  best = TRUE
)

   num_cores <- max(parallel::detectCores() - 1, 1)

   result <- FindTopicsNumber(my_dfm, topics = seq(40, 100, by = 5), metrics = c("Griffiths2004", "CaoJuan2009", "Arun2010", "Deveaud2014"), mc.cores = num_cores, control = controls_tm, verbose = TRUE)

This is all fine. Now I can run topicmodels in R for a given k with the same controls but it takes ~8 hours to run per model, even on a HPC cluster with 27 cores. I am looking for Python implementations of LDA topic models that I can run with the same controls so that it is consistent with what I used to optimize ldatuning, but faster, because I need to run multiple models to compare perplexity.
I have looked at the lda library in Python which uses Gibbs and takes <1 hour per model. But as far as I can tell, I cannot pass it the burnin or thin parameters.
I have also looked at sklearn.decomposition.LatentDirichletAllocation but it uses variational Bayes instead of Gibbs and it also doesn't look like it accepts burnin or thin anyway. Same goes for gensim (I think -- I am not very familiar with it).
Does this just not exist in Python? Or is there a workaround so that I can run a model in Python with Gibbs sampling and the parameters I want? Thanks!

A: Assuming you won't use online training, have you checked gensim's Latent Dirichlet Allocation via Mallet?

This module allows both LDA model estimation from a training corpus and inference of topic distribution on new, unseen documents, using an (optimized version of) collapsed gibbs sampling from MALLET.


text:
Q: Compare 2 Text Cells/Ignore Null Cells/More Text I have files that we need to track during reviews, we have 2 cells:  Reviewers and Attendees
I need to know if the text matches OR if Attendees contains more text than Reviewers AND ignore null.
This is what I get now:
Reviewers              Attendees              Participation
Smith, Bubba, Toby     Smith, Bubba, Toby           True
                                                    True
Smith, Bubba, Toby     Smith, Bubba, Toby, Fred     False
Smith, Bubba, Toby     Smith, Bubba                 False

I need to get:
Reviewers              Attendees              Participation
Smith, Bubba, Toby     Smith, Bubba, Toby           Equal
                                                    Null
Smith, Bubba, Toby     Smith, Bubba, Toby, Fred     More
Smith, Bubba, Toby     Smith, Bubba                 Less

Not sure if this is possible, or if I need to look at it from a different perspective.
The owners of this spreadsheet are not going to agree to change the format of the Reviewers or Attendees columns.
Any help is GREATLY appreciated!~

A: It is possible:
=IF(AND(A2="",B2=""),"Null",IF(LEN(A2)-LEN(SUBSTITUTE(A2,",",""))=LEN(B2)-LEN(SUBSTITUTE(B2,",","")),"Equal",IF(LEN(A2)-LEN(SUBSTITUTE(A2,",",""))>LEN(B2)-LEN(SUBSTITUTE(B2,",","")),"Less","More")))


text:
Q: Call to undefined function dl() php i am using following PHP version PHP Version 5.4.7. And i am implementing https://github.com/mgdm/OpenCV-for-PHP . But when i try to run the example it says
Fatal error: Call to undefined function dl() in C:\xampp\htdocs\OpenCV\opencv.php on line 5

Here is the Code
<?php
$br = (php_sapi_name() == "cli")? "":"<br>";

if(!extension_loaded('opencv')) {
    dl('opencv.' . PHP_SHLIB_SUFFIX);
}
$module = 'opencv';
$functions = get_extension_funcs($module);
echo "Functions available in the test extension:$br\n";
foreach($functions as $func) {
    echo $func."$br\n";
}
echo "$br\n";
$function = 'confirm_' . $module . '_compiled';
if (extension_loaded($module)) {
    $str = $function($module);
} else {
    $str = "Module $module is not compiled into PHP";
}
echo "$str\n";
?>

A: dl() is disabled by default in PHP 5.3,  as stated on PHP's documentation .
As it suggests, you would want to use the Extension Loading Directives instead.
So you're left with one of three options:

*

*Load the extension through php.ini

*Use a SAPI that supports and loads dl() as a dependency

*Downgrade PHP to 5.2 so that dl() is loaded automatically


text:
Q: SpecFlow throwing error Input string was not in a correct format I have the following line in the feature file
When user changes the ATM: Limit Offline to any amount between '$150 and $520'

which generates the following definition
[When(@"user changes the ATM: Limit Offline to any amount between '(.*)'")]
public void WhenUserChangesTheATMLimitOfflineToAnyAmountBetween(string p0)
{
    _cardOfflineLimitScard.ResetOfflineLimit("ATM");
}

I don't need the string p0, but  if I remove it manually, the step remains bound but during run time I get an error:

Input string not in a correct format

A: You need to escape the dollar sign characters. The string gets interpreted as a regular expression, and the $ matches the end of the string in Regex.
[When(@"user changes the ATM: Limit Offline to any amount between \$([0-9]+) and \$([0-9]+)")]
public void WhenUserChangesTheATMLimitOfflineToAnyAmountBetween(decimal lowAmount, decimal highAmount)
{
    ...
}

Now you can use the numbers in your step definition if you want.
Reference: Using Regular Expressions with The Microsoft .NET Framework.


text:
Q: HasMany relationship of two child Domain Classes in Grails Good Day to all, I am having an Architecture issue with the way I designed my Domain Class.
I have a parent domain class called TxnBatch which has a One to Many relationship with Transactions class, and also two other child class ProcessorTxnBatch and TamsTerminalTxnBatch that extend the TxnBatch class
The logic is that when a transaction is being performed, I first add it to processorTxnBatch.addToTransactions(transactions), After the transaction is processed, I then add it to the Terminal Batch tamsTerminalTxnBatch.addToTransactions(transaction) which is the other child class
The issue now is that when i add the same transaction to the transactions of another Batch, It removes the Transaction from the former Batch I added it to.
Parent Class
  package com.itex.cipg

  class TxnBatch implements Serializable{

static final String OPEN = "OPEN"
static final String CLOSED = "CLOSED"

/**
 *The Batch number of this Transaction
 **Set when the Batch is created
 **/
String batchNo = "0"

 /**
 *The Batch Status of the transaction
 **/
String batchStatus = OPEN
/**
 *The Time this batch was started
 **/
Date startTime
/**
 *The Time this batch was Closed
 **/
 Date lastUpdated
/**
 *The Time this batch was Closed
 **/
Date closeTime
/**
 *The NextSequence Number of this Batch
 **/
Integer seqNo = 1

//Attributes Updated During a payService.updateBatch() Function call in payService
/**
 * The Total Amount of All Transactions
 */
double allTransactionsSum = 0

/**
 * The Total Amount Charged for the Approved Transactions
 */
double approvedTransactionsCharge = 0

/**
 * The Total Amount of Approved Transactions
 */
double approvedTransactionsSum = 0

/**
 * The Total Amount of Declined Transactions
 */
double declinedTransactionsSum = 0

/**
 * The Total Amount of CANCELED Transactions
 */
double canceledTransactionsSum = 0

/**
 * The Total Amount of CANCELED Transactions
 */
double errorTransactionsSum = 0

/**
 * The Total number of ALL Transactions
 */
int allTransactionsCount = 0

/**
 * The Total number of Approved Transactions
 */
int approvedTransactionsCount= 0

/**
 * The Total number of declined Transactions
 */
int declinedTransactionsCount = 0

/**
 * The Total number of canceled Transactions
 */
int canceledTransactionsCount = 0

/**
*The Total Sum of Unprocessed Transactions
*/
int unProcessedTransactionsSum = 0

/**
*The Total number of Unprocessed Transactions
**/
int unProcessedTransactionsCount = 0

/**
 * The Total number of canceled Transactions
 */
int errorTransactionsCount = 0

/**
*The manimun batch Number to reach before closing this Batch
**/
int  maxBatchNoLimit = 100

static hasMany = [transactions: Transaction]

/**
 *The result of this batch
 *as gotten from TAMS when
 *the batch is closed
 **/
String result

//Implements the Constraints of this Object
static constraints = {
    batchStatus()
    batchNo(blank:false)
    seqNo()
    allTransactionsCount()
    unProcessedTransactionsSum()
    unProcessedTransactionsCount()
    allTransactionsSum(display:true)
    approvedTransactionsCount()
    approvedTransactionsSum()
    canceledTransactionsCount(display:true)
    canceledTransactionsSum()
    errorTransactionsCount(display:true)
    errorTransactionsSum(display:true)
    declinedTransactionsCount(display:true)
    declinedTransactionsSum(display:true)
    closeTime(nullable:true)
    result(nullable:true)
}

String toString()
{
    return  batchStatus + "-" + batchNo + ":" + seqNo
}

}

First Child Class
package com.itex.cipg

class ProcessorTxnBatch extends TxnBatch implements Serializable{

/**
*The Server Processor of the Transaction Batch
*
**/
Server server

}

The second child Class
package com.itex.cipg

class TamsTerminalTxnBatch extends TxnBatch implements Serializable{

/**
*The TAMS Terminal this batch belongs TO
**/
    TamsTerminal terminal
}

I will want to add a transaction to the TamsTerminalTxnBatch and also to the ProcessorTxnBatch Please note static hasMany = [transactions:transaction]
After I do
def transaction = new Transaction //arbitrarily creating a Transaction
processorTxnBatch.addToTransactions(transaction)
assert processorTxnBatch.transactions.size() = 1 //true
tamsTerminalTxnBatch.addToTransactions(transaction)
assert tamsTerminalTxnBatch.transactions.size() = 1 //true

assert processorTxnBatch.transactions.size() = 0 //true

I dont Know Why..........Please Kindly Help me out
Though They are stored on the same Table..........Thanks


text:
Q: Python Pygame Font x coordinate I am trying to make a 2d password generator in pygame and I have to ask the user and take text input from the user about how many length in numbers he wants his password to be.
I know that the text input will be short but what if the user types a big string that the text input passes my screen width so my question is how do I detect if the font passes my screen width so from now on whatever the user inputs will get displayed on a new Line because if the text is not in a newline my user wont be able to see what he is entering now.
Here is my text input function:
def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
               thing_x=None, thing_y=None):
    """

    :param x: Defines the x axis or the width position where the text input should be drawn.
    :param y: Defines the y axis or the height position where the text input should be drawn.
    :param color: Defines the color of the text input.
    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
                 char's text on the screen
    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
                   should be drawn.
    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
                   should be drawn.
    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
                 black.
    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
                  Surface.
    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
                    parameter thing should be drawn
    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
                    parameter thing should be drawn.
    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
    """

    characters = ""
    WINDOW.fill(fill)
    if thing is not None:
        draw(thing, thing_x, thing_y)
    if char is not None:
        char_text = str(char)
        char_text_surface = FONT.render(char_text, True, char_color)
        draw(char_text_surface, char_x, char_y, True)
    pygame.display.update()

    while True:
        for detect in pygame.event.get():
            if detect.type == QUIT:
                exit()

            elif detect.type == KEYDOWN:
                if detect.key == K_BACKSPACE:
                    characters = characters[:-1]
                elif detect.key == K_RETURN:
                    global text
                    text = characters
                    return text

                else:
                    characters = characters + detect.unicode

                WINDOW.fill(fill)
                if thing is not None:
                    draw(thing, thing_x, thing_y)
                if char is not None:
                    char_text = str(char)
                    char_text_surface = FONT.render(char_text, True, char_color)
                    draw(char_text_surface, char_x, char_y, True)

                text = FONT.render(f"{characters}", True, color)
                print(char_x)
                draw(text, x, y, True)

If you wonder what the draw function is here is the code for it:
def draw(thing, x, y, update=None):
    """

    :param thing: The object what needs to be drawn on the screen
    :param x: Defines the x axis or the width position where the object should be drawn.
    :param y: Defines the y axis or the height position where the object should be drawn.
    :param update: If the parameter update is not passed we don't update the display.
                   But if the parameter update is passed as True we update the display.
    :return: It returns the object on the display at its specific place or it returns
            the object on the display at its specific place and updates and updates the display based on the parameter
            update.
    """

    if update is True:
        WINDOW.blit(thing, (x, y))
        return pygame.display.update()

    else:
        return WINDOW.blit(thing, (x, y)

If you want to know my full code just ask me I will edit this post:

A: Use pygame.font.Font.size to determine the amount of space needed to render text:
text_width, text_height = FONT.size(text)

The line space of the font can be get with get_linesize
Use this methods to render the text line by line:

def render_text(font, text, color, x, y, max_length = 100, update=False):

    line_y = y
    si = 0
    ei = 1
    while ei < len(text)+1:
        text_width, text_height = font.size(text[si:ei])
        if text_width > max_length:
            text_surf = font.render(text[si:ei-1], True, color)
            WINDOW.blit(text_surf, (x, line_y))
            line_y += font.get_linesize()
            si = ei-1
        ei += 1
    if si < len(text):
        text_width, text_height = font.size(text[si:])
        text_surf = font.render(text[si:], True, color)
        WINDOW.blit(text_surf, (x, line_y))

    if update:
        pygame.display.update()

def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
               thing_x=None, thing_y=None):
    # [...]

    while True:
        for detect in pygame.event.get():
            if detect.type == QUIT:
                exit()

            elif detect.type == KEYDOWN:
                # [...]

                render_text(FONT, characters, color, x, y, 100, True)

A: Each character_text_surface will have a width, you can get this with:
character_text_surface.get_width()
So what you need to do is have a total_width variable, and for each character blitted, add the width of that character to the total_width. Then you can test it like this:
if start_of_input_x + total_width >= screenwidth:
  y += character_text_surface.get_height()


text:
Q: How to prune a transformer? I am trying to reduce memory and speed up my own fine-tuned transformer. I came across the tutorial for pruning on the huggingface site. I am referring to the following snippet. The trainer.train() is missing, so I added it. It ran without error, however, there is no reduction in memory (I used model.get_memory_footprint() and before and after pruning Model memory footprint: 503695916 bytes). Same for inference speed. I also tried out different pruning configurations (global pruning, different pruning types or target sparsities) but it did not help. Can someone help me?
from optimum.intel.neural_compressor import INCTrainer
from neural_compressor import WeightPruningConfig
from transformers import TrainingArguments, Trainer
from transformers.data.data_collator import default_data_collator

pruning_config = WeightPruningConfig(
pruning_type="magnitude",
start_step=0,
end_step=15,
target_sparsity=0.2,
pruning_scope="local",
)

from transformers import TrainingArguments, Trainer
save_dir="prunedModel"

trainer = INCTrainer(
model=model,
pruning_config=pruning_config,
args=TrainingArguments(save_dir, max_steps=500,num_train_epochs=1.0, do_train=True, do_eval=True,metric_for_best_model="f1",greater_is_better=True),
train_dataset=train_dataset,
eval_dataset=eval_dataset,
compute_metrics=compute_metrics,
tokenizer=processor,
data_collator=default_data_collator,
)
train_result = trainer.train() # <-- Added by me
trainer.save_model(save_dir) # <-- Added by me
optimized_model = AutoModelForSequenceClassification.from_pretrained(save_dir)

memory_footprint = optimized_model.get_memory_footprint()
print(f"Model memory footprint: {memory_footprint} bytes")`

Expected behavior
As per the model should be pruned and the actual model without pruned and the pruned model should have different sizes but they have the Model memory footprint:


text:
Q: How to access the string output of a JavaScript function in an MVC 4 razor html url action? I want to be able to pass the string output of my javascript function as a parameter to my MVC 4 Razor Url Action which itself is passed as a custom attribute to the input element. Here is the razor in my view file:
@Html.TextBoxFor(model => model.SomeProperty, new{data_autocomplete = @Url.Action("SomeAction","SomeController", new { someParameter= "here I want the string output of my javascript function" })})

How can I possibly achieve this?

A: I believe this could be done only after the HTML is rendered. The reason behind this is the Razor is mainly used for rendering the HTML. The Javascript could be run upon for a HTML element only its is completely rendered. If I understood your question, you want to dynamically assign the URL which is rendered by the javascript function to the   data_autocomplete property of the textbox. I would suggest you the method below
var currentURL = @Url.Action("SomeAction","SomeController");

var parameters  = YourJSMethodToreturnTheParameterValue();

$("#SomeProperty").attr("data_autocomplete",currentURL+'?someParameter='+parameters;

Ideally, the TextBoxFor would render the Property name as its ID.

A: Try this:
var textbox = document.getElementById('SomeProperty');
var currentUrl = textbox.getAttribute('data_autocomplete');
currentUrl  += '?someParameter=' + myJsFunctionThatReturnsString();
textbox.setAttribute('data_autocomplete', currentUrl);


text:
Q: Duplicate multiple records with one INSERT statement In MS-Access 2019, I'd like to duplicate existing records from tblTest and change one field tLink as a foreign key to another table.
I know how to do it with VBA looping over recordsets, but I'd like to use SQL here.
I assume it can be solved with a single statement, and as SQL-newbie I'm eager to learn how to do it.
So let's assume a simple table tblTest, tID is Primary Key and auto-number
tID    tLink    tName
Long   Long     Text(50)
-----------------------------
1       3       Bill
2      17       Sue
3       9       Tom
4       3       Chris

I'd like to duplicate all records with tLink = 3 and set their tLink to 1.
When snooping around in various tutorials, I learned ...
INSERT INTO tblTest SELECT * FROM tblTest WHERE tID=1

... but this fails because of tID having to be a unique value.
So I am stuck at this point, and removing the primary key from the table is not an option here. Is there a way around it?
So, (1) how to duplicate one record without running into the primary key issue, and then, (2) multiple records with 1 SQL statement?
I would then use UPDATE to set tLink to 1 WHERE tLink=3

A:
I'd like to duplicate all records with tLink = 3 and set their tLink to 1.

If you have an auto-number column, then you can just leave it apart in the insert statement. Access will automatically assign a new value for every inserted row.
What you want should be as simple as:
INSERT INTO tblTest(tLink, tName) SELECT 1, tName FROM tblTest WHERE tLink = 3


text: Q: How to add pre-order functionality for products in woocommerce I am trying to add pre-order functionality for simple and variable products. I got  some plugins but I would like to add it with the help of own functions. How can i achieve it?


text:
Q: Clustered index scan on a foreign key assertion I have a stored procedure that gets executed for any change to the objects in a table A(The stored procedure is triggered by an after update trigger). The stored procedure in turn updates a table B which has a foreign key reference to table A(and another table say Table C) and two indexes.
Now this stored procedure has a parameter passed which is the unique identifier of the table A so any access to the main table A is very row specific i.e it always affects only one row.
The same set up is across multiple projects in our system but the execution plan generated for one specific project is different from the others and I have narrowed down to the source of the issue. The execution plan is exactly the same up to the actual table insert(table B) but differs from there on for the index and foreign key assertions.
Here is a screen shot of a "good plan" where the foreign key assertions are done using a clustered index seek.
Good plan
Here's the execution plan for this particular project where we are seeing a lot of deadlocks and this is because there is a clustered index scan for these foreign key assertions. When I remove the foreign key the issue disappears. Why is there a scan here ? We have indexes on the foreign keys. Also why is the non clustered index inserts expanded in this plan? And what is the sequence operator doing ? I tried RECOMPILE and it generated the same plan with a scan for the foreign key update.
Bad plan


text:
Q: How to disable Browser refresh and back button event in ADF using Java script I want to prevent user to click on browser back or refresh button. so for that i want to disable these events so that user can not reload or refresh or back current page.
Kindly suggest .
Best Regards

A: Asked and answered here on SO.
Disabling the back button in the browser is hard or impossible depending on what you actually want, see here. If you are going to do it in raw JS, then call the JS from ADF, examples here, plus many more examples via google.
ADF includes declarative support for dis-allowing returning into a taskflow that you have navigated out of by setting the taskflow metadata in conjunction with the taskflow return component setting, details here.


text:
Q: Object oriented keywords in Javascript I could see interface,extends,declare keywords has been used in java script libraries

lib.d.ts

as we use in Java.
For example

interface HTMLObjectElement extends HTMLElement, GetSVGDocument { }

Why we can't use those keywords when we would like to apply oo design patterns to Javascript appliccations like Node.js

A: That is a typescript type definition file.
In order to use the same keywords you will need to code your Node.js application on Typescript and have a compiler that transform it into valid javascript.


text:
Q: What is optimal solution to store UUID in Pandas dataframe? I am having a problem to store UUID in Pandas's dataframe after read from CSV. My data is approximately 1 milion rows and the "ID" field is 16 character UUID.
I checked dtype and memory_usage, that columns was"Object" dtype and used 77MB of RAM. May you please guide me how to optimize it? I searched this topic but the result seems not satisfied enough. Thanks
Best Regards
PS: I am using Python 3.7 and Pandas 0.23.4

A: There is not much practical sense in that:
users_ids = orders_df['user_id'].unique().copy()
print("Total user_ids: ", len(np.unique(users_ids)))
print("Total size: ", sys.getsizeof(users_ids))
print("Total size: ", sys.getsizeof(users_ids[0]))

uuid_to_int = {}
next_uuid_int = 0
for uuid in users_ids:
    if uuid not in uuid_to_int:
        uuid_to_int[uuid] = next_uuid_int
        next_uuid_int += 1

def recode_uuid_to_int (uuid) -> int:
    return uuid_to_int[uuid]

print("UUID to int: ", recode_uuid_to_int(UUID('0sb7ff82-4ec5-4c71-9627-ca209e27df5f')))
orders_df['user_id_as_int'] = orders_df['user_id'].apply(lambda x: recode_uuid_to_int(x))
users_ids_recoded = orders_df['user_id_as_int'].unique().copy()
print("After recoding: ", sys.getsizeof(users_ids_recoded))

gives output:
Total user_ids:  [cut]
Total size:  139992
Total size:  56
UUID to int:  1
After recoding:  139992


text:
Q: Why is this GridBagConstraints code not working? Hello so I wanted to add text area, text field and a button to my panel. I wanted area to use 3/4 of height and full width, field to use 1/4 of height and 3/4 of width and a button to use 1/4 height and 1/4 width. I post a pic to show what I want to get. Code for this looks like:
// My JPanel class
public MainPanel() {
   setLayout(new GridBagLayout());
   add(area, new GBC(0, 0, 4, 3).setWeight(4,4).setFill(GBC.BOTH));
   add(field, new GBC(0, 3, 3, 1).setWeight(1,1).setFill(GBC.HORIZONTAL));
}

GBC is my class which inherits from GridBagConstraints class:
public class GBC extends GridBagConstraints {

   public GBC(int gridx, int gridy) {
      this.gridx = gridx;
      this.gridy = gridy;
      weightx = 100;
      weighty = 100;
   }

   public GBC(int gridx, int gridy, int gridwidth, int gridheight) {
      this(gridx, gridy);
      this.gridwidth = gridwidth;
      this.gridheight = gridheight;
   }

   public GBC setFill(int fill) {
      this.fill = fill;
      return this;
   }
}

So the problem is that both area and field take half of height and a button is in the center, hidden under field... Look terrible anyway, how to solve if?

A: weightx and weighty is what specifies how extra space is distributed. In your case, they both have the same value horizontally and vertically which is 100.
Try to set weightx and weighty to 4 for JTextArea and set weightx and weighty to 1 for JTextField
You can check the doc for what does every field do in GridBagConstraints:
http://docs.oracle.com/javase/7/docs/api/java/awt/GridBagConstraints.html

A: That's how it should look like:
add(area, new GBC(0, 0, 4, 3).setWeight(4,4).setFill(GBC.BOTH));
add(field, new GBC(0, 3, 3, 1).setWeight(1,1).setFill(GBC.HORIZONTAL));

Also read about weightx and weighty, cause you're using them in wrong way


text:
Q: Handling Swing focus events with Jython Jython 2.5
I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instance)
from javax.swing import *
from java.awt import *

class Test(JFrame):
    def __init__(self):
        JFrame.__init__(self,
                        'JDesktopPane and JInternalFrame Demo',
                        size=(600, 300),
                        defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.desktop = JDesktopPane()
        self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)

        frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
        panel = JPanel()

        self.label = JLabel('Hello from Jython')
        panel.add(self.label)

        self.textfield1 = JTextField('Type something here',15)
        # self.textfield1.addFocusListener(event.FocusListener())  # ???

        panel.add(self.textfield1)

        self.textfield2 = JTextField('and click Copy', 15)
        panel.add(self.textfield2)

        copyButton = JButton('Copy',actionPerformed=self.noAction)
        panel.add(copyButton)

        frame.add(panel)
        frame.pack()
        self.desktop.add(frame)

        frame.setSelected(1)
        frame.moveToFront()

    def noAction (self, event):
        pass

if __name__ == '__main__':
    test = Test()
    test.setLocation(100, 100)
    test.show()

A: I was just trying to figure this out yesterday myself...tested and works:
from javax.swing import *
from java.awt import *

class Test(JFrame):
    def __init__(self):
        JFrame.__init__(self,
                        'JDesktopPane and JInternalFrame Demo',
                        size=(600, 300),
                        defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.desktop = JDesktopPane()
        self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)

        frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
        panel = JPanel()

        self.label = JLabel('Hello from Jython')
        panel.add(self.label)

        self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus)

        panel.add(self.textfield1)

        self.textfield2 = JTextField('and click Copy', 15)
        panel.add(self.textfield2)

        copyButton = JButton('Copy',actionPerformed=self.noAction)
        panel.add(copyButton)

        frame.add(panel)
        frame.pack()
        self.desktop.add(frame)

        frame.setSelected(1)
        frame.moveToFront()

    def myOnFocus(self,event):
        print "testing..."

    def noAction (self, event):
        pass

if __name__ == '__main__':
    test = Test()
    test.setLocation(100, 100)
    test.show()

A: Cool'n simple. Thank you!
I think that the idiom is
{var} = {constructor}({param}, {event}={function})
tf = JTextField('1.23', focusLost=tf_focus_lost)

Other alternative:
from java.awt.event import FocusListener
class Enfoque(FocusListener):
    '''Add dynamically'''
# Left unimplemented
#    def focusGained(self, event):
#        print 'tf_b Enfoque.focusGained'

    def focusLost(self,event):
        print 'tf_b Enfoque.focusLost'

enf = Enfoque()

tf_b = JTextField('2.34')
tf_b.addFocusListener(enf)


text:
Q: Converting PDF to Dataframe using Python I am trying to convert a pdf to Dataframe, which contains tabular format. I am using Python 3.6.
Please help me to convert the same.
Please follow link for pdf file:
http://centerforcollegeaffordability.org/uploads/component-rankings-2014-v2.pdf

A: I have found a way out. I am using Tabula-py binding and PyPDF2.
I am using PyPDF2 for getting number of pages in PDF and using it to iterate through each page of .pdf file.
And, Tabula is used for extracting data and converting it to dataframe.
Please correct if there is better way to do it.
import pandas as pd
import numpy as np
from tabula import read_pdf_table
import PyPDF2

reader = PyPDF2.PdfFileReader(open('Your Path', mode='rb'))
m = reader.getNumPages()
#print(reader)
print(m)
for i in range(m):
    n = i+1

    if n==1:
        df = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False}, pages=n)
        index = np.where(df[0].isnull())[0]
        sect = df.iloc[index[0]:index[-1]]
        s = []
        headers = []
        for col in sect:
            colnames = sect[col].dropna().values.flatten()
            (s.insert(len(s), colnames))
            pic = [' '.join(s[col])]
            for i in pic:
                headers.append(i)
        print(df)
        df.drop(sect, inplace=True)
        df.columns = headers
        new_df = pd.DataFrame(columns=headers)
        new_df = pd.concat([new_df, df], axis=0, ignore_index=True)

    else:
        df_2 = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False, 'encoding': "ISO-8859-1"}, pages=n)
        df_2.drop(sect, inplace=True)
        df_2.columns = headers
        new_df = pd.concat([new_df, df_2], axis=0, ignore_index=True)

new_df.columns = headers
print(new_df)
new_df.to_csv('Your Path', index=False)

A: You can do something like this:
df = tabula.read_pdf('inputfile.pdf', pages='all')
  for item in df:
    for info in item.values:
      list1.append(info)
  df = pd.DataFrame(list1)
  df.to_excel('outfile.xlsx', sheet_name='Sheet1', index=True)

A: You can simply use:
import tabula

# Read PDF into list of DataFrame
dataframe = tabula.read_pdf("input.pdf", pages='all')

# Read remote PDF into list of DataFrame
dataframe_2 = tabula.read_pdf("https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/arabic.pdf")

# Convert PDF into CSV file
tabula.convert_into("input.pdf", "output.csv", output_format="csv", pages='all')

For more information you can check this blog link:
Click here


text:
Q: Why is awakeFromNib not called when the view is visited again? I would like to know if there is a method equivalent to awakeFromNib.
My app has 2 views and the 2nd view has a subclass (UIView) which I use to draw.
I use a timer which is called from awakeFromNib in order to animate the drawing.
- (void) awakeFromNib
{
    timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:selfselector:@selector(ReDraw) userInfo:nil repeats:YES];
}

- (void) ReDraw
{
    i++;
    [self setNeedsDisplay];
}

Now when i go back to my first view and come back to this view the drawing is still on (awakeFromNib is not called again).
The timer doesn't stop when i go back to the first view. I want the timer to stop when i go back and the drawing to restart when i visit the second view again.
The methods viewdidLoad and initWithFrame: do not work inside the subclass.

A: awakeFromNib, viewdidLoad and initWithFrame are all called during the initialization phase of the object. If the object is already created, those methods will not be called again. You can force a view to draw itself by using the setNeedsDisplay method of the view.


text:
Q: How to get refreshed and new DOM element using Javascript? I am using Web Application to automate using Javascript and selenium. There is a dropdown which has different portals and if I change the value from the dropdown entire page will get changed based on what portal we select. Say, Developer portal, Tester portal etc,.. but URL is same.
I can change the portal easily, but if I try to fetch the elements after changing the portal, I am getting the previous portal elements.
I am using JS with selenium,
String id = (String)jse.executeScript("var x = document.getElementsByTagName(\""+ tag +"\");var e=''; for(i=0; i<x.length; i++) { e+=x[i].innerText + \",\";if(x[i].innerText.trim()===\""+searchObject+"\"){x[i].click();}} return e;");

Note: If I use the refresh action, application navigates back to the previous portal(It is an application behavior).
Is there a way to get the elements?

A: Use mutation observer for the above quest.
// select the target node
var target = document.querySelector('#some-id');
// In your case this will body or the parent where you are adding elements

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation.type);
    });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }

// pass in the target node, as well as the observer options
observer.observe(target, config);

The observer will notify you when some element added or any attribute changed or you have changed the text. If you want to observe only children just remove the other two.


text:
Q: Google Script: How to script an automatic import from a txt in my drive into spreadsheet? I've never used Javascript before and i've been trying for ages to do this but with no luck, and I can't find any previous people trying.
I want to copy the text data straight from this txt document in my drive, it is possible to do this fine manually but I want it to be done daily automatically instead.
The text document;

Boxes Made,3
Target Percentage,34
Hourly Rate,2

If I import this into a spreadsheet with these settings its perfect;
Import Settings
And it imports like this;
After Import
Now I need to try and automate this so that a script imports it automatically.
The script I have so far doesn't work, please help.
Current script;

 function AutoImporter (Source)
{
  var Source = DriveApp.getFilesByName('DailyData.txt');
  var TextContents = Source.copyText();
  var Target = SpreadsheetApp.getActiveSheet();

  Target.appendText(TextContents[1]);
  }

--edit
Some guy just sent me a script that seems closer but still didn't work;

function autoCSV() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getActiveSheet();
  var r=s.getActiveCell();
  var id="DailyData.txt";//<<<<<enter the ID of the text file
  var f3=DriveApp.getFileById(id);
  var lst1=f3.getBlob().getDataAsString().split('\n').map(function(x) {return x.split(',')});
  var ncols=1,i,lst2=[];
  for (i in lst1) {if (lst1[i].length>ncols) ncols=lst1[i].length;}
  for (i=0;i<ncols;i++) lst2.push('');
  for (i in lst1) lst1[i]=lst1[i].concat(lst2.slice(0,lst2.length-lst1[i].length));

  s.getRange(r.getRow(), r.getColumn(), lst1.length, ncols).setValues(lst1);
}

A: You may read text file from Google Drive this way:
'use strict'; // <- Always use strict mode.

function foo() {

  var fileName = 'DailyData.txt';
  var files = DriveApp.getFilesByName(fileName);
  if (!files.hasNext()) {
    throw new Error('No file with name:' + fileName);
  }
  // We take only the first file among all files with such name.
  var file = files.next();
  var text = file.getBlob().getDataAsString('utf8');
  Logger.log(text);
  // Now you have to parse the file.

}

Documentation:

*

*DriveApp.getFilesByName returns collection of Files.

*File.getBlob returns Blob.

*Blob.getDataAsString returns String.


text:
Q: Modify an integer value in a textfile in C Lets say I have a text file like this:
106
60
107
50
108
37

So the 106 107 and 108 are my IDs and the 60, 50 and 37 are stock quantities. And I want to modify the stock quantities like let's say Iadd 30 more to ID:106, so it should be 60+30=90. So my question is, how should I code it so it updates the text file.
I have already tried to scan the file into an array but it doesn't seem to scan the data into the array:
while(fscanf(filename, "%d", array[i]))
{
    i++;
}

I tried that method and it doesn't seem to work. Is there any alternatives with this problem?

A: You cannot easily modify the text file in place because you might need to insert bytes as the numbers grow to more digits.
You should use loop to read the file and write updated contents to a new file:
int update_file(FILE *in, FILE *out, int ref, int delta) {
    int id, quantity;
    int res = 0;

    while (fscanf(in, "%d%d", &id, &quantity) == 2) {
        if (id == ref) {
            quantity += delta;
            res++;
        }
        fprintf(out, "%d\n%d\n", id, quantity);
    }
    return res;
}


text:
Q: MassTransit help registering multiple sagas I'm working on porting an old app to .net6, and ran into an issue with registrering multiple sagas with masstransit.
services.AddMassTransit<IProcessManagerBus>(busCfg =>
{
    busCfg.AddSagaStateMachine<OrderPM, OrderPMState>()
        .EntityFrameworkRepository<OrderPMState>(efConfig =>
        {
            efConfig.ConcurrencyMode = ConcurrencyMode.Optimistic;
            efConfig.DatabaseFactory(() => new OrderStateDbContext(configuration.GetConnectionString("DB")));
        });

    busCfg.AddSagaStateMachine<CsaLoginPM, CsaLoginPMState>()
        .EntityFrameworkRepository<CsaLoginPMState>(efConfig =>
        {
            efConfig.ConcurrencyMode = ConcurrencyMode.Optimistic;
            efConfig.DatabaseFactory(() => new CsaLoginStateDbContext(configuration.GetConnectionString("DB")));
        });

    busCfg.UsingRabbitMq((context, rabbitCfg) =>
    {
        rabbitCfg.UseJsonSerializer();
        rabbitCfg.Host(new Uri(configuration.GetValue<string>("messaging:pm-bus:host-address")), hostCfg =>
        {
            hostCfg.Username(configuration.GetValue<string>("messaging:pm-bus:username"));
            hostCfg.Password(configuration.GetValue<string>("messaging:pm-bus:password"));

            rabbitCfg.ReceiveEndpoint(configuration.GetValue<string>("messaging:pm-bus:receive-queue"), epCfg =>
            {
                epCfg.PrefetchCount = 10;
                epCfg.UseRetry(retryConfig => retryConfig.Exponential(5, TimeSpan.FromMilliseconds(500), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(1)));

                epCfg.ConfigureSagas(context);
            });
        });
    });
});

The OrderPMState works fine, but the CsaLoginPMState gives the following error when triggered: System.InvalidOperationException: The entity type CsaLoginPMState is not part of the model for the current context.
If I comment out the registration of the OrderPMState, the CsaLoginPMState works fine. I suspect, that the 2 sagas are using the same DbContext, despite being registered with their individual DbContext.
OrderStateDbContext
public class OrderStateDbContext : SagaDbContext
{
    public OrderStateDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    protected override IEnumerable<ISagaClassMap> Configurations
    {
        get { yield return new OrderPMStateMapping(); }
    }
}

CsaLoginStateDbContext
public class CsaLoginStateDbContext : SagaDbContext
{
    public CsaLoginStateDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    protected override IEnumerable<ISagaClassMap> Configurations
    {
        get { yield return new CsaLoginPMStateMapping(); }
    }
}

The old version of the app used AutoFac, and the registration was done like this:
builder.Register(x =>
    EntityFrameworkSagaRepository<OrderPMState>.CreateOptimistic(() => new OrderStateDbContext(_configuration.GetConnectionString("DB"))))
    .As<ISagaRepository<OrderPMState>>().SingleInstance();

builder.Register(x =>
    EntityFrameworkSagaRepository<CsaLoginPMState>.CreateOptimistic(() => new CsaLoginStateDbContext(_configuration.GetConnectionString("DB"))))
    .As<ISagaRepository<CsaLoginPMState>>().SingleInstance();

Am I missing something?

A: When using a DbContext, you should be using one of the two configuration methods that are specifically designed for use with DbContext.
 busCfg.AddSagaStateMachine<CsaLoginPM, CsaLoginPMState>()
    .EntityFrameworkRepository<CsaLoginPMState>(efConfig =>
    {
        efConfig.ConcurrencyMode = ConcurrencyMode.Optimistic;

        efConfig.AddDbContext<DbContext, CsaLoginStateDbContext>((provider,builder) =>
        {
            builder.UseSqlServer(configuration.GetConnectionString("DB"), m =>
            {
                m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
                m.MigrationsHistoryTable($"__{nameof(CsaLoginStateDbContext)}");
            });
        });
    });

Or you can add the DbContext separately and use that existing DbContext in the saga:

services.AddDbContext<CsaLoginStateDbContext>(builder =>
    builder.UseSqlServer(configuration.GetConnectionString("DB"), m =>
    {
        m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
        m.MigrationsHistoryTable($"__{nameof(CsaLoginStateDbContext)}");
    }));

services.AddMassTransit(x =>
{
    x.AddSagaRepository<JobSaga>()
        .EntityFrameworkRepository(r =>
        {
            r.ConcurrencyMode = ConcurrencyMode.Optimistic;
            r.ExistingDbContext<CsaLoginStateDbContext>();
        });
});

This is all covered in the documentation.


text:
Q: variable + value macro expansion I tried without any result.
My code looks like this:
#include "stdafx.h"
#include <iostream>

#define R() ( rand() )
#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT() H(S(distinct_name_), R())

int main(int argc, _TCHAR* argv[])
{
    std::cout << CAT() << std::endl;
    std::cout << CAT() << std::endl;
    std::cout << CAT() << std::endl;
    return 0;
}

I would like to get a result like this:
distinct_name_12233
distinct_name_147
distinct_name_435

as a result of concatenating
distinct_name_ (##) rand()

Right now I am getting an error:
term does not evaluate to a function taking 1 arguments.
Is this achievable ??
EDIT:
I finally succeeded after couple of hours. The preprocessor still does strange things I cannot understand completely. Here it goes:
#include "stdafx.h"
#include <iostream>

class profiler
{
public:
    void show()
    {
        std::cout << "distinct_instance" << std::endl;
    }
};

#define XX __LINE__
#define H(a,b) ( a ## b )
#define CAT(r) H(distinct_name_, r)
#define GET_DISTINCT() CAT(XX)
#define PROFILE() \
    profiler GET_DISTINCT() ;\
    GET_DISTINCT().show() ; \

int main(int argc, _TCHAR* argv[])
{

    PROFILE()
    PROFILE()
    return 0;
}

And the output is:
distinct_instance
distinct_instance

Thanks @Kinopiko for __LINE__ hint. :)

A: No, you can't do that. Macros are a compile-time thing and functions are called only at run time, so there's no way you could get a random number from rand() into your macro expansion.

A: I see that a lot of people have already correctly answered this question, but as an alternative suggestion, if your preprocessor implements __TIME__ or __LINE__ you could get a result quite like what you want, with a line number or time concatenated, rather than a random number.

A: What you are actually getting is...
std::cout << distinct_name_rand() << std::endl;

distinct_name_rand() isn't a function, so it fails with a compile error.
Macros don't execute functions during compile time.

A: You must pass run-time computed value to the macro since macro are evaluated at compile-time.
Try:
#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT(r) H(S(distinct_name_), r)

std::cout << CAT(rand()) << std::endl;


text:
Q: Android Libspotify Image Loading SIGSEGV So this particular libspotify error has me a little stumped. My app basically loads a users playlists, and allows users to go into those playlists at which time it populates the track data.
So the problem lies in the function:
sp_image* image = sp_image_create(session,  image_id);
(after calling)
const byte* image_id =  sp_album_cover(album, SP_IMAGE_SIZE_SMALL);
Now this works fine some of the time, but quite often it will pop up with a 'Corrupt memory passed to dlfree(), SIGSEGV' error, which cause. So first thing I looked for is a memory error but theres plenty of free memory and there are no null pointers when this occurs. The call occurs from with the library to libc.so so its much deeper into the library than i can access.
It obviously has something to do with memory but its odd that it could happen after loading 10 tracks or after 400 tracks and stranger yet, from my testing devices, it only happens on the Nexus 4 and Nexus 7 and not on the Galaxy S3, or HTC sensation. First thing that springs to mind is the fact that the N4 & N7 are Qualcomm devices but thats all i have to go on, and probably has nothing to do with anything!
Any help is much appreciated!

A: It's probably libspotify's fault, not yours. This library has never been particularly stable on Android (in fact, Spotify still calls it "beta"), however they will be replacing it soon with a new library similar to the Spotify iOS SDK.
My advice to you would be to not use libspotify unless you are under pressure to ship something right away. The new SDK will likely solve many of the headaches familiar to developers working with libspotify on Android.
Edit: The new Spotify Android SDK is out! You should use it instead of libspotify, it will save you much headache.


text:
Q: Pandas series rename axis failure I am creating Pandas MulitiIndex series from a dict. It succeeds normally but rename_axis fails when dict is empty
series = pd.Series({('a','b','c'):1,('a','d','e'):2}, dtype='float64').rename_axis(['first_column','second_column','third_column'])
series
first_column  second_column  third_column
a             b              c               1.0
              d              e               2.0
dtype: float64

This fails when the dictionary is empty
series = pd.Series({}, dtype='float64').rename_axis(['first_column','second_column','third_column'])
   1237             raise ValueError("Names must be a list-like")
   1238         if len(values) != 1:
-> 1239             raise ValueError(f"Length of new names must be 1, got {len(values)}")
   1240
   1241         # GH 20527

ValueError: Length of new names must be 1, got 3

I could check if the dictionary is empty and create series differently
series = pd.Series({}, dtype='float64', index=pd.MultiIndex.from_tuples([], names=['first_column', 'second_column', 'third_column']))

Wondering if there is better way to create series avoiding the explicit if condition for empty dict.
Thanks