text:
Q: Join two tables and using computed columns I have two simple tables in a database.
The schema looks like this:

I have created an SQL-Fiddle with some example-data.
Link: http://sqlfiddle.com/#!9/c5e87c/2
At first I want to simple query for all Printers that should get connected to a Computer.
I select the table computermapping and query for a ComputerGUID like this:
SELECT PrinterGUID
FROM computermapping
WHERE ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'

This is OK. At second, I want to join the table "computerdefaultprinter".
I use a LEFT JOIN on the ComputerGUID like this:
SELECT computermapping.PrinterGUID
FROM computermapping
LEFT JOIN computerdefaultprinter ON computerdefaultprinter.ComputerGUID = computermapping.ComputerGUID
WHERE computermapping.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'

Also OK.
Finally I want to know, which Printer will be the Default-Printer. A Computer can only have one Default-Printer. Using my sample data in the SQL-Fiddle I want the output to be like this:
PrinterGUID                          | isDefaultPrinter
--------------------------------------------------------
5549f63f-e02f-4685-a976-96b50c299bed | 1
957b7233-e590-4e7d-aed6-aee0573fc3a8 | 0
5106f1f7-068f-463f-9b76-7cc0ba017184 | 0

I used something in the past like:
SELECT computermapping.PrinterGUID, ( computerdefaultprinter.PrinterGUID IS NOT NULL) as isDefaultPrinter
...

But I can't get it to work anymore. I haven't used SQL for some years now.
Currently I am using MySQL, if this is important.
Could you please help me to solve this?
Thank you.
PS: I had problems to find an adequate title for my request. I don't know if using "computed columns" mentioned in the title is correct.

A: You are missing the condition that relates the PrinterGUIDs of the 2 tables in the ON clause:
SELECT m.PrinterGUID,
       p.PrinterGUID IS NOT NULL AS isDefaultPrinter
FROM computermapping AS m LEFT JOIN computerdefaultprinter AS p
ON p.ComputerGUID = m.ComputerGUID AND p.PrinterGUID = m.PrinterGUID
WHERE m.ComputerGUID = '5bec3779-b002-46ba-97c4-19158c13001f'

See the demo.
Results:
> PrinterGUID                          | isDefaultPrinter
> :----------------------------------- | ---------------:
> 5549f63f-e02f-4685-a976-96b50c299bed |                1
> 957b7233-e590-4e7d-aed6-aee0573fc3a8 |                0
> 5106f1f7-068f-463f-9b76-7cc0ba017184 |                0


text:
Q: Bootstrap session timeout, reset timer outside https://github.com/orangehill/bootstrap-session-timeout
There is the jquery plugin we use with such initialization in the _Layout.cshtml
 $(document).ready(function () {
                $.sessionTimeout({
                    keepAliveUrl: '/Account/KeepSessionAlive/',
                    logoutUrl: '/Account/LogOff/',
                    redirUrl: '/Account/SessionExpired/',
                    ignoreUserActivity: true,
                    warnAfter: 700000,
                    redirAfter: 720000,
                    countdownBar: true,
                    keepAliveInterval: 1000000
                });
            });

So, we don't pay attention to user activity and popup appears always in the same time.
But now, we have 3rd party thing (line online chat in the separate window).
So if user only chatting, timer ends and bootstrap popup shown.
The task is not only to send ping to KeepSessionAlive method of the controller, but also to reset timer inside the session timeout plugin.
For example plugin's popup appears on 11min30sec if do not touch anything. If for example on the 2 minute i update the timer and post ping, then popup should appear on 13min30sec.
Here is event listener from that 3rd party chat:
window.addEventListener('message', function (event) {
                    // Ping server and update timer here
                });

Please suggest the solutions. Thank you

A: Fixed that with event handling
How to trigger event in JavaScript?
But would be nice to hear another solutions, because spent almost the whole day with this :(

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to group rows in htmldatatable? How to group rows in htmldatatable?
I am using JSF.
A short example :
TransNum   TransAmount   InvoiceNum   InvoiceAmount

   1                50          1              10
   1                50          2              15
   1                50          3              30
   2                10          1               6
   2                10          2               5

If I select Grouping column as "InvoiceNum" then the table should look like:-
(i.e Grouping is done on InvoiceNum):
TransNum   TransAmount   InvoiceNum   InvoiceAmount
                               1
  1                50          1              10
  2                10          1               6
                               2
  1                50          2              15
  2                10          2               5
                               3
  1                50          3              30

TransNum   TransAmount   InvoiceNum   InvoiceAmount
Similarly, grouping can be done based on multiple columns values too.
Thanks in advance.

A: JSF h:dataTable has no built-in grouping.
Either you find a component that fits your needs in one of the component libraries, such as Primefaces, Richfaces or Icefaces.
Or you have to implement it yourself in the backing bean by sorting the list in the way you want.


text:
Q: how to link to url in service from itemclick handler mx:list so this one has stupped me cant find a good explanation anywhere, so i have a php service which provides an array of objects in binary back to my flash application. the service is fed into an mx:list, the sevice has 4 fields countrycode, citycode, city, and url. what i need to do is to call the url for each object and feed it to this itemClickHandler this is what i have tried plus the other two others on RIAstar's answer what am i doing wrong here?,
protected function citylist_itemClickHandler(event:ListEvent):void
    {
        var data:City = citylist.selectedItem as City;
        navigateToURL(new URLRequest(data.url));

    }

this is the mx:list with getCitysResult as the objects
    <mx:List includeIn="data" x="28" y="10" width="312" height="255" id="citylist" dataProvider="{getCitysResult.lastResult}" labelField="city" itemClick="citylist_itemClickHandler(event)">
    </mx:List>

what i need to do is get each row of this list to have a url link for the Mouse click

A: The ListEvent has a property rowIndex which carries the index of the row that was just clicked. You can use this index to retrieve the correct element from the dataProvider.
var city:City = cityList.dataProvider.getItemAt(event.rowIndex) as City;
navigateToURL(new URLRequest(city.url));

or directly on the service result object (which is the same, since it's bound):
var city:City = getCitysResult.lastResult.getItemAt(event.rowIndex) as City;

(unless that lastResult object is an Array: then it would be getCitysResult.lastResult[event.rowIndex])
or (the shortest way) use the List's selectedItem property:
var city:City = cityList.selectItem as City;


text:
Q: is it possible to customize shortcode in theme -or- make new shortcode combining two shortcodes I'm sorry if i asking stupid question because as i not code /php expert ?
I usering gravityview to filter and display gravity from values.

[gravityview id="111" search_field="11" search_value="xyzes"]

Now I want to change search_value dynamically AS "current logged in user"
So I trying making new SHORTCODE but not good working or not good idea
add_shortcode( 'customcode' , 'wp_get_current_user_func' );

function wp_get_current_user_func( $atts ) {
    $current_user = wp_get_current_user();

    return do_shortcode('[gravityview id="1111" search_field="16" search_value="$current_user = wp_get_current_user();"]');
}

MY Request please suggest me what right code or is there any way in backend I able to do as altering theme file?
Thank you so much in advance

A: You were close enough. Here is how you should do it:
add_shortcode( 'customcode' , 'wp_get_current_user_func' );

function wp_get_current_user_func( $atts ) {
$current_user = wp_get_current_user();
$user_login = $current_user->user_login;
//return do_shortcode('[gravityview id="1111" search_field="16" search_value=".$user_login."]');
$shortcode = sprintf(
'[gravityview id="%1$s" search_field="%2$s" search_value="%3$s"]',
"1111",
"16",
$user_login
);
echo do_shortcode( $shortcode );
}

You were missing to retrieve $current_user->user_login from function wp_get_current_user()
$user_login = $current_user->user_login;

You can also print out the other values as in this example:
<?php
    $current_user = wp_get_current_user();
    /**
     * @example Safe usage: $current_user = wp_get_current_user();
     * if ( !($current_user instanceof WP_User) )
     *     return;
     */
    echo 'Username: ' . $current_user->user_login . '
';
    echo 'User email: ' . $current_user->user_email . '
';
    echo 'User first name: ' . $current_user->user_firstname . '
';
    echo 'User last name: ' . $current_user->user_lastname . '
';
    echo 'User display name: ' . $current_user->display_name . '
';
    echo 'User ID: ' . $current_user->ID . '
';
?>


text:
Q: get data from unlimited nested array of objects I got this data structure:-
interface DataType {
  level: number;
  type: string | number | arrayString | arrayNumber | arrayObj | obj;
  key: string;
  value: any;
  children: number[] // will store index of children
}

const data = [
  { level: 1, type: 'obj', key: 'obj1', value: {}, children: [1, 2] },
  { level: 2, type: 'string', key: 'obj1 child', value: 'child string', children: [] },
  { level: 2, type: 'obj', key: 'obj1 child obj', value: {}, children: [3] },
  { level: 3, type: 'obj', key: 'obj1-1', value: {}, children: [4] },
  { level: 4, type: 'obj', key: 'obj1-1-1', value: {}, children: [5] },
  { level: 5, type: 'string', key: 'obj1-1-1-1', value: 'last nest', children: [] },
]

Currently I'm trying to delete selected row & it's children. But in the same time also need to delete children's children's child... of selected row.
A. I only successfully able to delete selected row & it's direct children with the code below.
// let say current we inside .map of above data array of objects
// thus, we gonna have 'item' & 'index`

<button
  onClick={(): void => {
    let index2Delete: number[] = []

    data.forEach((item2, index2) => {
      if(index2 === index) {
        // include curr data index to be deleted later
        index2Delete.push(index2)

        // include children indexes to be deleted if have any
        if(item2.children.length > 0) {
          index2Delete = [...index2Delete, ...item2.children]
        }
      }
    })

    // filter those that need to be deleted
    const filtered = data.filter((item2, index2) => !index2Delete.includes(index2))

    // update new data list
    handleUpdateNewDataList(filtered)
  }}
>
  Delete
</button

B. But unsuccessful when trying to do recursive way. Got exceed limit something
// let say current we inside .map of above data array of objects
// thus, we gonna have 'item' & 'index`

<button
  onClick={(): void => {
    let index2Delete: number[] = []

    const repeatThis = (mainIndex: number) => {
      data.forEach((item2, index2) => {
        if(index2 === mainIndex) {
          // include curr data index to be deleted later
          // check first if already include index, since we're repeating this func
          if(!index2Delete.includes(index2))
            index2Delete.push(index2)

          // include children indexes to be deleted if have any
          if(item2.children.length > 0) {
            index2Delete = [...index2Delete, ...item2.children]

            // check if children got their own children
            item2.children.forEach((item3, index3) => {
              const childInfo = data.find((item4, index4) => index4 === item3)

              if(childInfo?.children.length > 0)
                repeatThis(index3)
            })
          }
        }
      })
    }
    // run for main index
    repeatThis(index)

    // filter those that need to be deleted
    const filtered = data.filter((item2, index2) => !index2Delete.includes(index2))

    // update new data list
    handleUpdateNewDataList(filtered)
  }}
>
  Delete
</button

How can I adjust my code to make this work?

A: Here is my solution. First I created a function which calls out the levels I want to delete.
For children, I called a recursive approach in which I also check that nested children won't repeat again and again to get infinite loop.
let data = [
    { level: 1, type: 'obj', key: 'obj1', value: {}, children: [1, 2] },
    { level: 2, type: 'string', key: 'obj1 child', value: 'child string', children: [] },
    { level: 2, type: 'obj', key: 'obj1 child obj', value: {}, children: [3] },
    { level: 3, type: 'obj', key: 'obj1-1', value: {}, children: [4] },
    { level: 4, type: 'obj', key: 'obj1-1-1', value: {}, children: [5] },
    { level: 5, type: 'string', key: 'obj1-1-1-1', value: 'last nest', children: [] },
];
const levelToDelete = [];

const deleteChildrenData = (data, children, curr) => {
 //   console.log('CHILDREN', children);
   children.forEach(c => {
      levelToDelete.push(c);
      const childIndexes = [];
      data.forEach((d, indx) => {
          if (d.level === c && curr.level !== c) {
             childIndexes.push(indx);
          }
      });
      if (childIndexes.length) {
           childIndexes.forEach(innerC => {
            console.log('DATA INNER C,', data[innerC]);
            const nestedChildren =  data[innerC].children.filter(c => c !== curr.level);
           if (nestedChildren.length > 0) {
            deleteChildrenData(data, nestedChildren, data[innerC]);
          }
        });
    }
   });
}

const deleteData = (data, index) => {
    data.forEach((curr, innerIndex) => {
        if (innerIndex === index) {
            levelToDelete.push(curr.level);
            if (curr.children.length && curr.type === 'arrObj' || curr.type === 'obj') {
                const filteredChildren = curr.children.filter(c => c !== curr.level);
                deleteChildrenData(data, filteredChildren, curr);
            }
        }
    } )
}

deleteData(data, 0, []);
  // filter those that need to be deleted
  console.log(levelToDelete);
 const filtered = data.filter((item2, index2) => !levelToDelete.includes(item2.level))

console.log(filtered);


text:
Q: What kind of design pattern am I looking for and how do I implement this in python I am trying to give a slight amount of genericness to my code . Basically what I am looking for is this .
I wish to write an API interface MyAPI :
class MyAPI(object):
    def __init__(self):
       pass

    def upload(self):
       pass

    def download(self):
      pass

class MyAPIEx(object):
   def upload(self):
      #specific implementation

class MyAPIEx2(object):
   def upload(self)
    #specific implementation

#Actual usage ...
def use_api():
     obj = MyAPI()
     obj.upload()

SO what I want is that based on a configuration I should be able to call the upload function
of either MyAPIEx or MyAPIEx2  . What is the exact design pattern I am looking for and how do I implement it in python.

A: You are looking for Factory method (or any other implementation of a factory).

A: Its really hard to say what pattern you are using, without more info. The way to instantiate MyAPI is indeed a Factory like @Darhazer mentioned, but it sounds more like you're interested in knowing about the pattern used for the MyAPI class hierarchy, and without more info we cant say.
I made some code improvements below, look for the comments with the word IMPROVEMENT.
class MyAPI(object):
    def __init__(self):
       pass

    def upload(self):
       # IMPROVEMENT making this function abstract
       # This is how I do it, but you can find other ways searching on google
       raise NotImplementedError, "upload function not implemented"

    def download(self):
       # IMPROVEMENT making this function abstract
       # This is how I do it, but you can find other ways searching on google
       raise NotImplementedError, "download function not implemented"

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it
class MyAPIEx(MyAPI):
   def upload(self):
      #specific implementation

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it
class MyAPIEx2(MyAPI):
   def upload(self)
      #specific implementation

# IMPROVEMENT changed use_api() to get_api(), which is a factory,
# call it to get the MyAPI implementation
def get_api(configDict):
     if 'MyAPIEx' in configDict:
         return MyAPIEx()
     elif 'MyAPIEx2' in configDict:
         return MyAPIEx2()
     else
         # some sort of an error

# Actual usage ...
# IMPROVEMENT, create a config dictionary to be used in the factory
configDict = dict()
# fill in the config accordingly
obj = get_api(configDict)
obj.upload()


text:
Q: Many-to-one relationship in Hibernate I would like to establish a relationship many-to-one between two fields on database. I am using PostgreSQL database and Hibernate. The tables are ApplicationField and Device. The first one has 2 columns: AppFieldId and Name. The second one has NodeId, Description and AppFieldId. The hibernate mapping for ApplicationField is:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 05-may-2011 13:21:52 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.cartif.database.ApplicationField" table="APPLICATIONFIELD">
    <id name="iAppFieldId" column="applicationfieldid" type="java.lang.Integer">
        <generator class="sequence">
            <param name="sequence">s_applicationfield</param>
        </generator>
    </id>
    <property column="name" lazy="false" name="name" type="java.lang.String"/>
    <set name="devices">
        <key column="appfieldid" />
        <one-to-many column="nodeid" class="com.cartif.zigbee.device.Device"/>
    </set>
</class>
</hibernate-mapping>

And for Device:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                               "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 07-abr-2011 13:29:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.cartif.zigbee.device.Device" table="Device">
    <id column="nodeid" name="iIdentifier" type="java.lang.Integer"/>
    <property column="description" generated="never" lazy="false" name="description" type="java.lang.String"/>
    <set name="appField">
        <key column="nodeid"/>
        <many-to-one column="appfieldid" class="com.cartif.database.ApplicationField"/>
    </set>
</class>
</hibernate-mapping>

On Java classes I have a List devices on ApplicationField class and ApplicationField appField on Device class. However, when I try to create a sessionFactory, I obtain an exception like:
org.xml.sax.SAXParseException: Attribute "column" must be declared for element type "one-to-many".

How should I do the relationship between the tables?
Thanks a lot!!

A: I guess the relationship is as follow:
One ApplicationField has many Devices.
  One Device can refer to Many ApplicationField.
If It is true, then there are some mistakes in your mapping.
Replace devices set with following (change in Id column):
<set name="devices">
        <key column="applicationfieldid" />
        <one-to-many class="com.cartif.zigbee.device.Device"/>
</set>

Update many-to-one mapping as:
<many-to-one name="appField" column="applicationfieldid" class="com.cartif.database.ApplicationField"/>


text:
Q: Finding partial strings using str.find() then replace values from dictionary I need to replace the values from a column. The values from the column need not to be exact match, so I use str.find(). Once it scanned the string, it should replace the values from the dictionary.
I achieved the desired result for one instance, but I need to do it multiple times.
I tried creating a function but it didn't work. It only worked for the last dictionary value.
dictionary  = {"AA" : "111", "BB" : "222", "CC": "333,444"}

#result = []
for k, v in dictionary.items():
    df["renamed"] = np.nan
    df.loc[(df["combined_topic"].str.find(k) != -1), "renamed"] = v
    #result.extend(df["renamed"].to_dict(orient="records"))

How should I fix my code? or can you suggest more efficient way to replace multiple values.
Expected output:
combined_topic          renamed
AA, harvard                 111
Diliman, Technology, BB     222
Cat, Dog, CC, Bull          333, 444
``

A: Use Series.str.extract for get first matched value of dictionary and then Series.map by dict:
pat = '|'.join(dictionary)
df['renamed'] = df['combined_topic'].str.extract('('+ pat + ')', expand=False).map(dictionary)
print (df)
            combined_topic  renamed
0              AA, harvard      111
1  Diliman, Technology, BB      222
2       Cat, Dog, CC, Bull  333,444

Your solution houl be used with Series.str.contains, but mainly remove df["renamed"] = np.nan, because data are always overwritten in each loop:
for k, v in dictionary.items():
    df.loc[df["combined_topic"].str.contains(k), "renamed"] = v

Or:
for k, v in dictionary.items():
    df.loc[(df["combined_topic"].str.find(k) != -1), "renamed"] = v


text:
Q: How to solve the error "Fatal Error : Main Unable to start the activity" I've been trying to run this app but it throws the same error every time, I've tried everything I could. I would really like an expert's help over this.
This is a simple app to calculate and play with numbers in some manner idk if I should provide the .xml files too but I definitely will if they are needed.
   public class MainActivity extends AppCompatActivity {

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

            final EditText e1=(EditText) findViewById(R.id.name);
            final EditText e2=(EditText)findViewById(R.id.date);
            final EditText e3=(EditText)findViewById(R.id.month);
            final EditText e4=(EditText)findViewById(R.id.year);
            Button b=(Button) findViewById(R.id.button);

            char[] n = e1.getText().toString().toCharArray();
            int date = Integer.parseInt(e2.toString());
            int month = Integer.parseInt(e3.toString());
            int year = Integer.parseInt(e4.toString());
            int nn = 0;
            int driver=date, conductor=date+month+year;
            int temp,k=0;

    //EditText Jumping Module-------------------------------

        e2.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                int tl = e2.getText().length();

                if (tl >= 2) {
                    e3.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        e3.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                int lt = e3.getText().length();

                if (lt >= 2) {
                    e4.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

I don't think the rest of the code has any problem is the starting section so I've provided that above. Thank you

A: jhamon's comment is spot on. Your EditTexts are most likely empty, the user did not input any value yet but you try to get that value. However, since you included no logs and no xml (at the time i am writing this) i am going to assume that the EditTexts have some default value that you assigned in the xml and that is the value you want to get at this point.
For EditText e1 you get the text like this :
e1.getText().toString()

For the rest of the EditTexts you are missing the getText(). You simply say:
int date = Integer.parseInt(e2.toString());
int month = Integer.parseInt(e3.toString());
int year = Integer.parseInt(e4.toString());

So add the getText().
But please add the log output and you xml. It would really help us help you! ;)


text:
Q: Recursive query from the same table I have different product serial numbers in one table ProdHistory which contains, as the table name suggest, production history.
For example I have product serial SER001 which uses parts with its own serial number.
We also produce these parts thus uses the same table ProdHistory to track its subparts.
The same goes with the subparts and if it has sub-sub parts.
Sample Table
IF OBJECT_ID('tempDB.dbo.#SAMPLETable') IS NOT NULL DROP TABLE #SAMPLETable
CREATE TABLE #SAMPLETable
(
    ITEMSEQ INT IDENTITY(1,1),
    SERIAL NVARCHAR(10) COLLATE SQL_Latin1_General_CP850_CI_AS,
    ITEMID NVARCHAR(10) COLLATE SQL_Latin1_General_CP850_CI_AS,
    PARTSERIAL NVARCHAR(10) COLLATE SQL_Latin1_General_CP850_CI_AS,
    PARTID NVARCHAR(10) COLLATE SQL_Latin1_General_CP850_CI_AS,
    CREATEDDATETIME DATETIME
)

INSERT INTO
       #SAMPLETable (SERIAL,ITEMID,PARTSERIAL,PARTID,CREATEDDATETIME)
VALUES ('SER0001','ASY-1342','ITM0001','PRT-0808','2017-01-17'),
       ('SER0001','ASY-1342','ITM0002','PRT-0809','2017-01-17'),
       ('SER0001','ASY-1342','ITM0003','PRT-0810','2017-01-17'),
       ('SER0001','ASY-1342','ITM0004','PRT-0811','2017-01-17'),
       ('ITM0001','PRT-0808','UNT0001','PRT-2020','2017-01-16'),
       ('ITM0002','PRT-0809','UNT0002','PRT-2021','2017-01-16'),
       ('ITM0002','PRT-0809','UNT0003','PRT-2022','2017-01-16'),
       ('ITM0003','PRT-0810','UNT0004','PRT-2023','2017-01-16'),
       ('UNT0002','PRT-2021','DTA0000','PRT-1919','2017-01-15'),
       ('UNT0003','PRT-2022','DTA0001','PRT-1818','2017-01-15'),
       ('DTA0001','PRT-1818','LST0001','PRT-1717','2017-01-14')

The question is, if I'm given just the main serial number, how can I return all the parts and subparts serial associated with it?
Sample Result:
MainSerial SubSerial1 SubSerial2 SubSerial3 SubSerial4
-------------------------------------------------------
SER0001    ITM0001    UNT0001
SER0001    ITM0002    UNT0002    DTA0000
SER0001    ITM0002    UNT0003    DTA0001    LST0001
SER0001    ITM0003    UNT0004
SER0001    ITM0004

In above, it is not definite how many parts and subparts there are for a serial number.
I did not post my code since what I'm doing right now is to query it one by one.
If I have known number of subparts, I can do nested Joins, however it is not.
Another question is, if I'm just given any of the subparts above, is it possible to return the same result?

A: I think a way is to use Dynamic SQL like this:
-- Variables to generate SQL query string dynamically
declare @cols nvarchar(max) = '', @joins nvarchar(max) = '', @sql nvarchar(max) = '';

-- Using CTE to iterate parent-child records
with cte(i, cols, joins, itemId, serial, partId, partSerial) as (
    select
        1, -- Level or depth of hierarchically tree
        N's1.serial MainSerial, s1.partSerial SubSerial'+cast(1 as varchar(max)),
        N'yourTable s'+cast(1 as varchar(max)),
        s.itemId, s.serial, s.partId, s.partSerial
    from yourTable s
    -- A way to filter root-parents is filtering items those are not in parts
    where s.itemId not in (select si.partId from yourTable si)
    union all
    select
        i+1,
        cols + N', s'+cast(i+1 as varchar(max))+N'.partSerial SubSerial'+cast(i+1 as varchar(max)),
        joins + N' left join yourTable s'+cast(i+1 as varchar(max))+N' on s'+cast(i as varchar(max))+N'.partId = s'+cast(i+1 as varchar(max))+N'.itemId',
        st.itemId, st.serial, st.partId, st.partSerial
    from cte
    join #sampleTable st on cte.partId = st.itemId
)
-- Now we need only strings of deepest level
select top(1)
    @cols = cols, @joins = joins
from cte
order by i desc;

-- Finalize and executing query string
set @sql = N'select ' + @cols + N' from ' + @joins + N' where s1.itemId not in (select s.partId from yourTable s)';
exec(@sql);

Additional Note: Generated query is:
select s1.serial MainSerial
    , s1.partSerial SubSerial1
    , s2.partSerial SubSerial2
    , s3.partSerial SubSerial3
    , s4.partSerial SubSerial4
  --, ...
from yourTable s1
  left join yourTable s2 on s1.partId = s2.itemId
  left join yourTable s3 on s2.partId = s3.itemId
  left join yourTable s4 on s3.partId = s4.itemId
--left join ...
where s1.itemId not in (select s.partId from yourTable s);


text:
Q: Dataframes from .data, .names and .test files using pandas I am trying to work on the adult dataset, available at this link.
At the moment I'm stuck since the data I am able to crawl are in formats which are not completely known to me. Therefore, after downloading the files, I am not able to correcly get a pandas dataframe with the downloaded files.
I am able to download 3 files from UCI using the following links:
data = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
names = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names'
test = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'

They are respectively of formats .data, .names and .test. I have always worked using .csv format, therefore I am a little confused about these ones.
How can I get a pandas dataframe with the train data (= data + names) and a pandas dataframe with the test data (= test + names)?
This code won't completely work:
train_df = pd.read_csv(r'./adult.data', header=None)
train_df.head()  # WORKING (without column names)

df_names = df = pd.read_csv(r'./adult.names')
df_names.head()  # ERROR

test_df = pd.read_csv(r'./adult.test')
test_df.head()  # ERROR

A: Use:
import pandas as pd
import re

# adult.names
with open('adult.names') as fp:
    cols = []
    for line in fp:
        sre = re.match(r'(?P<colname>[a-z\-]+):.*\.', line)
        if sre:
            cols.append(sre.group('colname'))
    cols.append('label')

# Python > 3.8, walrus operator
# with open('adult.names') as fp:
#     cols = [sre.group('colname') for line in fp
#                 if (sre := re.match(r'(?P<colname>[a-z\-]+):.*\.', line))]
#     cols.append('label')

options = {'header': None, 'names': cols, 'skipinitialspace': True}

# adult.data
train_df = pd.read_csv('adult.data', **options)

# adult.test
test_df = pd.read_csv('adult.test', skiprows=1, **options)
test_df['label'] = test_df['label'].str.rstrip('.')

A: You achieve that using pandas like this:
import pandas as pd
# reading csv files
data =  pd.read_csv('adult.data', sep=",")
print(data)

names =  pd.read_csv('adult.names', sep="\t")
print(names)

test =  pd.read_csv('adult.test', sep="\t")
print(test)


text:
Q: Restricting keys to elements that have specified attribute set I want to be able to reference specific xml elements from other. To do so this element has an optional Attribute name.
To validate that all references exist U use the elements key and keyref in the xsd.
The key definition looks something like this:
<key name="LevelPK">
  <selector xpath='./test:Level'/>
  <field xpath="@Name"/>
</key>

The keyref
<keyref name="LevelFK" refer="test:LevelPK">
  <selector xpath=".//test:LevelRequirement/test:Level"/>
  <field xpath="@Name"/>
</keyref>

The problem is that the Name Attribute is optional for the keys. I want only to create them if I have to reference them on another element.
This results in an error that the field Name can not be found for those by the key. As far as I understand xPath, I should be able to define a query that looks for every element with specific attributes. xpath="./test:Level[@Name]" But now I get an error that the xpath is not valid for this element.
I use VS2017 for validation.


text:
Q: Mysql + Combobox Hola alguien podria resolver mi problema..
Tengo un combobox cargado desde mysql con una tabla llamada estados lo que pretendo hacer es obtener la cantidad de ciudades que hay en el item seleccionado del combobox.
Select nombreciudad,count(nombreciudad) as Cantidad from estados group by nombreciudad order by Cantidad where nombrestado=;" +(item de combobox)

A: Bueno lo primero que tendrías que hacer es que tu combobox cargue la consulta de la base de datos para que te despliegue la lista de estados, y ya que esta cargada esta información, seleccionas un "Estado" y deberás consultar a la base de datos que ciudades están relacionadas con el estado seleccionado con el siguiente código puedes "escuchar" el id o el valor que este relacionado al estado que te permita cargar la consulta de las ciudades....

$(document).ready(function(){
    $("button#recargarCiudad").click(function(e){
         $("#Estado").on('change', function(){
            $("#Estado option:selected").each(function(){
                var cadenaClave = $('#Estado').val();

                $.ajax({
                async:true,
                cache:false,
                type: 'POST',
                url: 'cargarCiudades.php',data{cadenaClave:cadenaClave}
            })
        .done(function(data){
        $('#Ciudades').html(data);

        })
        .fail(function(){
        alert('Hubo un error al cargar la lista de ciudades');
            });
           });// fin de  each - función que escucha elemento-
        });
    });

});

Este script lo que hace es obtener un valor que podría ser un id o cualquier otro dato que te sirva para poder hacer la consulta a la bd y te regrese las ciudades que pertenecen al estado seleccionado...  o en su defecto que es para lo que yo lo uso, cargar un segundo selector dependiente del otro, ya teniendo estos datos los cuentas con Count y obtienes el numero de registros que te regresa.


text:
Q: Visual studio 15.7.0 xamarin form build error Hello guys i have just update my vs community to the latest version.after the update if i am trying to create a normal Xamarin.From application then it's giving me some error.
Xamari.froms.build.tasks.xamlGtask could not be loaded.

I tried to uninstall xamar.forms and install it again..but that doesn't help also.
What should i do?

A: *

*Clean the project

*Close the project

*Delete folders Temp,Prefetch and %temp%

*Open project

*Rebuild

A: Update Xamarin.Forms version in your Xamarin forms solution (PCL,Xamarin iOS project and Xamarin Android). Most of the times    reason for this behavior is your solution contains older xamarin    forms version and Visual Studio contains latest version.


text:
Q: How to configure and connect a IEEE 802.1X EAP-TLS wireless network with ConnMan on Debian 10? I want to connect with ConnMan on a Debian 10 Mate to a hidden wireless network that uses IEEE 802.1X EAP-TLS. I know his SSID. I have a .p12 extension certificate. I can't set the GUI.
So I created the configuration file that ends with .config under /var/lib/connman
But I don't know how to do it. I restarted the service but it only appeared once in the GUI but it gave the error Failure: blocked. It didn't appear when I rearranged the configuration file and restarted the service.
References:
https://www.mankier.com/5/connman-service.config
http://www.malinov.com/Home/sergey-s-blog/intelgalileo-addingwifi


text:
Q: gdb debugger in xcode doesn't work I'm trying to use direct commands to gdb through xcode's console window when the program is paused.  But the (gdb) prompt just accepts the carriage returns, and does nothing.  Has anyone encountered this? I'm on the latest version of Mac OS X (10.6.2) with the XCode 3.2 beta.

A: If using a beta best to contact the beta mailing lists as this is the sort of issue the developers want to know.
If using a beta the first thing I would check is does this work using the previous production version
Also note that you might be under a NDA and so can only discuss with the developers.

A: This is a bug in the software, or an incompatibility with some setting in my system.  Formatting my laptop and reinstalling the software fixed the problem.


text:
Q: Hostapd failed to start - Failed to initialize interface I'm trying to set up hostapd on linux machine as a network authenticator with 802.1x.
I've been mostly following this guide, with some adaptations since I'm using Ubuntu Jammy instead of RHEL, and using veth interfaces in the bridge instead of physical ones.
I created the hostapd.conf file as instructed with the content as they described - My bridge interface is br0 like in the sample, I changed the own_ip_addr to the IP on interface br0, and changed the nas_identifier, auth_server_addr, auth_server_shared_secret, acct_server_addr, and acct_server_shared_secret to match the config on my RADIUS server.
Everything else is the same as the example file, but for some reason hostapd wont start. /var/log/syslog says there is an error in the config file but doesn't really explain what the problem is:
Oct 25 13:47:13 blackfox systemd[1]: hostapd.service: Scheduled restart job, restart counter is at 320.
Oct 25 13:47:13 blackfox hostapd[347060]: 1 errors found in configuration file '/etc/hostapd/hostapd.conf'
Oct 25 13:47:13 blackfox hostapd[347060]: Failed to set up interface with /etc/hostapd/hostapd.conf
Oct 25 13:47:13 blackfox hostapd[347060]: Failed to initialize interface
Oct 25 13:47:13 blackfox systemd[1]: hostapd.service: Control process exited, code=exited, status=1/FAILURE
Oct 25 13:47:13 blackfox systemd[1]: hostapd.service: Failed with result 'exit-code'.
Oct 25 13:47:15 blackfox systemd[1]: hostapd.service: Scheduled restart job, restart counter is at 321.
Oct 25 13:47:15 blackfox hostapd[347062]: 1 errors found in configuration file '/etc/hostapd/hostapd.conf'
Oct 25 13:47:15 blackfox hostapd[347062]: Failed to set up interface with /etc/hostapd/hostapd.conf
Oct 25 13:47:15 blackfox hostapd[347062]: Failed to initialize interface
Oct 25 13:47:15 blackfox systemd[1]: hostapd.service: Control process exited, code=exited, status=1/FAILURE
Oct 25 13:47:15 blackfox systemd[1]: hostapd.service: Failed with result 'exit-code'.
Oct 25 13:47:17 blackfox systemd[1]: hostapd.service: Scheduled restart job, restart counter is at 322.
Oct 25 13:47:17 blackfox hostapd[347065]: 1 errors found in configuration file '/etc/hostapd/hostapd.conf'
Oct 25 13:47:17 blackfox hostapd[347065]: Failed to set up interface with /etc/hostapd/hostapd.conf
Oct 25 13:47:17 blackfox hostapd[347065]: Failed to initialize interface
Oct 25 13:47:17 blackfox systemd[1]: hostapd.service: Control process exited, code=exited, status=1/FAILURE
Oct 25 13:47:17 blackfox systemd[1]: hostapd.service: Failed with result 'exit-code'.

Does anyone have any idea what's going on?

A: Running
hostapd -dd /etc/hostapd/hostapd.conf

Gave some more details as to what was going on. RHEL has a special administrative group called wheel which is non-existent in Ubuntu.
Went back to the config file and changed
ctrl_interface_group=wheel

to replace wheel with either 0, root, 27, sudo
It started successfully with all of them.


text:
Q: Multiple IF statement in SSRS How to write multiple if statement in SSRS. I have written like this.
=IIf(Parameters!MyDuration.Value="ThisMonth" & Parameters!Transactions.Value="Sale", Sum(Fields!ThisMonthSal), True,False)

this is throwing an exception that multiple parameter used. Please guide me how to write this multiple if statement.

A: The & operator concatenates two strings. You're looking for the And operator. Refer to this msdn article.
In addition, note that IIF has three parts (see decision functions here), and works like this:
=Iif(test, truepart, falsepart)

I'm not sure what you're trying to do with the "SUM" bit (or what you're trying to achieve at all, the question's not clear on that), but something like this would work:
=IIf(Parameters!MyDuration.Value="ThisMonth" And Parameters!Transactions.Value="Sale",
      Iif(Sum(Fields!ThisMonthSal.Value) = 0, "Zero sum", "Non-zero sum"),
      "Not thismonth or sale")

Finally, you're not entirely clear about the error you're getting. If you're also having a problem with accessing the parameter you may have to investigate that seperately. In any case, the above should explain the Iif bit.


text:
Q: Sabre GetReservation wsdl does not contains schema for PriceQuoteServices I am using sabre GetReservation SOAP call its working fine but now I added PRICE_QUOTE subject area which contains response of PriceQuoteServices but the wsdl provided by sabre for GetReservation does not contains xsd(schemas) for PriceQuoteServices.
The issue is when I am going to parse the xml response of GetReservation using python-zeep it ignores the PRICE_QUOTE object since it was not defined in the schemas. Is their any work around for this instead of geting raw_response from zeep and then converting to json?

A: This is because there are basically two transactions being merged in the response.  The Price_Quote subject area tells the system to also return the PriceQuoteServicesRQ response as part of the XML.
The documentation for PriceQuoteServicesRQ is on Sabre Dev Studio - the transaction is actually called 'Manage Price Quote Details'
https://developer.sabre.com/docs/soap_apis/air/fulfill/manage_price_quote_details/resources
There is a WSDL and Docs there for you to use
Hope this helps


text:
Q: Update UniqueConstrains on a JPA table I have a table defined as follow:
@Entity
@Table(
        uniqueConstraints = {@UniqueConstraint(columnNames = {"reward_id", "transaction_id"})}
)
public class ShipmentItem extends Model {
    ...
}

I want to change the unique constraint to make it more relaxed:
@Entity
@Table(
        uniqueConstraints = {@UniqueConstraint(columnNames = {"reward_id", "transaction_id", "sku"})}
)
public class ShipmentItem extends Model {
    ...
}

The updated code compiles, but JPA doesn't change the table schema. Is there a configuration setting I need to use?
If JPA cannot do this, what's the systematic approach to this problem? I can write migration, however, JPA generates the name for the constraint automatically, so it's not obvious how to drop the old constraint.
Not sure if it matters, but I am using hibernate and mysql.

A: Since you are using Hibernate, there is a property for automatically updating your schema: hibernate.hbm2ddl.auto with the value update
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html
(But be aware that it is not recommended to use it on Production)


text:
Q: vb.net SQL SERVER "Incorrect Syntax near'='." Im having problem in displaying records in datagridview and i dont know how to fix it. the messagebox is display "Incorrect Syntax near'='. here's my code.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim search As String = String.Empty
    search &= "select * from record"
    search &= "where identification=@identification;"

    Using conn As New SqlConnection("server=KENJOY_FMCD;database=humanresource;user=ayala747;password=4525422;")
        Using cmd As New SqlCommand()
            With cmd
                .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = search
                .Parameters.AddWithValue("@identification", vsearch.Text)
            End With
            Try
                conn.Open()
                cmd.ExecuteNonQuery()
                Dim da As New SqlDataAdapter(cmd)
                Dim ds As New DataSet
                da.Fill(ds)

                If ds.Tables.Count > 0 Then
                    DataGridView1.DataSource = ds.Tables.Count
                Else
                    MsgBox("Identification Number Not Found!")
                End If
                conn.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Using
    End Using
End Sub

A: You're missing a white space before your where:
search &= "select * from record "
' Here ------------------------^
search &= "where identification=@identification;"

A: Your SQL statement doesn't leave a space between the table name and the WHERE keyword, so it looks like:
select * from recordwhere identification=@identification;


text:
Q: ingesting CDRs into hadoop I've just started working on a hadoop use case of analyzing CDRs in near-real time.
CDRs are encoded in ASN1.1. A remote server is feeded regularly by CDRs. I'm wondering about how to ingest CDRs from this server into my cluster, and decode them to generate CSV files that can be processed by Hive (or Spark Streaming ..).
Is Flume Adapted to ingest this kind of data ? When do you think I should decode ASN1.1, before or after ingesting ? I have a program written in C for decoding ASN1.1.
If Flume is adapted to ingest data, should I implement an Avro client in the server containing initial data, or is there another well-suited method ?


text:
Q: Django "Model.objects.create()" linking two fields/relationship kindly correct me with the tittle if it is wrong or misleading, thanks.
I am very new to Django Python. I am using Django 3.1.1.
My question is about the "Model".objects.create(), I use it with ajax to save or create data in my Logger model.
Question: How can I link the Logger.userprofile to UserProfile.user using Logger.objects.create() or what is the next thing to do to linked the two fields?
My UserProfile model is already linked to the User model via OneToOneField but was saving data using form.save(), and this was successful. below is what I have constructed so far by following numerous tutorials.
This is already working and it is creating data in my Model, I just need to add the link between the UserProfile and the Logger for the sake of easy identification of the log created.
Log is created in the Logger Model via qrcode scan.
Views.py
def processQRCode(request):

    if request.method == 'POST':
            qrcoderes = request.POST['qrcoderes']
            logged_in = request.POST['logged_in']
            logged_in_location = request.POST['logged_in_location']

            Logger.objects.create(
                qrcode_uuid = qrcoderes, #edited from qrcode_uuid to qrcoderes to distinguish the two variables.
                logged_in = logged_in,
                logged_in_location = logged_in_location
            )

    return HttpResponse('Success!')

Models.py
UserProfile Model
class UserProfile(models.Model):

    GENDER = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    user = models.OneToOneField(User, related_name='userprofile', null=True, on_delete=models.SET_NULL)

    qrcode_uuid = models.UUIDField(unique=True, default=uuid4)
    qr_code = models.ImageField(upload_to='qr_codes', blank=True)

    firstName = models.CharField(max_length=200)
    middleName = models.CharField(max_length=200)
    lastName = models.CharField(max_length=200)
    gender = models.CharField(max_length=6, choices=GENDER)
    birthdate = models.DateField(max_length=200)
    contact = models.CharField(max_length=200)
    agency = models.CharField(max_length=200)
    deptSec = models.CharField(max_length=200)
    designation = models.CharField(max_length=200)
    streetHouse = models.CharField(max_length=200)
    purok = models.CharField(max_length=200)
    barangay = models.CharField(max_length=200)
    cityMunicipality = models.CharField(max_length=200)
    province = models.CharField(max_length=200)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'User Profile'

    def __str__(self):
        return self.firstName + " " + self.middleName + " " + self.lastName

    def save(self, *args, **kwargs):
        qrcode_img = qrcode.make(self.qrcode_uuid)
        canvas = Image.new('RGB', (370, 370), 'white')
        draw = ImageDraw.Draw(canvas)
        canvas.paste(qrcode_img)
        fileName = f'qr-code-{self.qrcode_uuid}.png'
        buffer = BytesIO()
        canvas.save(buffer,'PNG')
        self.qr_code.save(fileName, File(buffer), save=False)
        canvas.close()
        super().save(*args, **kwargs)

Logger Model
class Logger(models.Model):
    userprofile = models.OneToOneField(UserProfile, null=True, on_delete=models.SET_NULL)

    qrcode_uuid = models.CharField(max_length=200, null=True)
    logged_in = models.CharField(max_length=1, default="1")
    logged_in_location = models.CharField(max_length=200, null=True)
    log_datetime = models.DateTimeField(auto_now_add=True)

    class Meta:
            verbose_name_plural = 'Logger'

    def __str__(self):
            return self.logged_in_location + " " + self.qrcode_uuid

Ajax.js
function processQRCodeDetails(){

$.ajax({
      type:'POST',
      url: '/processqrcode/',
      data:{
        qrcoderes: $('#process-qrcoderes').val(),
        logged_in: $('#logged_in').val(),
        logged_in_location: $('#logged_in_location').val(),
        csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val()
      },
      success: function(data){
        $('#staticBackdrop').modal();
        console.log('Success');
      },
      error: function(data){
        console.log('Error')
      }
    });

}

template.html
<form id="process-qrcoderes-form">
  {% csrf_token %}
  <input class="form-control" type="text" name="process-qrcoderes" id="process-qrcoderes" onchange="processQRCodeDetails(); return false;" autofocus="autofocus">
  <input type="text" name="logged_in" id="logged_in" value="1">
  <input type="text" name="logged_in_location" id="logged_in_location" value="test">
</form>

A: You need to get UserProfile from db and pass it to create method
 def processQRCode(request):
    if request.method == 'POST':
        qrcode_uuid = request.POST['qrcoderes']
        logged_in = request.POST['logged_in']
        logged_in_location = request.POST['logged_in_location']

        # edit: you can get your UserProfile instance by "qrcode_uuid" as well
        # use get_or_create, note that it returns tuple, not instance
        userprofile, created = UserProfile.objects.get_or_create(qrcode_uuid=qrcode_uuid)

        if created:
            # some additional actions here for newly created UserProfile, filling some fields may be

            # recommended naming convention for class attrs in python is underscore_case, not camelCase
            userprofile.firstName = "John"
            userprofile.save()

        Logger.objects.create(
            qrcode_uuid = qrcode_uuid,
            logged_in = logged_in,
            logged_in_location = logged_in_location,
            userprofile=userprofile
        )

    return HttpResponse('Success!')

A: Solved it accidentally.
I don't know what happened to the UUIDField but, got a record which was edited under the UserProfile model (has only 3 records in it), unfortunately and fortunately, when I scanned the 3rd record which was edited using the "Save and Continue editing" of django admin, "it work like a charm!" (as everyone call it when it worked :D), so, I proceeded editing the 2 other records and it worked also.
My primarily goal was to just insert the id of the UserProfile model to Logger model to linked the 2 models using the following syntax:
# been trying this syntax for ages now. lol. and it was not the problem.
userprofile_id = UserProfile.objects.get(qrcode_uuid=qrcoderes)

    #Note: Using the .objects.create() method also works now.
    log = Logger(
            userprofile = userprofile_id,
            qrcode_uuid = qrcoderes, #edited from qrcode_uuid to qrcoderes to distinguish the two variables.
            logged_in = logged_in,
            logged_in_location = logged_in_location
        )
    log.save()

Note: this was not working, it was giving me an error UserProfile matching query does not exist., even using the shell, it is giving me the same error. So, I thought, my syntax was the problem, that's why I posted my problem here.
Maybe, I'll trying to use the CharField for the UUID if that's makes a difference or if it is compatible for the UUID.


text:
Q: How to save command cooldown? The code below adds a cooldown for command, but when bot restarts, the cooldown resets. So how can I make the bot remember from previous usage? If the cooldown limit is 5 times per day and if the member used 3 times and if bot restarts it should start from where it was left for all members.
import discord
from discord.ext import commands
import random

from utils import Bot
from utils import CommandWithCooldown

class Members():
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True, cls=CommandWithCooldown)
    @commands.cooldown(1, 600, commands.BucketType.user)
    async def ping(self, ctx):
        msg = "Pong {0.author.mention}".format(ctx.message)
        await self.bot.say(msg)

def setup(bot):
    bot.add_cog(Members(bot))

A: Similar to what Patrick Haugh suggested, the cooldown mapping is stored in Command._buckets. You can pickle the bucket before the bot starts and save it after the bot finishes. For your convenience, replace the Bot class with the following (a.k.a "moneypatching"):
token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"
cooldown_info_path = "cd.pkl"

from discord.ext import commands

class Bot(commands.Bot):

    async def start(self, *args, **kwargs):
        import os, pickle
        if os.path.exists(cooldown_info_path):  # on the initial run where "cd.pkl" file hadn't been created yet
            with open(cooldown_info_path, 'rb') as f:
                d = pickle.load(f)
                for name, func in self.commands.items():
                    if name in d:  # if the Command name has a CooldownMapping stored in file, override _bucket
                        self.commands[name]._buckets = d[name]
        return await super().start(*args, **kwargs)

    async def logout(self):
        import pickle
        with open(cooldown_info_path, 'wb') as f:
            # dumps a dict of command name to CooldownMapping mapping
            pickle.dump({name: func._buckets for name, func in self.commands.items()}, f)
        return await super().logout()

bot = Bot(prefix)
# everything else as usual

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command(pass_context=True)
@commands.cooldown(1, 3600, commands.BucketType.user)
async def hello(ctx):
    msg = "Hello... {0.author.mention}".format(ctx.message)
    await bot.say(msg)

class ACog:
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    @commands.cooldown(1, 600, commands.BucketType.user)
    async def ping(self, ctx):
        msg = "Pong {0.author.mention}".format(ctx.message)
        await self.bot.say(msg)

bot.add_cog(ACog(bot))
bot.run(token)

This will save the cooldown data to "cd.pkl" when the bot is properly logged out.


text:
Q: How to configure which characters are allowed in CentOS usernames In systems such as Debian, there is a file /etc/adduser.conf which includes directive NAME_REGEX that can be used to define which characters are allowed in a username.
Is there a way to do this in CentOS 6.9? I can see that there is a file /etc/default/useradd but there is no indication anywhere in the documentation that it could support a similar directive.
I would like to be able to create a username with the @ sign in it, such as user@domain.com.


text:
Q: Understanding Tkinter window responsiveness when running a background thread I am using Tkinter to create a GUI that is continually updated from a computation thread. In order to keep the GUI responsive, I create an event in each loop of this thread that tells the main thread (in which the Tkinter window was created) to update the GUI with the computed data. The structure of the thread looks like this:
class background_thread(threading.Thread):
    def __init__(self, parent, stopper):
        threading.Thread.__init__(self)

        self.parent  = parent
        self.stopper = stopper

        ### Init. variables ###

    def run(self):
        while(not self.stopper.is_set()):

            ### Compute data ###

            root.event_generate("<<update_gui>>", when = "now")

This works nicely, but I'm having trouble understanding the behavior of my Tkinter window when the thread is running. First, even though my mainloop() is still responsive (I get approximately 40 frames per second), the window itself is not responsive at all. By this, I mean that it's not really possible to drag it nor to close it. What is the reason for this and is there any way to prevent it?
One of the problems arising from this is that I have to stop the thread before closing the window. For this, I use a button that toggles its execution:
def callback_toggle_thread(self, event):
    if(not self.background_thread.isAlive()):
        self.background_thread.start()
    else:
        self.stopper.set()

But if I try to redefine the window close button protocole:
root.protocol("WM_DELETE_WINDOW", on_closing)

def on_closing():
    if(self.background_thread.isAlive()):
        self.stopper.set()                  # Asks the thread to stop
        self.background_thread.join()       # Waits for the thread to stop

    root.destroy()                          # Closes the window

the program just freezes. Am I doing anything wrong?

A: As I suggested in a comment if you call root.update() after generating the event in the background thread it will force the application to update itself. This fixed the original issue although I can't walk through the specific flow of execution since the example code isn't enough to test.


text:
Q: Is there a thread safe JacksonJsonObjectReader class in Spring Batch If I use Sprint-Batch to read the Json file without specifying taskExecutor it works fine, but with taskExecutor specified it can't read properly. Wrapping with SynchronizedItemStreamReader can solve the problem of thread safety, but it does not work with JacksonJsonObjectReader. So I want to know if there is a thread-safe JacksonJsonObjectReader class to use

A: The typical usage of the JacksonJsonObjectReader is to use it as a delegate in a JsonItemReader. So if you wrap the JsonItemReader in a SynchornizedItemStreamItemReader, there is no need to synchronize the object reader (since the entire read method will be synchronized).
Now if you want to use the JacksonJsonObjectReader outside of this setup, you need to synhronize it yourself. This class is not thread safe.


text:
Q: Error with running LDA of flipmultivariates package on radiotelemetry data I'm trying to run an LDA on a group of radio-tracked birds from a number of different flocks which I have done over a number of winter seasons. In this case the predictor values are the signal strengths from 4 radio-towers with the flocks as the class variables. I think this is an creative use of LDA on a big data project and might therefore may be relevant to others.
I'm using the flipmultivariates package and followed this site as best I could: https://www.displayr.com/linear-discriminant-analysis-in-r-an-introduction/, and set up my data accordingly. Here are the first few lines:
structure(list(mfgID = c("337", "337", "337", "337", "337", "337"
), `month(ts)` = c(1, 1, 1, 1, 1, 1), `day(ts)` = 7:12, CP = c(NA,
NA, NA, NA, -63.32, -60.181), Elnina = c(NA, -24.1004, -25.5027,
-36.6236, -67.3128, NA), hans = c(-62.9033, -60.6047, NA, NA,
NA, NA), Nanoswamp = c(-47.0282, -41.3482, -49.6897, -53.9879,
NA, NA), flockID = c("EF", "EF", "EF", "EF", "EF", "EF")), class =     "data.frame", row.names = c(NA,
-6L))

I'm running the code:
lda1 <- LDA(flockID ~ Nanoswamp, hans , Elnina , CP,
    data    = FlocksforLDA2,
    missing = "Exclude cases with missing data",
    output  = "Scatterplot")

I keep getting this error message:
Error in EstimationData(form, data, subset, weights, missing, seed = seed) : There are fewer observations (0) than there are variables (2)
I've quite a number of NAs but I thought the missing line code above would address this. I'm using the flipmultivariates package because it greatly simplifies the LDA code and provides nice figures which is important.
If I've missed something silly I apologize, but any help is greatly appreciated.


text:
Q: How to pass multiple parameters to named groups url I don't know how to pass multiple parameters through template url reverse lookup
test

to match this url pattern:
r'^something/date/(?P<pk>\d+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$'

Get error:
Could not parse the remainder: '{"pk":location.pk,' from '{"pk":location.pk,'

Somebody has a clue?

A: The Django template language is not python. You cannot pass dictionaries as arguments, or use square brackets for slicing variables.
The example in the docs shows how to pass named arguments to the url tag.
{% url 'some-url-name' arg1=v1 arg2=v2 %}

You can use the slice filter as well.
year=date_single|slice:":3"

https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#url
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#slice


text:
Q: How do I send an object to a GET endpoint that takes in a Java object (Angular)? There is an object like this (more than one field, but just one for this ex)
public class MyObject{
  private String objString;

  public String getObjString(){
   return objString;
  }

 public void setObjString(String str){
  this.objString = str;
 }
}

and a wrapper for it to take multiple
public class MyObjects{
 private List<MyObject> objects;
 ... getters and setters for list...
}

and an endpoint like this
@GetMapping("/sample")
public ResponseEntity<String> sampleEndpoint(MyObjects objs){...}

What should I be doing to send it properly?  I have tried making a mock model of it and sending it over as a request param but that is not working.  I am able to hit the endpoint in the browser if I do a url like
'/sample?objs%5B0%5D.objString=test&objs%5B1%5D.objString=test1'
but am not sure what the best method to do this in angular is.


text:
Q: Animation border I have border, that I want to animate by clicking button (name = "button1"). Button is outside. My code throws an exception. Whats wrong? Thanks
  <Border Name="brdClasses" Background="#FF2c3e50">
                    <Border.RenderTransform>
                        <ScaleTransform x:Name="MyAnimatedScaleTransform"
                                         ScaleX="1" ScaleY="1"  />
                    </Border.RenderTransform>
                    <Border.Triggers>
                        <EventTrigger SourceName="button1" RoutedEvent="Button.Click">
                            <EventTrigger.Actions>
                                <BeginStoryboard Name="MyBeginStoryboard">
                                    <Storyboard >
                                        <DoubleAnimation
                                         Storyboard.TargetName="MyAnimatedScaleTransform"
                Storyboard.TargetProperty="(ScaleTransform.ScaleX)"
                To="3.0" Duration="0:0:10" AutoReverse="True" />

                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger.Actions>
                        </EventTrigger>
                    </Border.Triggers>
                </Border>

A: I Dont know why your code doent works... But I did a simple example in a specific way.. if it helps make use of that..
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Border Name="brdClasses" Grid.Row="1" Background="#FF2c3e50" Height="100" Width="150">
       <Border.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Border.RenderTransform>
    </Border>
    <Button Content="Button1" x:Name="button1">
        <Button.Triggers>
           <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="button1">
        <BeginStoryboard>
            <Storyboard>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="brdClasses">
            <EasingDoubleKeyFrame KeyTime="0" Value="3"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
        </Button.Triggers>
    </Button>
</Grid>


text:
Q: Finding and replacing key: value pairs I'm in the process of porting over a Python library to JavaScript / TypeScript. To help myself out, I'm trying to develop various regex rules that I can apply to files that will automatically convert a lot of the syntax and at least get me close, cleaning up where needed.
I've got the following example:
https://regex101.com/r/mIr0pl/1
this.mk(attrs={keyCollection.key: 40}))
this.mk(attrs={keyCollection.key: 50, override.key: override.value})
this.mk(attrs={keyCollection.key: 60,
               override.key: override.value})

I am trying to do a Find/Replace in my editor, to find all key: value pairs associated with attrs dictionaries. Here's the regex I've got:
/attrs={(.+?):\s*(.+?)}/gms
I want to convert it to this:
this.mk(attrs=[[keyCollection.key, 40]]))
this.mk(attrs=[[keyCollection.key, 50], [override.key, override.value]])
this.mk(attrs=[[keyCollection.key, 60],
               [override.key, override.value]])

I'm having trouble first nailing down the regex to get the repeated key: value groups, and then also how I would go about utilizing those repeated groups in a replace.
(my editor is VSCode, but I'm using this nifty extension to run these modifications: https://marketplace.visualstudio.com/items?itemName=bhughes339.replacerules)
Any help would be appreciated :)

A: Since VS Code already supports infinite-width lookbehind construct you may use
"replacerules.rules": {
    "Wrap the attrs with square brackets first": {
        "find": "(attrs=){([^:{]+:*[^}]*)}",
        "replace": "$1[[$2]]"
    },
    "Format attributes inside attrs": {
        "find": "(?<=attrs=\\[\\[[^\\]]*(?:](?!])[^\\]]*)*),(\\s*)",
        "replace": "],$1["
    },
    "Replace colons with commas inside attrs": {
        "find": "(?<=attrs=\\[\\[[^\\]]*(?:](?!])[^\\]]*)*):",
        "replace": ","
    }
}

"replacerules.rulesets": {
    "Revamp attrs": {
        "rules": [
            "Wrap the attrs with square brackets first",
            "Format attributes inside attrs",
            "Replace colons with commas inside attrs"
        ]
    }
}

Step #1 regex demo
Step #2 regex demo
Step #3 regex demo
Output:
this.mk(attrs=[[keyCollection.key, 40]]))
this.mk(attrs=[[keyCollection.key, 50], [override.key, override.value]])
this.mk(attrs=[[keyCollection.key, 60],
               [override.key, override.value]])

A: Maybe,
(?<=attrs={|,)([^:}]*):([^:},]*)(?=}|,)

might be somehow closer.
If you might have had other attrs, you might want to initially filter out those others.

If you wish to explore/simplify/modify the expression, it's been
  explained on the top right panel of
  regex101.com. If you'd like, you
  can also watch in this
  link, how it would match
  against some sample inputs.


text:
Q: Is it possible to build a package with bitbake without poky? I have all compiled binaries for target machine. I want to create a binary package - say .ipk, .rpm -  for target machine. As this suggested to clone poky, which will have bitbake within it. But, as this document says, we can directly use bitbake without poky, however, it not mentioned anywhere that we need poky as well as bitbake to build a custom package. But of course poky is required if we have to compile source code and create binaries.
If I don't need to compile any source code at all, does I need to have Poky?
Is it possible to build a package with only bitbake?

A: First, Poky is a reference distribution that contains primarily bitbake and openembedded-core.
Yes, you need oe-core to build packages as the logic to build packages is part of oe-core, not bitbake.


text:
Q: XmlSerializer.FromTypes producing memory leaks? According to MSDN  XmlSerializer Class section "Dynamically Generated Assemblies" the XmlSerializer produces memory leaks when using certain constructors. I wonder if the
XmlSerializer.FromTypes(Type[])

method produces memory leaks, too?
EDIT:
I'm experiencing memory problems, when using the FromTypes method. So i started some investigations:
for (int i = 0; i < 1000; i++)
{
    DummyObject content = new DummyObject()
    {
        Age = 29,
        Location = "London",
        Name = "Pete"
    };
    XmlSerializer serializer = XmlSerializer.FromTypes(new[] { content.GetType() })[0];
    using (TextWriter textWriter = new StreamWriter($@"D:\test\array\{i}.xml"))
    {
        serializer.Serialize(textWriter, content);
    }
}

After executing the above code a few times the diagnostic tools of Visual Studio 2015 show the following:
Diagnostic Tools Image
The garbage collector runs, but it seems like the dynamically generated assemblies are flooding the memory. It would be interesting to know which constructor the FromTypes method internally uses. So, the FromTypes method produces memory leaks, too?

A: I slightly changed your code - run a loop 3000 times instead of 1000 and write serialized data into memory stream instead of file, and profile it with dotMemory. (I found using VS that RuntimeType instances are leaked, but did not find how to see where they were created).
At the end app occupied about a 1Mb of memory (I did not received a result of 500Mb as on your screenshot) but it's obviously a leak here.

Then opened all new objects created between the first and the fourth snapshots placed in Gen2 heap and found out that most of them are (as I mentioned above) instances of RuntimeType.

Opened them and saw that there are five almost equal sized groups of them.

So, the answer is "yes, this method produces a memory leak"
Below five stack traces where these objects were allocated
--------- 1 --------------
Allocated: 83580 B in 2985 objects
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
System.Reflection.Emit.TypeBuilder.CreateType()
System.Xml.Serialization.XmlSerializationWriterILGen.GenerateEnd()
System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly()
Folded items
[AllThreadsRoot]
--------- 2 --------------
Allocated: 83552 B in 2984 objects
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
System.Reflection.Emit.TypeBuilder.CreateType()
System.Xml.Serialization.XmlSerializationReaderILGen.GenerateEnd()
System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly()
Folded items
[AllThreadsRoot]
--------- 3 --------------
Allocated: 83552 B in 2984 objects
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
System.Reflection.Emit.TypeBuilder.CreateType()
System.Xml.Serialization.XmlSerializationILGen.GenerateBaseSerializer()
System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly()
Folded items
[AllThreadsRoot]
--------- 4 --------------
Allocated: 83552 B in 2984 objects
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
System.Reflection.Emit.TypeBuilder.CreateType()
System.Xml.Serialization.XmlSerializationILGen.GenerateTypedSerializer()
System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly()
Folded items
[AllThreadsRoot]
--------- 5 --------------
Allocated: 83552 B in 2984 objects
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
System.Reflection.Emit.TypeBuilder.CreateType()
System.Xml.Serialization.XmlSerializationILGen.GenerateSerializerContract()
System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly()
Folded items
[AllThreadsRoot]


text:
Q: How to distribute oracle database I want to distribute oracle database 11g on 3 servers but I don't know how to start.
I read some documents like :
http://docs.oracle.com/cd/B10501_01/server.920/a96521/ds_concepts.htm
and some others that are the same .
but I didn't find how to start.
I want a get start document about how to start distribute oracle , that contains :
1) how to install oracle for distribution
2) how to link them with some rules
3) how to query in a java application

A: According to your comment, you want to integrate several existing system. In that case, the easiest approach are database links:
There is no special installation involved. Just add the remote databases to TNSNAMES.ORA so that they know how to connect to each other.
Then create a database link, e.g.:
CREATE DATABASE LINK orlando
   CONNECT TO joe
   IDENTIFIED BY mysecret
   USING orcl33b;

Now you can query data (or insert or update):
SELECT a.name, b.total_amt
FROM person a
JOIN sales@orlando b
WHERE a.id = b.cust_id;

sales@orlando refers to the remote table sales in the remote orlando database.
There are different types of database links (regarding authentication, sharing and availability in other schema). You'll need to check which is best serves you.


text:
Q: Command Line : Concatenate multiple files by date I have got a plenty of .txt files in a directory. The directory also contains .png and some .pdf files. I have successfully concatenated .txt files using this command :
@ECHO Off
SETLOCAL
for /r %%f in (*.txt) do (
echo.
type "%%f"
)>> output.doc

GOTO :EOF

The above command was obtained from one of the online sites. This command will concatenate .txt files in alphabetical order. But i don't want it like that , i want it to be done by the date modified or created (modified is recommended).
I have got a hint that the line
for /r %%f in(*.txt) do (

must be modified in order to concatenate by date.I'm new to this command line or batch scripting so i don't really know much about it. How should i do this .
Thanks everyone for the answers.
Sorry for not including this question in the first time.
I have got one more requirement based on another question that i asked previously(Question) i have got a batch file for concatenating .txt files and for adding two lines on top of every file (one for writing the file name without the extension and other for writing the date associated to the concatenated file).Can anyone please modify the below batch file to concatenate .txt files by the order of date-modified and to add the two lines on top of each file.
@echo off
SETLOCAL
for /r %%f in (*.txt) do (
echo File Name   : %%~nf
FOR /f %%d IN ("%%~tf") DO echo Date        : %%d
echo.
type "%%f"
) >> output_text.doc

GOTO :EOF

Every problem solved final batch file :
@echo off
setlocal enableextensions disabledelayedexpansion

set "root=%cd%"

>"output.doc" (
    for /f "tokens=1,2,*" %%a in ('
        robocopy "%root%\." "%root%\." *.txt /l /s /is /ts /ndl /njh /njs /nc /ns
        ^| sort
    ') do (
     echo( %%~nc
     for /f "tokens=1-3 delims=/" %%d in ("%%a") do echo %%f/%%e/%%d
     type "%%~fc"
    )
)

A: Powershell (3 -see note) one liner:
gci *.txt -Recurse -File |sort -Property LastWriteTime |% {(gc $_) + "`n"} >output.doc

*

*It first lists all matching files (gci)

*then sorts them by modified date (sort)

*then gets contents of file and appends a newline to each (gc)

*and finally writes all to output file.

Note: Because it uses -File which was introduced in ps3. This can be rewritten in Ps2 syntax, but it's more verbose.
Edit: as requested by OP: modify {(gc $_) + "`n"}
to read:
{"$($_.basename)`n$(get-date -u %d/%m/%Y $_.lastwritetime)`n$(gc $_)`n"}

(string interpolation used this time to show various options)
Side note: [possible] file encoding inconsistencies & problems not    handled.

A: @echo off
    setlocal enableextensions disabledelayedexpansion

    set "root=%cd%"

    >"output.doc" (
        for /f "tokens=2,*" %%a in ('
            robocopy "%root%\." "%root%\." *.txt /l /s /is /ts /ndl /njh /njs /nc /ns
            ^| sort
        ') do type "%%~fb"
    )

This will use robocopy to get the list of all the .txt files under the indicated root folder.
The list of files is generated including the last modified date of the files. robocopy prints the UTC time in yyyy/mm/dd hh:mm:ss format, so the list can be properly sorted.
The rest of the code is just a for /f command to process the final list, retrieving the file reference and typing it. The full command is redirected to the output file to avoid the open/close operation for each processed file.
edited as it is needed to include the file name and the timestamp in the final output ...
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "root=%cd%"

    >"output.doc" (
        for /f "tokens=1,2,*" %%a in ('
            robocopy "%root%\." "%root%\." *.txt /l /s /is /ts /ndl /njh /njs /nc /ns
            ^| sort
        ') do (
            echo(%%~nc
            echo(%%a %%b [%%~tc]
            type "%%~fc"
        )
    )

The tokens clause has been changed to retrieve the timestamp from robocopy so we can include it in the output. %%a will hold the date, %%b the time and %%c the file name with full path.
For each file, it is first echoed the file name without extension (%%~nc), then the robocopy time stamp and, just to compare as the output of robocopy is a UTC time, the file timestamp (%%~tc). Then the file is typed.
As before, all the output is redirected to the final file.

A: for /f "delims=:" %f in ('dir *.txt /O:D /T:W /B') do @echo %f

This command will use dir to sort by oldest to newest date (/O:D) using the last written date (/T:W) and bare format (/B) to just return the filenames. Setting the delims to : in the for command keeps it from trying to parse the filename based on spaces or commas since : is not allowed in a filename.


text:
Q: Xcode 8 no support iOS 7 I've upgraded my Xcode to Xcode 8. Now I notice that I cannot run/debug on an iPhone with iOS 7.n.n. I've have read that it isn't supported in Xcode 8. I do know that my app will still work on iOS 7, but if something fails I would like to hang it on Xcode to debug it. So my question is:
Do I still get the bug fixes/improvement that were introduced in iOS 10 when submitting my app with a base sdk setting of iOS 9.3?

A: Xcode 8 (or even Xcode 7) doesn't include support for iOS 7 simulator, which is what I think you're really asking about.
To pick up the new iOS 10 SDK changes, link against the iOS 10 SDK and then set your target's minimum deployment version to iOS 7.
If you were using analytics, chances are very high that you'll find the number of iOS 7 using customers is incredibly low.

A:
Do I still get the bug fixes/improvement that were introduced in iOS 10 when submitting my app with a base sdk setting of iOS 9.3?

No, of course not. If you do that, you are still an iOS 9 app. You must link against iOS 10 if you want to run natively under iOS 10.
However, you can do that and still be backward compatible to iOS 7. And you can easily test on an iOS 7 device, so the change to Xcode 8 does you no harm.


text:
Q: Edit entire row in a DataGridView (not only one cell) Could somebody advice how to do this?
Currently i have :

*

*DataGridView with four columns - Text1 | Text2 | EditButton | SaveButton

*When i click on the Text1 it becomes an editable field and i can
change its value

*Then i try to edit Text2 but the click on this cell saves my changes in Text1

The issue is : when i try to edit second field (Text2) the first one (Text1) loses the focus, exits edit mode and saves changes that i made meanwhile i want to save all changes in a row simultaneously.
What i want to implement :

*

*I press EditButton and all cells becomes editable so i can change value of any cell in a row

*I change value of Text1, then value of Text2

*And only when i press SaveButton it saves made changes

The question is : how to keep all cells in a row in edit mode until i press specific button?

A: Maybe you can use a custom DataGridView like this
public class CustomDGV : DataGridView
{
    private object _cellValue;
    private Dictionary<int, object[]> _pendingChanges;

    public CustomDGV()
    {
        _pendingChanges = new Dictionary<int, object[]>();
    }

    protected override void OnCellBeginEdit(DataGridViewCellCancelEventArgs e)
    {
        // Save the value of the cell before edit
        _cellValue = this[e.ColumnIndex, e.RowIndex].Value;

        // If there's already a pending change for that cell, display the edited value
        if (_pendingChanges.ContainsKey(e.RowIndex))
        {
            this[e.ColumnIndex, e.RowIndex].Value = _pendingChanges[e.RowIndex][e.ColumnIndex];
        }

        base.OnCellBeginEdit(e);
    }

    protected override void OnCellEndEdit(DataGridViewCellEventArgs e)
    {
        // Adds the edited value of the cell into a dictionary
        if (!_pendingChanges.ContainsKey(e.RowIndex))
        {
            _pendingChanges.Add(e.RowIndex, new object[this.ColumnCount]);
        }

        _pendingChanges[e.RowIndex][e.ColumnIndex] = this[e.ColumnIndex, e.RowIndex].Value;

        // Display the "old" value
        this[e.ColumnIndex, e.RowIndex].Value = _cellValue;
    }

    public void SavePendingChanges(int rowIndex)
    {
        if (_pendingChanges.ContainsKey(rowIndex))
        {
            // Gets the pending changes for that row
            var rowData = _pendingChanges[rowIndex];
            // Update every cell that's been edited
            for(int i = 0; i < rowData.Length; i++)
            {
                if (rowData[i] != null)
                    this[i, rowIndex].Value = rowData[i];
            }
            // Removes the pending changes from the dictionary once it's saved
            _pendingChanges.Remove(rowIndex);
        }
    }
}

And on CellContentClick you can call SavePendingChanges()
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex > -1 && e.RowIndex > -1)
    {
        if (e.ColumnIndex == 3) // Save button
        {
            dataGridView1.SavePendingChanges(e.RowIndex);
        }
    }
}

A: Ok, i know it may look a bit messy but this seems to be simplest solution i could come up to - display TextBox over each read only cell when grid is going to edit mode :
public void DisplayEditors(DataGridView grid, DataGridViewRow row)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.ReadOnly == false)
                {
                    var place = grid.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, true);
                    var name = string.Format("EDITOR-{0}-{1}", cell.ColumnIndex, cell.RowIndex);
                    var editor = grid.Controls.Find(name, false).FirstOrDefault();

                    if (editor == null)
                    {
                        editor = new TextBox();

                        (editor as TextBox).Name = name;

                        grid.Controls.Add(editor);
                    }
                    else
                    {
                        editor.Show();
                    }

                    editor.Size = place.Size;
                    editor.Location = place.Location;
                    editor.Text = Convert.ToString(cell.Value);
                }
            }
        }


text:
Q: Constructor and method not working as expected in Java program Constructor and method not working as expected in Java program
I have the following code:
package principal;
public class Principal {
public static void main(String[] args) {
    Thread filosofos[]=new Thread[5];
    for (int i=0;i<5;i++) {
        System.out.println("loop");
        filosofos[i]=new Thread();
        filosofos[i].start();
    }
    // TODO Auto-generated method stub
}
}

package principal;
public class Filosofo implements Runnable{
static final int tamanho=5;
static int talheres[]=new int[tamanho];
static Semaforo semaforo= new Semaforo(1);
static int quantidade=0;
int id;
public Filosofo(){
    System.out.println("Construtor iniciado.");
    for (int i=0;i<tamanho;i++) {
        talheres[i]=0;
    }
    quantidade++;
    id=quantidade;
}
public void run () {
    System.out.println("Filosofo "+id+" iniciado");
    try {
        // Filosofo pensando
        Thread.sleep(1000);
    } catch (Exception e) {

    }
    semaforo.down();
    System.out.println("Filosofo "+id+" comendo");
    semaforo.up();
}
}

The program should exhibit the string "Construtor iniciado." and the other 2 strings of method run. However when I run the code nothing happens only output that I receive is
loop
loop
loop
loop
loop

why the string of the constructor is not showing up? Why the method run is not running as expected? It looks like the constructor and the method run are not running at all, and I don't know what is going wrong.

A: You have declared class Filosofo but you never create a single instance of it.
Perhaps you want to pass a new instance of Filosofo as thread constructor parameter for each thread?
package principal;

public class Principal
{
    public static void main(String[] args)
    {
        Thread filosofos[]=new Thread[5];

        for (int i=0;i<5;i++) {
            filosofos[i]=new Thread(new Filosofo());
            filosofos[i].start();
        }
    }
}

Except this, instead of using a static field for counting Filosofo instances and assign them an id, why you don't just pass the id in the constructor?
Also the other fields, don't need to be static, pass the shared fields, like semaforo, in the constructor and copy them in a class field.
I don't know the meaning of talheres field and I don't understand why you reinitialize a static field in each instance constructor, maybe you can just initialize once in main and pass that field in the constructor of each Filosofo, as you know, arrays are not copied, only a reference to them is copied.
Also instead of catch (Exception e) you should use catch (InterruptedException e).
You should do something useful with the exception, like printing it.
If you intend to ignore an exception at least you should add a very detailed comment on why you are doing that.

A: You never instantiate any Filosofo, just Threads.


text:
Q: pushing blank rows in the middle of an array google app script javascript I have some data pulling from a sheet.  I have created an array that is sorted by the 2nd column (SKU column) below is what is returned in the spreadsheet:

In this array would like to add a blank row when the SKU changes to make it easier to read.  I wrote the following code:
function update(){

  var mfgSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order Info");
  var purchaseLog = SpreadsheetApp.
    openById("1KkR4jE1c00WuQpPrexW8f9BIq5vxl0fWaUGxbeYERsE").
    getSheetByName("Order Details");

    var orderSort = purchaseLog.getRange(3, 1, purchaseLog.getLastRow(), 15).getValues().
    sort(function(r1,r2){
      var a = r1[1];
      var b = r2[1];
      if(a>b){
        return 1;
      }else if (a<b){
        return -1;}
      return 0;
    }).filter(function (item){if(item[1]!=""&&item[1]!="Purchase Order Link"){return true}})
    .map(function(r){return [r[0],r[1],r[2],r[5],r[6],r[11],r[13],r[12],r[8]]});

  var SKUs = orderSort.map(function(r){return r[1]})

  var SKUList = [];
  for (var i in SKUs) {
    var SKU = SKUs[i];
    var duplicate = false;
    for (var j in SKUList) {
      if (SKU === SKUList[j]) {
        duplicate = true;
      }
    }
    if (!duplicate) {
      SKUList.push(SKU);
    }
  }

  var finalArr = []
  for(var i = 0; i <= SKUList.length-1; i++){
    var element = orderSort.filter(function(item){if(item[1]===SKUList[i]){return true}});
    finalArr.push(element);
    finalArr.push([,,,,,,,,,]);
  }

  Logger.log(finalArr);

}

The code almost works, but I'm getting a weird 3d Array, and I'm afraid that my logic is very wrong.  Photo of the log is also included.  Anyone that could help me solve this problem, it would be greatly appreciated.

A: element is already a 2D array. By pushing it to another array, a 3D array is created. Use Array.concat instead:
finalArr = finalArr.concat(element);//instead of finalArr.push(element);


text:
Q: Javascript function only allowing for one class on an anchor tag I am trying to add a navigation item to a site built by someone else. They wrote a javascript function that is only allowing one class to be on an anchor tag. I need to add a second class to the last navigation item that will give it a border-right. The .last class is already written in CSS and I have put .last on the proper anchor tag, but because of the javascript it will only render .active in the browser and not the .last class. Any ideas on how to do that with this function or with the html I already have? Thanks.
Javascript function:
function setActive() {
  aObj = document.getElementById('navigation').getElementsByTagName('a');
  for(i=0;i<aObj.length;i++) {
  if(document.location.href.indexOf(aObj[i].href)>=0) {
     aObj[i].className='active';
  }
 }
}

window.onload = setActive;

CSS:
#navigation .MainNavigation li a.last{
border-right:#648558 2px solid;
}

#navigation .MainNavigation li a.active{
padding:12px 19px 12px 17px;
background: url(/_images/bkgd_Active.png) repeat;
}

URL of page: http://securitybank.designangler.com/insurance

A: Like this:
aObj[i].className='active anotherclassname';

Or add to existing classes with:
aObj[i].className=aObj[i].className + ' active';

A: You can try this if it's the last item, only with CSS:
#navigation .MainNavigation li:last-child a {
   border-right:#648558 2px solid;
}


text:
Q: Ansible community parted module asking "Are you sure you want to continue", is there an override I am trying to expand an ext4 partition to fill a disk on Alpine using Ansible.
Following the community parted module documentation here I should be able too. However when it comes to performing that action the returned error message says "Warning: Partition /dev/xvda3 is being used. Are you sure you want to continue?\n".
Is there anyway to force this action to proceed on a live system as it looks like Parted is asking for user interaction even though the -s flag is enable?
The task I'm using:
 - name: Read device information
  community.general.parted: device=/dev/xvda unit=MiB
  register: sdb_info

 - name: Extend an existing partition to fill all available space
  community.general.parted:
    device: /dev/xvda
    number: "{{ sdb_info.partitions | length }}"
    part_end: "100%"
    resize: true
    state: present

The full error from ansible-playbook main.yaml -vvvv:
fatal: [10.10.30.100]: FAILED! => {
    "changed": false,
    "err": "Warning: Partition /dev/xvda3 is being used. Are you sure you want to continue?\n",
    "invocation": {
        "module_args": {
            "align": "optimal",
            "device": "/dev/xvda",
            "flags": null,
            "fs_type": null,
            "label": "msdos",
            "name": null,
            "number": 3,
            "part_end": "100%",
            "part_start": "0%",
            "part_type": "primary",
            "resize": true,
            "state": "present",
            "unit": "KiB"
        }
    },
    "msg": "Error while running parted script: /usr/sbin/parted -s -m -a optimal /dev/xvda -- resizepart 3 100%",
    "out": "",
    "rc": 1
}

Target host:

*

*Alpine-VM 3.16.2

*Parted 3.5

*Python 3.10.5

Local:

*

*Ansible 2.13.3

*Python 3.10.4

A: According the documentation community.general and source code community.general/blob/main/plugins/modules/system/parted.py, the module is just a wrapper around the Linux tool parted.
Looking into other similar reports like Ubuntu Launchpad #1270203, the confirmation question
Warning: Partition <part> is being used. Are you sure you want to continue?

seems to be the normal and expected behavior if one tries to resizepart on a mounted partition.

Ansible community parted module asking "Are you sure you want to continue"

So it is not community module which is asking, but the Linux tool parted itself.

is there an override

In the community module itself is currently neither this corner case covered, nor an override implemented yet. Therefore the error message is thrown.
You could

*

*either try to unmount the partition before and mount after resize again with mount module – Control active and configured mount points

*or use the shell module with cmd: /usr/sbin/parted -s -m -a optimal /dev/xvda -- resizepart 3 yes 100% (... or yes | ...) as mentioned in the thread #1270203

*or enhance the behavior of the module by patching and extending the source parted.py accordingly


text:
Q: Is there a built-in way to represent an HRESULT as a winerror.h constant such as E_FAIL? In my C# code I want to be able to log COMExceptions so that not only hex representation of HRESULTs (for example, 0x80004005) is output but also the corresponding WinError.h define symbol (such as E_FAIL) is output.
If I call ToString() on the exception reference there's a hex representation only.
Is there a built-in way to get the E_FAIL-like human-readable constants for the HRESULT values inside COMException objects?

A: Something like this using COMException's HResult property
unchecked
{
    var msg = Marshal.GetExceptionForHR((int)0x80004005).Message;
}

A: Look here - http://msdn.microsoft.com/en-us/library/windows/desktop/ms679351%28v=vs.85%29.aspx at FORMAT_MESSAGE_FROM_SYSTEM. It returns human-readable message about passed error code.


text:
Q: Unity - I'm getting duplicate rewards on admob Reward Based Video Ads So I added a Reward based ad on my Unity Project, I want to reward the user with 300 coins for watching an ad but I'm getting duplicated rewards everytime. I think I know where is the problem, but I can't solve it!
I have this Start Function and a function to get the reward on my Ad Script:
    void Start()
{
    this.rewardBasedVideoAd = RewardBasedVideoAd.Instance;
    rewardBasedVideoAd.OnAdLoaded += HandleOnAdLoaded;
    rewardBasedVideoAd.OnAdOpening += HandleOnAdOpening;
    rewardBasedVideoAd.OnAdClosed += HandleOnAdClosed;
    rewardBasedVideoAd.OnAdRewarded += HandleOnAdRewarded;
    MobileAds.Initialize(initStatus => { });
    this.LoadRewardBasedAd();
}

public void HandleOnAdRewarded(object sender, Reward args)
{
    PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + 300);

}

When you die in the game and want to start again I call SceneManager.LoadScene(0); which is the only Scene I got! I think when I Load Scene the Start function is running again and adding another reward rewardBasedVideoAd.OnAdRewarded += HandleOnAdRewarded;. I've tried calling rewardBasedVideoAd.OnAdRewarded -= HandleOnAdRewarded; several times and in different moments but it didn't solve the problem.
If I restart the game n times in a row, when I watch an ad I will get the Reward n times!
Can someone help me? Thank you in advance!

A: Pretty sure you want to keep only one instance of this GameObject throughout your whole game.
I would call DontDestroyOnLoad for this GameObject.
I think you will need to tweak your Start function, you would need to look if you already have such object in scene before you do your stuff (just tag this GameObject with specific tag and look for objects with that tag in your start function). (Follow example in Unity Documentation I've attached above. DontDestroy.cs is what you need from there)

A: Just add OnDestroy function and unsubscribe from events. That's all.