text:
Q: Importing a package with a keyword in path I'm trying to import a package in which one of the namespaces is the keyword 'import'. How is it best to do this? Would the folder need to be renamed?
Example:
import protobuf.import.import_enum_pb2 as importEnum

This gives an invalid syntax error.
I have started to look at using __ import __ function instead-but wondered if there is a better workaround I haven't found a quotation or escaping method that works.

A: foo_bar = __import__("foo bar")

Also see https://stackoverflow.com/questions/9123517/how-do-you-import-a-file-in-python-with-spaces-in-the-name#:~:text=4%20Answers&text=You%20should%20take%20the%20spaces,supported%20by%20the%20import%20statement.&text=This%20will%20import%20foo%20bar.py%20as%20foo_bar%20.

A: Have found this can be done using importlib
Example:
errorseverity = importlib.import_module(' protobuf.import.import_enum_pb2')

importlib see documentation:
https://docs.python.org/3/library/importlib.html#importlib.import_module


text:
Q: How to use async/await in a single function I am using google places api to get a list off cafes nearby. So,the api provides max 60 places but they are present in 3 different pages.To get the list of all 60 places, it provides tokens in the first and second page with the help of which we can access remaining places. I wrote a function that stores the place ids in an array.The places from first page is storing fine. But, in the first request i am accessing the token for the next page. The problem i am facing is, the request for second page is being called before assigning of the token.So, it results in an error. How can i make the reqeust for second page to wait until the token value is assigned?
const request= require('postman-request');
const nearbycafes = (latitude,longitude,callback) => {
var placeids=[];
let token;
let count=0;
const url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+latitude+','+longitude+'&radius=1500&type=cafe&key=xyz'
request({url: url, json: true},(error,response)=>{
    console.log('ssss');
    if(error){
        callback('Error connecting to the API',undefined)
    }

    else if(response.body.results.length==0){
        callback('No such address exist. Try something else',undefined)
    }
    else{
            let i=0;
            //for(i;i<response.body.results.length;i++){
                placeids.push(response.body.results[0].place_id)
            //}
            if(response.body.next_page_token){
                 token=response.body.next_page_token;
                 count++;
                 console.log(count);
            }
        }
        callback(undefined,{
            placeids
        })

})
console.log(count);
// if(count===1){
//     const url2='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+latitude+','+longitude+'&radius=1500&type=cafe&key=xyz='+token+''
//     request({url: url2, json: true},(error,response)=>{
//         console.log('ssss2');
//         if(error){
//             callback('Error connecting to the API',undefined)
//         }

//         else if(response.body.results.length==0){
//             callback('No such address exist. Try something else',undefined)
//         }
//         else{
//                 let i=0;
//                 for(i;i<response.body.results.length;i++){
//                     placeids.push(response.body.results[i].place_id)
//                 }
//                 if(response.body.next_page_token){
//                     token=response.body.next_page_token;
//                     count++;
//                 }
//             }
//             callback(undefined,{
//                 placeids
//             })

//     })
// }

}

module.exports = nearbyhospitals;

A: You need to write a recursive function to get all the pages sequentially:
const request = require('postman-request')

function getPage (lat, long, token, cb) {
  const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${long}&radius=1500&type=cafe&key=xyz${token ? `&token=${token}` : ''}`
  request({ url: url, json: true }, (error, response) => {
    if (error) {
      cb(new Error('Error connecting to the API'), undefined)
    } else if (response.body.results.length === 0) {
      cb(null, [])
    } else {
      if (response.body.next_page_token) {
        getPage(lat, long, response.body.next_page_token, (err, res) => {
          if (err) {
            return cb(err)
          }
          cb(undefined, res.concat(response.body.results))
        })
      } else {
        cb(undefined, response.body.results)
      }
    }
  })
}

function nearbycafes (latitude, longitude, callback) {
  getPage(latitude, longitude, undefined, callback)
}
module.exports = nearbycafes

// just to try
nearbycafes(43.834527, 13.258358, (err, res) => {
  console.log({ err, res })
})

A: Unfortunately, I cannot see the 'second' request in the code above. I assume the second request is being done in the 'callback' function. If you want to be sure that 'token' is not empty when 'callback' is executed, simply call the callback directly after assignment:
    else{
        let i=0;
        //for(i;i<response.body.results.length;i++){
            placeids.push(response.body.results[0].place_id)
        //}
        if(response.body.next_page_token){
             token=response.body.next_page_token;
             callback(undefined, { placeids: placeids });
             count++;
             console.log(count);
        }
    }

It appears that the positive (I assume) 'callback' call is outside of the 'else' clause. You sure you got the braces correct?
Best approach, though, is to avoid such 'global' variables as token in this case. You could parametrize callback and pass the token via function call. The rule of thumb in such chained requests is as follows:
function A(callback) {
    $.ajax({
        //...
        success: function (result) {
            //...
            $.ajax({
                // ...
                success: function (result) {
                // ...
                }
            })
        }
    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove a list of words from beginning of a sentence I have a list of words to remove from beginning of a sentence.
With this code i am able to remove only 1 word from the beginning of string, in this example the word 'Hello'
    for($i=0; $i<strlen(string); $i++){
    $remove = 'Hello';
    if (substr(string, 0, strlen($remove)) == $remove) {
    string = substr(string, strlen($remove));}
    string=ucfirst(string);}

 input :Hello World.
 output:World.

how to modify this code and add a list of words to remove using the code once? maybe an array of words will be great.
Also im able to use this code several times for each word that i have to remove but in terms of performance i think will peform slow. any help? thanks

A: Try to use PHP preg_replace function.
$string = 'Hello world Hello';

$patterns = array();
$patterns[0] = '/Hello/';

$replacements = array();
$replacements[0] = '';

ksort($patterns);
ksort($replacements);

echo preg_replace($patterns, $replacements, $string, 1);

reference: http://www.php.net/manual/en/function.preg-replace.php

A: I would explode the string into an array.
$string = 'these are words some of which may be bad like this1 this2 and this3';

$words = explode(' ', $string);

foreach($words as $word) {

   // Insert function to check your list of words against an array remove
   // and even replace them with your own.
   // View: preg_replace http://us2.php.net/manual/en/function.preg-replace.php

}


text:
Q: "In preparation for" or "In Preparation of"? What´s the difference in use between "in preparation of" or "in preparation for"? They seem both correct.
Context:

The team practiced how they would respond to bad weather in
  preparation of Election Day.

A: It depends entirely on context, and is dictated by the meanings of the separate prepositions 'of' and 'for':
'I am making plans in preparation for my daughter's wedding' but; 'I haven't made the cake yet, I am still involved with preparation of the ingredients'.


text:
Q: Error While Creating Nested Table in Oracle Below is the Tables i have created.
CREATE TYPE ft_obj AS OBJECT (
    ftid         NUMBER(5),
    ftlocation   VARCHAR(30),
    country      VARCHAR(10)
);
/

CREATE TABLE ft_table OF ft_obj (
    ftid PRIMARY KEY
) OBJECT IDENTIFIER IS PRIMARY KEY;
/

CREATE TYPE frod_obj AS OBJECT (
    prodid           NUMBER(6),
    ft_ref           ft_obj,
    proddesc         VARCHAR(50),
    costperitem      DECIMAL,
    labcostperitem   DECIMAL
);
/

CREATE TABLE frod_table OF frod_obj (
    prodid PRIMARY KEY
) OBJECT IDENTIFIER IS PRIMARY KEY;

CREATE TYPE wf_obj AS OBJECT (
    wfid           NUMBER,
    ft_ref         ft_obj,
    wfname         VARCHAR(30),
    taxcode        INT,
    yearlyincome   DECIMAL,
    yearlytax      DECIMAL
);
/

CREATE TABLE wf_table OF wf_obj (
    wfid PRIMARY KEY
) OBJECT IDENTIFIER IS PRIMARY KEY;
/

CREATE TYPE wfusage_obj AS OBJECT (
    jobdate         DATE,
    jobhours        INT,
    jobhourlyrate   DECIMAL,
    jobposted       CHAR,
    wfid_ref        REF wf_obj
);
/

CREATE TYPE wfusage_nesttabtyp AS
    TABLE OF wfusage_obj;
/

CREATE TABLE wfusage_objtab OF wfusage_obj;
/

CREATE TYPE odetails_obj AS OBJECT (
    mfid           NUMBER,
    prodid_ref     REF frod_obj,
    quantity       INT,
    itemprice      DECIMAL,
    wfusage_ntab   wfusage_nesttabtyp
);
/

CREATE TYPE odetails_nesttabtyp AS
    TABLE OF odetails_obj;
/

CREATE TYPE prod_obj AS OBJECT (
    prodoid          NUMBER,
    odate            DATE,
    promisedate      DATE,
    completiondate   DATE,
    shipmentdate     DATE,
    status           VARCHAR(20),
    odetails_ntab    odetails_nesttabtyp
);
/

CREATE TABLE prod_objtab OF prod_obj (
    PRIMARY KEY ( prodoid )
) OBJECT IDENTIFIER IS PRIMARY KEY
NESTED TABLE odetails_ntab STORE AS oprod_ntab ( (
    PRIMARY KEY ( nested_table_id,
                  mfid )
)
ORGANIZATION INDEX
COMPRESS ) RETURN AS LOCATOR
/

ALTER TABLE oprod_ntab ADD (
    SCOPE FOR ( prodid_ref ) IS frod_table
);
/

Getting the below error while creating Nested Table.

ORA-02320: failure in creating storage table for nested table column
  odetails_ntab  ORA-25175: no PRIMARY KEY constraint found
  02320. 00000 -  "failure in creating storage table for nested table column %s"
  *Cause:    An error occurred while creating the storage table for the
             specified nested table column.
  *Action:   See the messages that follow for more details. If the situation
             they describe can be corrected, do so; otherwise contact Oracle
             Support.

    INSERT INTO prod_objtab  VALUES ( 45000,
    '12-April-2019',
    '01-MAy-2019',
    '01-MAy-2019',
    '01-MAy-2019',
    'COMPLETED',
    odetails_nesttabtyp()
);
INSERT INTO TABLE (SELECT pr.odetails_ntab  FROM prod_objtab pr WHERE pr.prodorderid = 45000 )
                    values (45001,(SELECT REF(pt) FROM frod_table pt WHERE pt.prodid = 10001 ),100,500,
                    wfusage_nesttabtyp(wfusage_obj('12-April-2019',60,100,'AME',
                    (SELECT REF(wf) FROM wf_table wf WHERE wf.wfid = 240))));

getting the error in line 9
ORA-01401: inserted value too large for column

A:
ORA-02320: failure in creating storage table for nested table column
  odetails_ntab ORA-25175: no PRIMARY KEY constraint found 02320. 00000
  - "failure in creating storage table for nested table column %s" *Cause: An error occurred while creating the storage table for the specified nested table column. *Action: See the messages that follow
  for more details. If the situation they describe can be corrected, do
  so; otherwise contact Oracle Support.

Since you have done Multi-level nesting, while creating the table you need 2 levels of Storage as well for the Nested tables. See below how you can do it.
CREATE TABLE prod_objtab OF prod_obj (
    PRIMARY KEY ( prodoid )
) OBJECT IDENTIFIER IS PRIMARY KEY
NESTED TABLE odetails_ntab STORE AS oprod_ntab ( ( PRIMARY KEY (NESTED_TABLE_ID, mfid ))
ORGANIZATION INDEX COMPRESS
NESTED TABLE wfusage_ntab STORE AS  XX ) RETURN AS LOCATOR;

Read more at
https://docs.oracle.com/en/database/oracle/oracle-database/18/adobj/multilevel-collection-types.html#GUID-76D5A6B0-28AD-483D-942C-B7F3B90AC379


text:
Q: Get the current store -Ext JS Simple question here,
I have a grid in my application that can hold one of any 3 given stores (utlizes bindStore() function).
Is there a function to retrieve the current store? Something like: Ext.getStore(grid.currentStore());
Cheers!

A: Solution was much easier than I thought. All I had to do was: `var store = Ext.getCmp('grid').getStore();'

A: Ext.StoreMgr.lookup('store id'); will return store for you.


text:
Q: Grunt serve adds '#' in the url I'm trying to build a simple web app (I'm newbie in Node.js, Yeoman, Grunt) and I'm following this great tutorial - "Build a M.E.A.N web app".
The only thing that I don't understand is why when running
grunt serve

I got urls like localhost:9000/#/projects. What's the point of the '#'?
Any help would be greatly appreciated.
Here you could find my gruntfile.

A: It's not because of grunt serve, hashtag adds angular. It is how browser works with single page application(SPA). When you don't reload your page, client javascript needs to know how to route requests and display views. If you want to turn off this feature, you need to switch it in angular with:
$locationProvider
  .html5Mode(true)

More on question you can read here


text:
Q: Exception in internal-nlog when returning a File(MemoryStream) from a controller action After updating my app to .net core 3.1, I started noticing new logs in the internal-nlog files such as:
2020-07-23 23:49:07.0858 Warn Failed to get property value for object: System.IO.MemoryStream Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.InvalidOperationException: Timeouts are not supported on this stream.
   at System.IO.Stream.get_ReadTimeout()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at NLog.Internal.ObjectReflectionCache.ObjectPropertyList.Enumerator.get_Current()

The app itself is functional and working, it is just that this log pops up.
I managed to track it down to an nlog update from 4.5.6 to 4.7.2. After some playing around I came to the conclusion that the log entry does not appear on nlog 4.5.11, and it starts to appear on nlog 4.6.0
The log entry is written (twice) after exiting a particular controller action. It can be summed up as:
var stream = generateMemoryStream();
return this.File(stream,mediatype,somefilename);

The possibly relevant nlog config chunk is below
<target xsi:type="File" name="jsonFile" fileName="Logs\nlog-json-${shortdate}.log" >
      <layout type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level}"/>
        <attribute name="message" layout="${message}"/>
        <attribute name="templatedMessage" layout="${message:raw=true}" />
        <attribute name="exception" encode="false">
          <layout type='JsonLayout'>
            <attribute name="message" layout="${exception:format=message}" />
            <attribute name="type" layout="${exception:format=shortType}" />
            <attribute name="stackTrace" layout="${exception:format=stackTrace}" />
            <attribute name="data" layout="${exception:format=Data}" />
          </layout>
        </attribute>
        <attribute name="eventProperties" encode="false">
          <layout type='JsonLayout' includeAllProperties="true"  maxRecursionLimit="2"/>
        </attribute>
      </layout>
    </target>

Has anyone else noticed this behaviour? Or can point me in a certain direction?

A: Until NLog 4.7.3 is released then you can prevent reflection of Stream-objects with the following code:
NLog.LogManager.Setup().SetupSerialization(s =>
   s.RegisterObjectTransformation<System.IO.Stream>(o => o.ToString()));

This will remove the noise coming from NLog trying to perform property-reflection of Stream-objects.


text:
Q: Python: Replace a list in place from where it is referenced, not create a new reference/list I am working with quite big number of values in Python (memory footprint is 5GB).
Sometimes, I need to access values by key, sometimes I need to loop values. For performance reasons, I am converting the Dict to a List at startup, so I can:

*

*use the Dict in cases where I want to access values by key

*use the List in cases where I want to loop values

my_big_dict_of_values
my_big_values_list = list(my_big_dict_of_values.values())

Here's a performance comparison, just for clarity:
>some_dict = dict(zip(range(1000000), reversed(range(1000000))))
>some_list = list(some_dict.values())
>%timeit for t in some_dict.values(): t
21.1 ms ± 483 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
>%timeit for t in some_list: t
16.1 ms ± 1.31 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

My problem arises when I need to delete keys from the dict based on user input.
First, I delete entries from the dict with:
for key in keys_to_remove:
    del(my_big_dict_of_values[key])

After this operation, I also want to update my_big_values_list. I can do this with:
Solution A (Slow)
indexes_to_remove = list()
for idx, value in enumerate(my_big_values_list):
    if value.key in keys_to_remove:
        indexes_to_remove.append(idx)
for index in sorted(indexes_to_remove, reverse=True):
    del my_big_values_list[index]

However, this is really slow and cumbersome.
Ideally, I would like to just create the list from the dict again with:
Solution B (Fast with reference issue)
my_big_values_list = list(my_big_dict_of_values.values())

This is fast, but it seems to create a new reference. I would need to replace all references of my_big_values_list passed to other classes/functions, which appears strange, e.g. to illustrate.
my_big_dict_of_values
my_big_values_list = list(
    my_big_dict_of_values.values())

handle_process = handle_process_class(
    my_big_dict_of_values, my_big_values_list)

userinput = userinput(handle_process)

handle_process.calculate()

def userinput_class():
    def __init__(handle_process):
        self.handle_process = handle_process
    def user_del_key(key):
        del(self.handle_process.my_big_dict_of_values[key])
        # Update list here too:
        # Solution A works
        # Solution B throws error in
        # handle_process.calculate() because
        # handle_process still has old list

def handle_process_class():
    def __init__(my_big_dict_of_values, my_big_values_list):
        self.my_big_dict_of_values = my_big_dict_of_values
        self.my_big_values_list = my_big_values_list
    def calculate(self):
        return len(self.my_big_values_list)

Is there a way to modify my_big_values_list in place, but simply replace with a new list (e.g. list(my_big_dict_of_values.values())).
I have read how Python passes references to values, and I think I understand most of it. That's why I came up with solution A, but I don't know how to use Solution B to modify the referenced list. Perhaps someone can explain what is going on here?

A: To modify the list in-place, assign to its slice:
my_big_values_list[:] = list(my_big_dict_of_values.values())

Example:
>>> my_big_dict_of_values = {"a": 1, "b": 2, "c": 3}
>>> my_big_values_list = list(my_big_dict_of_values.values())
>>> another_list_reference = my_big_values_list

>>> print(my_big_values_list, another_list_reference)
[1, 2, 3] [1, 2, 3]

>>> del(my_big_dict_of_values["b"])
>>> my_big_values_list[:] = list(my_big_dict_of_values.values())

>>> print(my_big_values_list, another_list_reference)
[1, 3] [1, 3]

However in terms of performance and memory usage, you should consider if a separate huge list is really necessary, as you can loop directly over dictionary.values().


text:
Q: Combining lines in a txt file to complete phrases File content as follows (it's a part of video subtitles).
I want to combine lines to complete phrases.
1
00:00:00,000 --> 00:00:13,680
Je vais mettre en direct sur l'hôtel comme ça on peut regarder les messages et tout.

2
00:00:13,680 --> 00:00:14,680
Ouais.

3
00:00:14,680 --> 00:00:20,080
Tiens je vais recevoir la notification Romain étant direct.

4
00:00:20,080 --> 00:00:22,720
Vas-y ouvrez le live.

5
00:00:22,720 --> 00:00:25,640
Ouais c'est bon on vous entend.

6
00:00:25,640 --> 00:00:26,640
Nice.

7
00:00:26,640 --> 00:00:28,480
Attends je vais présenter vite fait du coup, je vais attendre que tout le monde vienne.

8
00:00:28,480 --> 00:00:40,640
Salut Raphaël, salut Ismaël, salut Jean-Marc, bonjour à tous, bonjour Clément, bonjour

9
00:00:40,640 --> 00:00:41,640
Thierry.

10
00:00:41,640 --> 00:00:42,640
Bonjour à tous.

11
00:00:42,640 --> 00:00:44,640
Je ne sais pas s'ils nous entendent ou pas normalement.

12
00:00:44,640 --> 00:00:45,640
Si si ils t'entendent là.

13
00:00:45,640 --> 00:00:46,640
On va attendre.

14
00:00:46,640 --> 00:00:51,480
Limite on peut nous filmer en attendant que ça démarre vite fait, attends.

15
00:00:51,480 --> 00:00:53,360
Je vais vous filmer vous.

16
00:00:53,360 --> 00:00:57,520
Bon les gars juste pour faire une petite précision aujourd'hui on va avoir deux intervenants,

17
00:00:57,520 --> 00:01:02,560
on va avoir, je vais couper ma tête, on va avoir du coup CP Dropshipping, je pense que

18
00:01:02,560 --> 00:01:06,320
vous le connaissez, il a une chaîne YouTube, il a un compte Facebook assez suivi donc voilà

19
00:01:06,320 --> 00:01:11,520
avec un très beau t-shirt Balenciaga et aussi Jérémy donc on a deux Dropshippers qui pèsent

20
00:01:11,520 --> 00:01:16,960
assez lourd et voilà Jérémy c'est un administrateur du Discord et qui commence à faire tout

21
00:01:16,960 --> 00:01:21,520
est bien, qui commence à faire pas mal de souis, qui va venir habiter sur Malte bientôt

22
00:01:21,520 --> 00:01:22,520
je crois.

23
00:01:22,520 --> 00:01:25,520
On a regardé les vidéos d'avion là tout à l'heure.

24
00:01:25,520 --> 00:01:28,520
Il faudrait que je le ramène une semaine.

25
00:01:28,520 --> 00:01:30,320
Ah merde, je me suis trompé.

I have a txt file in the above format and I want to convert this file with DeepL.
However, in this file, the translation is inaccurate because the sentences are not always complete.
So what I want to do is if the sentence in one line is not finished, I add the parts of the
next lines to that line until that sentence is complete and delete the parts I added from the other lines.
1
00:00:00,000 --> 00:00:13,680
Je vais mettre en direct sur l'hôtel comme ça on peut regarder les messages et tout.

2
00:00:13,680 --> 00:00:14,680
Ouais.

3
00:00:14,680 --> 00:00:20,080
Tiens je vais recevoir la notification Romain étant direct.

4
00:00:20,080 --> 00:00:22,720
Vas-y ouvrez le live.

5
00:00:22,720 --> 00:00:25,640
Ouais c'est bon on vous entend.

6
00:00:25,640 --> 00:00:26,640
Nice.

7
00:00:26,640 --> 00:00:28,480
Attends je vais présenter vite fait du coup, je vais attendre que tout le monde vienne.

8
00:00:28,480 --> 00:00:40,640
Salut Raphaël, salut Ismaël, salut Jean-Marc, bonjour à tous, bonjour Clément, bonjour Thierry.

9
00:00:40,640 --> 00:00:41,640

10
00:00:41,640 --> 00:00:42,640
Bonjour à tous.

11
00:00:42,640 --> 00:00:44,640
Je ne sais pas s'ils nous entendent ou pas normalement.

12
00:00:44,640 --> 00:00:45,640
Si si ils t'entendent là.

13
00:00:45,640 --> 00:00:46,640
On va attendre.

14
00:00:46,640 --> 00:00:51,480
Limite on peut nous filmer en attendant que ça démarre vite fait, attends.

15
00:00:51,480 --> 00:00:53,360
Je vais vous filmer vous.

16
00:00:53,360 --> 00:00:57,520
Bon les gars juste pour faire une petite précision aujourd'hui on va avoir deux intervenants, on va avoir, je vais couper ma tête, on va avoir du coup CP Dropshipping, je pense que vous le connaissez, il a une chaîne YouTube, il a un compte Facebook assez suivi donc voilà avec un très beau t-shirt Balenciaga et aussi Jérémy donc on a deux Dropshippers qui pèsent assez lourd et voilà Jérémy c'est un administrateur du Discord et qui commence à faire tout est bien, qui commence à faire pas mal de souis, qui va venir habiter sur Malte bientôt je crois.

17
00:00:57,520 --> 00:01:02,560

18
00:01:02,560 --> 00:01:06,320

19
00:01:06,320 --> 00:01:11,520

20
00:01:11,520 --> 00:01:16,960

21
00:01:16,960 --> 00:01:21,520

22
00:01:21,520 --> 00:01:22,520

23
00:01:22,520 --> 00:01:25,520
On a regardé les vidéos d'avion là tout à l'heure.

24
00:01:25,520 --> 00:01:28,520
Il faudrait que je le ramène une semaine.

25
00:01:28,520 --> 00:01:30,320
Ah merde, je me suis trompé.

For doing this, I've tried this lines of code. But I couldn't complete and understood what to do exactly
import re

file = open('files/FINAL/v23FINAL.srt')
content = file.readlines()
new = ''

i = 2
max = len(content) - 1

while i < max :
    now = str(content[i][-2])
    next = str(content[i+4][-2])

    print(now + '\n' + next)

    if now != '.' or now != '?' or now != '!':
        for j in range(len(content[i+4])):
            if content[i+4][j] == '.' or content[i+4][j] == '?' or content[i+4][j] == '!':
                print(content[i+4][0:j+1])
                print(content[i+4][j+2:len(content)-2])
                break

        i += 4

    else:
        new += content[i]
        new += content[i+1]
        new += content[i+2]
        new += '\n'

        i += 4

with open('newText.srt', 'a') as n:
    n.write(new)

A: You should split the file into records by its record separator, double newlines, then extract the lines and their headers, save them into lists, and defer producing output from the lists until the current line ends with a sentence ending character:
with open('input.srt') as file:
    lines = []
    headers = []
    for record in file.read().split('\n\n'):
        number, time, line, *_ = record.split('\n')
        lines.append(line)
        headers.append(f'{number}\n{time}')
        if line[-1] in '.!?':
            print(headers.pop(0))
            print(' '.join(lines), end='\n\n')
            if headers:
                print('\n\n'.join(headers), end='\n\n')
            lines = []
            headers = []

Demo: https://replit.com/@blhsing/ImportantVioletAutoresponder


text:
Q: Create test instance in Junit 5 with factory method (no dynamic test) Using JUnit 4, one could take control over test instance lifecycle using runners. For instance, I used to implement method createTest() of BlockJUnit4ClassRunner to have a fine-tuned instance creation (in my case, use Weld to retrieve a CDI-ready instance).
With JUnit 5, extensions are supposed to replace runners and rules. Yet, I cannot find a way to hook into test instance creation the way I could with JUnit 4.
Is there a way to tell JUnit Jupiter how to create my test instance (for example, using Weld container) without using dynamic tests?
Here is what I do now in JUnit 4, and want to be able to do in Jupiter:

public class ContainerRunner extends BlockJUnit4ClassRunner {

    private WeldContainer container;

    ...

    @Override
    public Object createTest() {
        return container.select(this.getTestClass().getJavaClass()).get();
    }
}

And later:
@RunWith(ContainerRunner.class)
@Singleton
public class ContainedTest {

    @Inject
    private Logger logger;  // this works

    @Test
    public void testSomething() {
        ...
    }
}

Thanks for any insights.

A: By now, it's probably best to use one of the two Weld JUnit 5 Extensions.
But to answer your question directly, you can (3 years later) write an extension that implements TestInstanceFactory, i.e.:
class ContainerExtension implements TestInstanceFactory {
    private WeldContainer container;

    @Override public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext) throws TestInstantiationException {
        return container.select(this.getTestClass().getJavaClass()).get();
    }
}

Then your test uses @ExtendWith(ContainerExtension.class) instead of @RunWith(ContainerRunner.class).


text:
Q: How to do two requests in parallel I have the following code which requests something from Amazon's API:
params = {'Operation': 'GetRequesterStatistic', 'Statistic': 'NumberHITsAssignable', 'TimePeriod': 'LifeToDate'}
response = self.conn.make_request(action=None, params=params, path='/', verb='GET')
data['ActiveHITs'] = self.conn._process_response(response).LongValue

params = {'Operation': 'GetRequesterStatistic', 'Statistic': 'NumberAssignmentsPending', 'TimePeriod': 'LifeToDate'}
response = self.conn.make_request(action=None, params=params, path='/', verb='GET')
data['PendingAssignments'] = self.conn._process_response(response).LongValue

Each of these requests takes about 1s waiting for Amazon to return data. How would I run both of these in parallel, so it would (ideally) take 1s to run, instead of 2s?

A: You can use a multiprocessing.Pool to parallelize the requests:
from multiprocessing import Pool

class Foo:
    def __fetch(self, statistic):
        params = {
            'Operation': 'GetRequesterStatistic',
            'Statistic': statistic,
            'TimePeriod': 'LifeToDate'
        }
        response = self.conn.make_request(
            action=None, params=params, path='/', verb='GET'
        )
        return self.conn._process_response(response).LongValue

    def get_stats(self):
        pool = Pool()
        results = pool.map(self.__fetch, [
            'NumberHITsAssignable', 'NumberAssignmentsPending'
        ])
        data['ActiveHITs'], data['PendingAssignments'] = results

this has the nice effect of being able to parallelize any given number of requests. By default, a worker per core is created, you can change the number by passing it a parameter to the Pool.


text: Q: Reducing delay of appearance of circle in secure UITextField I have a UITextField where I want to type a password and also, I have set UITextField secure property in IB. Now, my question is that When I am typing the password, it shows the characters for some duration and then shows the black circles, how can I reduce this delay?


text:
Q: wrong output when there is tag is inside flex container I have problem with flexbox. Whenever I put some tag inside the format (visible output) is wrong.
HTML:

IMG

Some text here.

Cause of A tag [Cause of A tag]
 (this is inside A tag) [(this is inside A tag)]
 flexbox is displayed wrong [flexbox is displayed wrong]

CSS:
.container
{background:black;
padding:10px;
display:flex;}

.line1
{border:2px solid blue;
padding:10px;
background:yellow;}

.line2
{display:flex;
align-items:center;
align-self:stretch;
border:3px solid blue;
padding:10px;
background:yellow;}

.line3
{display:flex;
align-items:center;
align-self:stretch;
border:3px solid blue;
padding:10px;
background:yellow;}

.one
{padding:10px;
background:red;}

What I want to do is to align-items:center; at .line3 but I need to set up display:flex; to do so. But the the format is gone... and  has some space around.
https://jsfiddle.net/4025gLo8/4/ - wih flex (item are centered but there is  problem)
https://jsfiddle.net/b8amyfog/4/ - without flex (proper format, but without align-items:center;  or align-self:stretch; etc.)

A: If I am understanding your question correctly, you want everything from the second fiddle + the content in line 3 to align to the center of the container. If that is what you want, I think this fiddle might solve your problem: https://jsfiddle.net/mk3xh1fe/
^ Let me know if that is what you were looking for.
The issue was that, since you're using display: flex on the div, and there are several elements within that div, they need to be told to align as a column rather than a row (which is the default).
Also, I enforced some code styling rules here to your css to follow standards and that, in my opinion, make the css more readable.
Hope this helps!


text:
Q: Ensuring the Multinomial Counting Theorem Produces Integer Coefficients As a result of the Multinomial Counting Theorem, we get that the number of ways to distinctly arrange $n$ objects with groups of identical objects each with length $a_1, a_2, ..., a_k$ is equal to:
$$\binom{n}{a_1,a_2,...,a_k} = \frac{n!}{a_1!a_2!\dots a_k!}$$
How do we ensure that this number is always an integer. In other words, given $n \in \mathbb{Z} \wedge (a_1,a_2,...,a_k) = \mathbb{Z}^k \wedge \sum a_i = n$, show that:
$$\frac{n!}{a_1!a_2!\dots a_k!} \in \mathbb{Z}$$
The best "proof" I can think of is combinatorially, and it's rather intuitive because it's the number of ways to arrange certain objects, so it must be an integer. Is there an algebraic way to show this?

A: $\binom{n}{a_1,a_2,...,a_k} = \frac{n!}{a_1!a_2!\dots a_k!} = \binom{n}{a_1}\binom{n-a_1}{a_2}...\binom{(n-\sum_{i=1}^{k-1} a_i)}{a_k}$ and we know each is an integer.


text:
Q: How to get exit status or completion message from an asynchronous gcloud sql export job? I have a daily export task for pulling data from gcloud sql to a bucket in cloud storage, but the job winds up timing out and gcloud sends back an error saying this. Nonetheless, the SQL instance continues running the export, and the files make it to their destination, no problem.
In order to get around the timeout error, which is fouling up our logs, I have tried adding the --async flag, which gets around the error as it should, but there is no exit or completion message.
gcloud --project=$PROJECT sql export csv cloud-sql --database=$DB $BUCKET/$(date +%Y%m%d)_$NAME.csv --async --query="cat $SQLPATH/$table.sql" >> $LOG 2>&1
Is there some bash code or modification I can make to receive a status update or exit response to that I can accurately log that the job has been completed?

A: You can start this bash code at the same time you issue the command in another process. It has a function that gets the status of the operation (whose id is saved in the log), then the first status read and the next ones are compared until they are different, and the status is printed periodically:

OPERATION=$(cat $LOG|tr / \ | awk '{print $NF}'| tail -n 1)
get_status(){
    CURRENT_STATUS=$(gcloud sql operations describe $OPERATION | grep status: | awk '{print $NF}')
}
FIRST_STATUS=$CURRENT_STATUS
echo FIRST STATUS: $FIRST_STATUS
while [ $FIRST_STATUS == $CURRENT_STATUS ]
do
    get_status
echo CURRENT STATUS: $CURRENT_STATUS
sleep 5
done
echo CURRENT STATUS: $CURRENT_STATUS
echo DONE!


text:
Q: Best way to select most recent record So the database I am using does not have a great way to select the most recent number by its unique ID. We have to narrow down to get the most recent record with a bunch of sub queries joining back to the original table. The original table is TBL_POL.
Ex.
Policy_ID   Load_DATE   ENDORSEMENT#    SEQUENCE    EXTRACTDATE
25276       8/16/2015       0               1        8/15/2015
25276       2/13/2016       1               2        2/12/2016
25276       9/24/2016       3               4        9/20/2016
25276       9/24/2016       3               4        9/20/2016
25276       9/24/2016       2               3        9/20/2016

so first we grab the max load date and join back to the original table and then grab the max endorsement # and then join back and grab the max sequence and then join back and get the max extract date to finally get back to our final record so it will be unique. Above is an example.
Is there an easier way to do this? Someone mentioned row_number() over(partition by), but I think that just returns the whatever row number you would like. I am for a quick way to grab the most record with all these above attributes in one swipe. Does anyone have a better idea to do this, because these queries take a little while to run.
Thanks

A: @Bryant,
First, @Backs saved this post for you.  When I first looked at it I thought "Damn. If he doesn't care to spend any time making his request readable, why should I bother"?  Further, if you're looking for a coded example, then it would be good to create some readily consumable test data to make it a whole lot easier for folks to help you.  Also, as @Felix Pamittan suggested, you should also post what your expected return should be.
Here's one way to post readily consumable test data.  I also added another Policy_ID so that I could demonstrate how to do this for a whole table instead of just one Policy_ID.
--===== If the test table doesn't already exist, drop it to make reruns in SSMS easier.
     -- This is NOT a part of the solution. We're just simulating the original table
     -- using a Temp Table.
     IF OBJECT_ID('tempdb..#TBL_POL','U') IS NOT NULL
   DROP TABLE #TBL_POL
;
--===== Create the test table (technically, a heap because no clustered index)
     -- Total SWAG on the data-types because you didn't provide those, either.
 CREATE TABLE #TBL_POL
        (
         Policy_ID      INT     NOT NULL
        ,Load_DATE      DATE    NOT NULL
        ,ENDORSEMENT#   TINYINT NOT NULL
        ,SEQUENCE       TINYINT NOT NULL
        ,EXTRACTDATE    DATE    NOT NULL
        )
;
--===== Populate the test table
 INSERT INTO #TBL_POL
        (Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE)
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM (VALUES
        --===== Original values provided
         (25276,'8/16/2015',0,1,'8/15/2015')
        ,(25276,'2/13/2016',1,2,'2/12/2016')
        ,(25276,'9/24/2016',3,4,'9/20/2016')
        ,(25276,'9/24/2016',3,4,'9/20/2016')
        ,(25276,'9/24/2016',2,3,'9/20/2016')
        --===== Additional values to demo multiple Policy_IDs with
        ,(12345,'8/16/2015',0,1,'8/15/2015')
        ,(12345,'9/24/2016',1,5,'2/12/2016')
        ,(12345,'2/13/2016',1,2,'2/12/2016')
        ,(12345,'9/24/2016',3,4,'9/20/2016')
        ,(12345,'9/24/2016',3,4,'9/20/2016')
        ,(12345,'9/24/2016',2,3,'9/20/2016')

        ) v (Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE)
;
--===== Show what's in the test table
 SELECT *
   FROM #TBL_POL
;

If you are looking to resolve your question for more than one Policy_ID at a time, then the following will work.
--===== Use a partitioned windowing function to find the latest row
     -- for each Policy_ID, ignoring "dupes" in the process.
     -- This assumes that the "sequence" column is king of the hill.
   WITH cteEnumerate AS
        (
         SELECT *
                ,RN = ROW_NUMBER() OVER (PARTITION BY Policy_ID ORDER BY SEQUENCE DESC)
           FROM #TBL_POL
        )
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM cteEnumerate
  WHERE RN = 1
;

If you're only looking for one Policy_ID for this, the "TOP 1" method that @ZLK suggested will work but so will adding a WHERE clause to the above.  Not sure which will work faster but the same indexes will help both.  Here's the solution with a WHERE clause (which could be parameterized).
--===== Use a partitioned windowing function to find the latest row
     -- for each Policy_ID, ignoring "dupes" in the process.
     -- This assumes that the "sequence" column is king of the hill.
   WITH cteEnumerate AS
        (
         SELECT *
                ,RN = ROW_NUMBER() OVER (PARTITION BY Policy_ID ORDER BY SEQUENCE DESC)
           FROM #TBL_POL
          WHERE Policy_ID = 25276
        )
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM cteEnumerate
  WHERE RN = 1
;

A: May be you should try Grouping SET
Throw another sample data.
Also i am not sure about performance.
Give Feedback but result and performance both
SELECT *
FROM (
    SELECT Policy_ID
        ,max(Load_DATE) Load_DATE
        ,max(ENDORSEMENT#) ENDORSEMENT#
        ,max(SEQUENCE) SEQUENCE
        ,max(EXTRACTDATE) EXTRACTDATE
    FROM #TBL_POL t
    GROUP BY grouping SETS(Policy_ID, Load_DATE, ENDORSEMENT#, SEQUENCE, EXTRACTDATE)
    ) t4
WHERE Policy_ID IS NOT NULL

     drop table #TBL_POL


text:
Q: Optimizing calculating combination and avoiding overflows I am solving a programming problem which is stuck at calculating nCr efficiently and at the same time avoiding overflows. I have made the following trivial simplification but am just curious about if there are any more sophisticated simplifications available out there.
(n)!/(n-k)!*k! = n*(n-1)*.....*(max(n-k+1, k))/(min(n-k, k-1))
Can there be any more simplification possible considering different cases for k as even or odd, just suggesting a way.
Any comment is appreciated.

A: I found an interesting solution here: http://blog.plover.com/math/choose.html
    unsigned choose(unsigned n, unsigned k) {
      unsigned r = 1;
      unsigned d;
      if (k > n) return 0;
      for (d=1; d <= k; d++) {
        r *= n--;
        r /= d;
      }
      return r;
    }

This avoids overflows (or at least limits the problem) by performing multiplication and division alternatively.
E.g. for n = 8, k = 4:
result = 1;
result *= 8;
result /= 1;
result *= 7;
result /= 2;
result *= 6;
result /= 3;
result *= 5;
result /= 4;
done

A: I had to solve this problem, too. What I did was use the fact that there are the same number of multiplications as divisions and bundled them together, taking one multiplication and one division at a time. It comes out as an integer at the end, but I use double for the intermediate terms and then round to the nearest integer at the end.
// Return the number of combinations of 'n choose k'
unsigned int binomial(unsigned int n, unsigned int k) {
unsigned int higher_idx;
unsigned int lower_idx;
if(k > n-k) {
    higher_idx = k;
    lower_idx = n - k;
} else {
    higher_idx = n - k;
    lower_idx = k;
}
double product = 1.0;
double factor;
unsigned int idx;
for(idx=n; idx>higher_idx; idx--) {
    factor = (double)idx / double(lower_idx - (n - idx));
    product *= factor;
}
return (unsigned int)(product + 0.5);
}


text:
Q: Convert all urls in a string to anchors I have a string ($string for this example) and I want to do the following:
Parse the string and convert all urls within it to "actual links" (adding the open/close anchor tag).
What is the best way to do this?  I tried using preg_split() to create an array of the links contained in the string, with the idea of using str_replace() after the fact to make the changes.  This approach isn't working however because I am having a hard time isolating the links in the string of text with preg_split().
$string could contain several links within it so that's why I was going with this approach.  If I knew precisely what the links were ahead of time or if str_replace() worked with pattern matching I would be set.
In short, I don't think the approach described above is the best way to go.  What is a better method?

A: This is precisely the kind of thing preg_replace was intended for...
preg_replace('/your URL regex/', '$0', $string);

EDIT: whaddya know, top Google hit for "URL regex PHP": http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/
# PHP Example: Automatically link URL's inside text.

$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '$1', $text);

Note that if you want to match URLs in full generality, you'll need a devilishly complicated regular expression, but to match most common HTTP/HTTPS URLs, the above regex should work.

A: I think you're misunderstanding the purpose of preg_split(). It's used to split a string apart based on a regex. For example if you have a data string "one1two2three3four" you could use preg_split with a regex of "\d" and you'd get a 4-element array returned, consisting of "one", "two", "three", "four".
So unless the links are always separated by specific characters, preg_split() isn't the right tool for the job. You'll probably want to use preg_match() and then loop over the different matches that are returned.
Edit: or as David stated, preg_replace() is even better than preg_match().

A: The regular expression depends on how the links will appear, or where they can appear (within quotes, inside a custom HTML Tag, etc).
It also depends on where the input is coming from. If it is coming from a user, it might be a better idea to use a markdown-like syntax.
At any rate, check out: http://regexlib.com/Search.aspx?k=links for some regular expressions that claim to match URIs and such. You would then use (originally posted by David):
preg_replace('/your URL regex/', '$0', $string);


text:
Q: Page table size, virtual memory size and physical memory size The memory architecture of a machine has:
+-----------------------+-------+
| Virtual address:      | 48-bit|
| Page size             | 8 KB  |
| Page table entry size | 32 bit|
+-----------------------+-------+

Let's pretend that 4 bits from page table entry are used by OS to determine the access rights for each page

*

*Virtual memory size ?

*Max physical memory size allowed by page table

*Page table size

I've tried the following setup:

*

*Virtual memory size = 2^48 B

*Physical memory size = 2^41 B
PPN = 32-4=28 bits physical address= 28+ offset bits=28+13=41 bits

*Page table size= 2^35 * 32 bits
the number of page entries= 48-13=35
page table size= page table entry size* number of page entries

I'm confused about PPN. Should it be 28 bits or 32 bits? I don't know if my solution is correct. Could someone provide me suggestion(s).
Thank you.

A: The question is vague. First, by "max physical memory size" do you mean the maximum physical memory address space size or the maximum physical memory size that can be accessed at any point in time? In the former case, your calculations are correct. In the latter case, the physical memory size is limited by two factors:

*

*The maximum number of page table entries.

*The maximum physical memory address space size.

I think you can figure out the calculations for this case by yourself.
Second, by "page table size" do you mean the the number of page table entries required to cover the maximum virtual address space, the maximum physical address space, or something else (e.g., supported by the page table pointer format)? Also, is the page table single-level or multi-level? Or perhaps it's multi-level, but "page table size" refers only to the last-level page table entries. Your calculations are only correct if "page table size" means the total size of page table entries required to cover the maximum virtual address space where the page table follows the single-level format.
Third, It seems that your are assuming that memory is byte-addressable and that a byte is 8 bits in size. These are common assumptions, but it is better to state them explicitly in the question or the answer. The calculations would be different otherwise.

I'm confused about PPN. Should it be 28 bits or 32 bits?

You're correct, it's 28 bits.


text: Q: Why does stl implement std::greater using functor? I was looking at the std::greater function the other day and was very confused as to why they implemented it as a functor. Were they just showing off their c++ skills or was there an actual design decision that led to that?


text:
Q: Argument of a Gauss sum It is well known that the Gauss sum of a Dirichlet character modulo $N$
$$G(\chi)=\sum_{a=1}^N\chi(a)e^{2\pi ia/N}$$
Moreover,$$\vert G(\chi)\vert=\sqrt{N}$$
when $\chi$ is primitive.
Question :If $G(\chi)=-\sqrt{N}$, the root number of L-function associated to the character $\chi$ is -1 or -i, which is not likely to occur. How to rule out such possibilities?

A: Here is a remark, if $\chi$ is a quadratic character.  Then there is a remarkable result of Gauss, saying that
$$
G(\chi, N)=\begin{cases} \sqrt{N}, \;\text{ if } N\equiv 1 (4) \cr 0, \; \text{ if } N\equiv 2 (4) \cr i\sqrt{N} \; \text{ if } N\equiv 3 (4)  \cr (1+i)\sqrt{N} \;\text{ if } N\equiv 0 (4) \end{cases}
$$
So this rules out that  $G(\chi, N)=-\sqrt{N}$. It took Gauss over $4$ years to prove this.
A proof is in section $9.10$ of Tom Apostol's book on analytic number theory.
For characters of higher orders $k>4$, I believe it is an open problem, which roots of unity can occur. If $\chi$ is a real, primitive Dirichlet character, then only $1$ and $i$ can occur (i.e., $\sqrt{N}$ or $i\sqrt{N}$).

A: OK. The corollary 3 of T Funakura combined with the result of Gauss rules out such possibilities.
P.S.The corollary 3 of T.Funakura states that if $G(\chi)/\sqrt{N}$ is a fourth root of unity,  then $\chi$ is a real character.


text:
Q: AH00169: caught SIGTERM, shutting down for Mac Apache and MySQL failed to start in XAMPP 7.1.27-1. I got the above error, below is the error log.
[Tue Dec 29 10:21:26.460495 2020] [lbmethod_heartbeat:notice] [pid 15627] AH02282: No slotmem from mod_heartmonitor
[Tue Dec 29 10:21:26.467621 2020] [mpm_prefork:notice] [pid 15627] AH00163: Apache/2.4.38 (Unix) OpenSSL/1.0.2r PHP/7.1.27 mod_perl/2.0.8-dev Perl/v5.16.3 configured -- resuming normal operations
[Tue Dec 29 10:21:26.467685 2020] [core:notice] [pid 15627] AH00094: Command line: '/Applications/XAMPP/xamppfiles/bin/httpd -E /Applications/XAMPP/xamppfiles/logs/error_log -D SSL -D PHP'
[Fri Jan 15 06:55:08.753700 2021] [mpm_prefork:notice] [pid 15627] AH00169: caught SIGTERM, shutting down

I have used the lsof -i list and kill -9 PROCESS_ID to kill all processes that run under localhost. I have also changed the apache port, but still apache and MySQL not running.

A: Try the following command
sudo /Applications/XAMPP/xamppfiles/bin/httpd -k start

A: Currently, this is my temporary solution.
1: Edit this file
sudo nano /Applications/XAMPP/xamppfiles/etc/my.cnf

2: Add this line, then save the file
innodb_force_recovery = 1

3: then start MySQL with the below code
sudo /Applications/XAMPP/bin/mysql.server start

4: comment the added line in my.cnf, then save the file
#innodb_force_recovery = 1

5: Stop the MySQL
sudo /Applications/XAMPP/bin/mysql.server stop

6: Use XAMPP Manager to start MySQL
When you restart your PC, you have to repeat these steps.


text:
Q: C Dynamic Array of Struct in [Array of Struct in [Array of Struct in [Array of Struct ]]] I want to store a 100 employees. RollNo,Name,Salary,and the time(various data, I'm unable to explain here but you can understand be seeing below code snippet
main()
{
    struct day {
      int hour[40];
      int min[40];
      int mins[40];
      int rec;
      int totmins;
      int totsal;
      char status;
      int temp;
    };
    struct month {
      struct day * da[31];
    };

    struct year {
      struct month * mn[12];
    };

    struct roll {
      int rn;
      char name[30];
      int salary;
      struct year * yr[25];
    };

so I dynamically allocated the memory by
struct day *da[31];
    for(i=0;i<=31;i++)
        {   da[i]=(struct day*)malloc(31 * sizeof *da);
             if( da[i]== NULL )
             {printf("%d Couldn't able to allocate requested memory for day\n",i);getch();exit(0);}
        }

struct month *mn[12];
    for(i=0;i<=12;i++)
        {   mn[i]=(struct month*)malloc( 12 * sizeof *mn);
            if( mn[i]== NULL )
             {printf("%d Couldn't able to allocate requested memory for month\n",i);getch();exit(0);}
        }

struct year *yr[25];
    for(i=0;i<=25;i++)
        {   yr[i]=(struct year*)malloc( 25 * sizeof *yr);
            if( yr[i]== NULL )
                {printf("%d Couldn't able to allocate requested memory for year\n",i);getch();exit(0);}
        }

struct roll *rol[100];
    for(i=0;i<=100;i++)
        {   rol[i]=(struct roll*)malloc(100 * sizeof *rol));
             if( rol[i]== NULL )
             {printf("%d Couldn't able to allocate requested memory for roll\n",i);getch();exit(0);}
        }

But in my actual piece of code, when i do
[consider d=27,m=1,y=15 and i=1]
rol[i] - > yr[y] - > mn[m] - > da[d] - > rec++;

it is incrementing remaining members also, that is
rol[2] - > yr[y] - > mn[m] - > da[d] - > rec++;
.
.

rol[100] - > yr[y] - > mn[m] - > da[d] - > rec++;

Which means there is some error in the allocation only...Could anyone help me out?

MODIFIED CODE:
    for (i = 0; i < 100; i++) {
      rol[i] = (struct roll * ) malloc(100 * sizeof(struct roll));
      if (rol[i] == NULL) {
        printf("%d Couldn't able to allocate requested memory for roll\n", i);
        getch();
        exit(0);
      }
      for (j = 0; j < 25; j++) {
        rol[i] -> yr[j] = (struct year * ) malloc(25 * sizeof(struct year));
        if (rol[i] -> yr[j] == NULL) {
          printf("%d Couldn't able to allocate requested memory for year\n", i);
          getch();
          exit(0);
        }

        for (k = 0; k < 12; k++) {
          rol[i] -> yr[j] -> mn[k] = (struct month * ) malloc(12 * sizeof(struct month));
          if (rol[i] -> yr[j] -> mn[k] == NULL) {
            printf("%d Couldn't able to allocate requested memory for month\n", i);
            getch();
            exit(0);
          }

          for (l = 0; l < 31; l++) {
            rol[i] -> yr[j] -> mn[k] -> da[l] = (struct day * ) malloc(31 * sizeof(struct day));
            if (rol[i] -> yr[j] -> mn[k] -> da[l] == NULL) {
              printf("%d Couldn't able to allocate requested memory for day\n", l);
              getch();
              exit(0);
            }
          }
        }
      }
    }

but I'm getting that it couldn't allocate memory...

A: struct day *da[31];
    for(i=0;i<=31;i++)
        {   da[i]=(struct day*)malloc(31 * sizeof *da);
             if( da[i]== NULL )
             {printf("%d Couldn't able to allocate requested memory for day\n",i);getch();exit(0);}
        }

This code is wrong.
You are creating an array of structs with 31 elements. 0-30.
You in the loop are going through 32 elements or 0-31.
Change <=31 to <31

A: I do not see anywhere that you initialize any pointers. Maybe the pointer initialization is in code you did not reveal.
malloc() returns uninitialized memory. The debug option of the compiler probably initializes memory returned from malloc(). The initialization would be to some value or values other than zero that likely would aid in debugging. For example, the The debug version of malloc() might allocate the requested amount plus 5 bytes. The officially allocated amount might be initialized to 0xa5a and the extra 5 bytes might be initialized to 0x5a5. That way, a small overrun of a buffer (overruns of less than 5 bytes) can usually be detected.
I think your code shows calling malloc() 32 + 13 + 26 + 101 = 172 times. But I suspect that you want to call malloc() 31 * 12 * 25 * 100 = 230,000 times. That is a lot of allocations and a whole lot of memory. But looks like that is what you intended. You want 31 days and therefore 31 allocations for each month. You want 12 months for each year, 25 years for each rn, and 100 rns. So, that looks to me more like a multiplication instead of an addition of malloc() calls.
I am guessing that you have not initialized your pointers and are using a debugging version of malloc(). Your uninitialized pointers are the 101 * 26 = 2626 year pointers. That is 25 pointers for each of your 101 rns. Then for each year pointer, you have 13 month pointers that are uninitialized, etc.
What I suppose is happening in your code is the processor is using the debug initialization of malloc memory as an address to reference. If memory were initialized to zero-bytes, the processor would detect a NULL pointer and you would get a runtime error. However, the processor thinks that you are referencing by a valid address, therefore does not complain. What comes out is that you are incrementing some wild address that has nothing to do with your structures. Because all of your structures are using the same wild address, it appears as if all recs are being incremented.
What you need to do is allocate for rn. Then for each rn, allocate for each of the 25 years. Make sure each year of the rn POINTS TO an allocation for the year. That is the initialization. Then for each rn and each year, allocate for the month, and initialize so each month points to an allocation....etc.
Sounds like a lot of work, and complicated. Therefore, if you have a choice, you might want to dream up some other solution.
To come up with another solution, you could think how you would lay out your fields (columns) in Excel. And that would get you down to one struct. You could probably call malloc() just one time (already much simpler).


text:
Q: Increase Android ViewPager performance I'm creating a android application with target on 2.2. I still want to use the ViewPager provided in the android.support-v4.jar.
I'm using a FragmentPagerAdapter in combination with Fragment to display content.
Each fragment contains a WebView, displaying some html data.
Scrolling a WebView up and down works great but the swiping between pages in the ViewPager behaves very jerky and not at all as smooth as scrolling the WebView.
Is there any way you can increase the scroll performance of the ViewPager, maybe something like ConvertView from BaseAdapter?
I'm guessing I could load the url in a background thread but from what I've heard that's not best practice.
Any suggestions would be great, thanks.

A: I realized you could use the
viewPager.setOffscreenPageLimit(items.size());

to keep all items preloaded in memory and avoid the "freeze/laggy" performance while scrolling,.

A: You should consider reusing the Fragments by providing some method to reuse existing fragments in the ViewPager and populate or refresh it's UI with the new data.


text:
Q: MySQL String to Date (Generic) Can anyone suggest a function that converts strings to date?
> This Function will takes a string and give:
> 0000-00-00 if string cannot be converted (string in <> date out)
> NULL if String NULL or blank(string in = date out)
> yyyy-mm-dd if string can be converted (string in = date out)

A: > This Function will takes a string and give:
> 0000-00-00 if string cannot be converted (string in <> date out)
> NULL if String NULL or blank(string in = date out)
> yyyy-mm-dd if string can be converted (string in = date out)

Drop function if exists stringtodate;

DELIMITER $$

CREATE FUNCTION `stringtodate`(v TEXT) Returns DATE
BEGIN
DECLARE result DATE;

IF (v Is Null or v = '') THEN SET result = NULL;
ELSEIF (STR_TO_DATE(v,'%d-%m-%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d-%m-%Y');
ELSEIF (STR_TO_DATE(v,'%d,%m,%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d,%m,%Y');
ELSEIF (STR_TO_DATE(v,'%d/%m/%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d/%m/%Y');
ELSEIF (STR_TO_DATE(v,'%Y-%m-%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y-%m-%d');
ELSEIF (STR_TO_DATE(v,'%Y,%m,%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y,%m,%d');
ELSEIF (STR_TO_DATE(v,'%Y/%m/%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y/%m/%d');
ELSEIF (STR_TO_DATE(v,'%d-%m-%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d-%m-%y');
ELSEIF (STR_TO_DATE(v,'%d,%m,%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d,%m,%y');
ELSEIF (STR_TO_DATE(v,'%d/%m/%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d/%m/%y');

ELSE SET result = CAST("0000-00-00" AS DATE);

END IF;

Return result;

END


text:
Q: How to link Two Multi-Dimensional arrays using pointers? I need to basically merge a Binary Heap, and Linear Probing Hashtable to make a "compound" data structure, which has the functionality of a heap, with the sorting power of a hashtable.
What I need to do is create 2 2 dimension arrays for each data structure (Binary Heap, and Hash) then link them to each other with pointers so that when I change things, such as deleting a value in the Binary Heap, it also gets deleted in the Hash table.
Therefore, I need to have one row of the Heap array pointing from the Heap to the Hastable, and one row of the hashtable array pointing from the hashtable to the heap.

A: Create a container that contains both, with accessor functions/methods (depending on your language of implementation) that performs all the operations required of your algorithm.
IE:
Delete from container:  does a delete from Binary and from hash.
Add to container: adds to binary and to hash.
EDIT:
Oh, an assignment - fun! :)
I'd do this:
still implement a container.  But, instead of using a standard library for btree/hash, implement them like this:
Make a type that can be put in your data member that has a pointer to the BTree node and the Hashtable Node that the data element lives in.
To delete a data element, given a pointer to it, you can perform the delete algorithm on a btree (navigate to parent from node pointer, delete child (left or right), restructure tree) and on the hash table (delete from hash list).  When adding a value, perform the add algorithm on btree and hash, but be sure you update the node pointers in the data before you return.
Some pseudocode (I'll use C, but i'm not sure what language your using):
    typedef struct
    {
        BTreeNode* btree
        HashNode* hash
    } ContianerNode;
to put data in your container:
typedef struct
{
    ContainerNode node;
    void* data; /* whatever the data is */
} Data;

a BTreeNode has something like:
typedef struct _BTreeNode
{
    struct _BTreeNode* parent;
    struct _BTreeNode* left;
    struct _BTreeNode* right;
} BTreeNode;

and a HashNode has something like:
typedef struct _HashNode
{
    struct _HashNode* next;
} HashNode;
/* ala singly linked list */

and your BTree would be a pointer to a BTreeNode and your hastable would be an array of pointers to HashNodes.  Like this:
typedef struct
{
    BTreeNode* btree;
    HashNode* hashtable[HASHTABLESIZE];
} Container;

void delete(Container* c, ContainerNode* n)
{
    delete_btree_node(n->btree);
    delete_hashnode(n->hash);
}

ContainerNode* add(Container* c, void* data)
{
    ContainerNode* n = malloc(sizeof(ContainerNode));
    n->btree = add_to_btree(n);
    n->hash = add_to_hash(n);
}

I'll let you complete those other functions (can't do the whole assignment for you ;) )

A: Why bother with the links?
You have two associative structures just duplicate any operation on one to the other (ensuring that if one operation excepts you either crash the whole thing or leave the object in a valid state if you care about such things)
Unless you can make use of the structure of one to help you with the other (and I don't see how you can since either one can entirely rearrange it's internal state on any modification operation) this is just as effective and much simpler.
Of course this means that the O() cost of any modification operation is the cost of the most expensive and memory costs are doubled but that is true of the original plan unless their is some trick I'm missing.


text:
Q: How to make div with text and icon right How to make div with center text and icon right like on this photo

A: div{
  text-align: center;
  background: red;
}
div img{
  float: right;
}

A: text is in center picture on right

A: There are two method to do you can use following are methods
Inline method
div style="text-align: center;">

EXTERNAL CSS method
div{
  text-align: center;
  background: red;
}
div img{
 float: right;
}

A: I hope this is what you want.

#red {
width:500px;
  height:100px;
  padding:20px;
  background-color:#f70c1e;
  color:white;
  line-height:100px;
  font-size:40px;
  font-family:sans-serif;
  text-align:center;

}
img{
float:right;
}

 Yada yada .

A: You could also just put it in a table:

Text
Image

And some css for the padding


text:
Q: Vue how to solve `TypeError: Cannot read properties of undefined` when pushing to array In my vue-app I try to loop through some video-items, get their youtube-id and fetch their thumbnails.
so I have:

then I have
data(){
  return {
    thumbnail : '',
    thumbnails: [] // don't know if I can use that
   }
},

methods: {
   getVideoThumbNails(){
      const videos = document.querySelector(".videos");
      const iframes = videos.querySelectorAll(".video-item");

      iframes.forEach(function (item, index) {
        let youtube_video_id = item.getAttribute("youtube-id");

        if (youtube_video_id.length === 11) {
           const video_thumbnail = "http://img.youtube.com/vi/" + youtube_video_id + "/maxresdefault.jpg";
        }

        // this.thumbnail = video_thumbail
        this.thumbnails.push(video_thumbnail);
     });
   }
},
mounted(){
 this.getVideoThumbNails()
}

For some reason I don't know, this gives me the error TypeError: Cannot read properties of undefined (reading 'thumbnails')
Can someone tell me what I'm doing wrong? And how can I apply those images in the end?

A: First you should use an arrow function as callback for the forEach method in order to get access to the component instance, second you must put the  this.thumbnails.push(video_thumbnail); inside the condition block :
      iframes.forEach( (item, index) =>{
        let youtube_video_id = item.getAttribute("youtube-id");

        if (youtube_video_id.length === 11) {
           const video_thumbnail = "http://img.youtube.com/vi/" + youtube_video_id + "/maxresdefault.jpg";

     // this.thumbnail = video_thumbail
        this.thumbnails.push(video_thumbnail);
        }

     });


text:
Q: TSQL - Case error with syntax Someone can tell me why I have error
select TrN_FPlID as Platnosc
CASE
WHEN TrN_FPlID  = '1' THEN 'Gotowka'
WHEN TrN_FPlID  = '3' THEN 'Przelew'
from CDN.TraNag

and I have this error:
    Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'CASE'.

A:
You need a comma to separate the selected columns.

select
    TrN_FPlID as Platnosc,
    (CASE
        WHEN TrN_FPlID  = '1' THEN 'Gotowka'
        WHEN TrN_FPlID  = '3' THEN 'Przelew'
    END) as ColumnName
from CDN.TraNag

Always put an END syntax after you have finish your CASE statement
  Add as YourColName after the case syntax like you have done to TrN_FPlID
  Another way of doing this

select
    TrN_FPlID as Platnosc,
    iif(TrN_FPlID  = '1','Gotowka',iif(TrN_FPlID  = '3','Przelew',null)) as ColumnName
from CDN.TraNag

A: You are missing comma before case and the case statement is missing End.
Conditional expression is not required for each case, while checking for the equal = operator.
    select TrN_FPlID as Platnosc,
    CASE TrN_FPlID
    WHEN '1' THEN 'Gotowka'
    WHEN '3' THEN 'Przelew'
    end
    from CDN.TraNag

A: Check the documentation corresponding to your DBMS
First, you are missing a coma before the CASE, second your CASE is missing an END and third, the syntax WHEN field = value is not valid.


text:
Q: Find an array element position in compile time -- Edited --
Hi all. I've got an array of elements that will not change in all the execution of the program, and where items can have sons inside the own array. I've got to prepare the array before process it. However, because I know that the array will not change, I would like to declare it as const, and prepare all of it in compile time, so I could throw away the integers int son_id[NUM_OF_SONS], prepare_items() function and the array declaration will be, in my opinion, clearer.
#include <stdlib.h>
#include <stdio.h>

#define NUM_OF_SONS 5

struct item{
    int id;
    char *str;
    int son_id[NUM_OF_SONS];
    const struct item *son[NUM_OF_SONS];
};

const struct item *find_item(int id);

static struct item items[] = {
    {4, "FIRST ELEMENT"},
    {5, "SECOND ELM"},
    {10, "THIRD ELM"},
    {15, "FATHER", {5,10}},
    {0, 0 }
};

const struct item *find_item(int id){
    int i;
    for(i=0; items[i].str != NULL; ++i){
            if(items[i].id == id) return &items[i];
    }

    return NULL;
}

void fill_sons(struct item *item){
    int i;
    for(i=0;i<NUM_OF_SONS;++i){
            if(item->son_id[i]!=0)
                    item->son[i] = find_item(item->son_id[i]);
    }
}

void prepare_items(){
    int i;
    for(i=0;i<sizeof(items)/sizeof(items[0]);++i){
            fill_sons(&items[i]);
    }
}

void print_sons(const struct item *item);

void print_item(const struct item *item){
    printf("The item %d has the text %s.\n",item->id,item->str);
    print_sons(item);
}

void print_sons(const struct item *item){
    int i;
    for(i=0;i<NUM_OF_SONS;++i){
            if(NULL!=item->son[i])
                    print_item(item->son[i]);
    }
}

int main(){
    prepare_items();

    print_item(&items[0]);
    print_item(&items[3]);
}

I've though in something like this:
static struct item items[] = {
    {4, "FIRST ELEMENT"},
    {5, "SND ELM"},
    {10, "THIRD ELM"},
    {15, "FATHER", {&items[1],&items[2]}},
    {0, 0 }
};

However, there could be about 200 elements in the array, and I need to be able to insert or delete elements in the middle of it (in compile time). So &items[1],&items[2] should be ITEM_ID(5),ITEM_ID(10), some kind of preprocessor instruction. How could achieve that?
Thanks in advance, and sorry for the long post.

A: The nearest equivalent to templates in C (that I know of) is X-Macros. I think you can achieve this result, but it will require introducing another identifier for each struct (actually it doesn't -- scroll down to the "Edit"!) which we can sync with the array by declaring these identifiers in an enum.
To start with, we change the initializer elements to be in the form of macro calls. For the style I prefer, the name of this macro is not important, so I'll call it _. All calls will need the same number of elements, so add an empty list where necessary. And the whole thing is wrapped in one big macro. This big macro will receive another macro as an argument which it calls for each element.
#define DATA(_) \
    _(4, "FIRST_ELEMENT", {}) \
    _(6, "SECOND_ELEMENT", {}) \
    _(10, "FATHER ELEMENT", {15, 20}) \
    _(15, "SON ELEMENT 1", {}) \
    _(20, "SON ELEMENT 2", {}) \
    _(0, NULL, {})

Now we can declare the array data by defining a usage macro that emit the arguments in the correct form for the array declaration.
#define CREATE_ARRAY(a, b, c) \
    {a, b, c},

struct item items[] = {
DATA(CREATE_ARRAY)
}

So far we've just achieved the same result. But now it's in a more flexible form. The next step is adding the new IDs.
#define DATA(_) \
    _(FIRST, 4, "FIRST_ELEMENT", {}) \
    _(SECOND, 6, "SECOND_ELEMENT", {}) \
    _(FATHER, 10, "FATHER ELEMENT", {15, 20}) \
    _(SON1, 15, "SON ELEMENT 1", {}) \
    _(SON2, 20, "SON ELEMENT 2", {}) \
    _(END, 0, NULL, {})

And adjust the CREATE_ARRAY macro to account for the new argument.
#define CREATE_ARRAY(a, b, c, d) \
    {b, c, d},

struct item items[] = {
DATA(CREATE_ARRAY)
};

Now the fun part. We make another macro to generate the IDs as enum values.
#define CREATE_IDS(a, b, c, d) \
    a,

enum identifiers {
DATA(CREATE_IDS)
};

Now the data can use these identifiers to index the array.
#define DATA(_) \
    _(FIRST, 4, "FIRST_ELEMENT", {}) \
    _(SECOND, 6, "SECOND_ELEMENT", {}) \
    _(FATHER, 10, "FATHER ELEMENT", {SON1, SON2}) \
    _(SON1, 15, "SON ELEMENT 1", {}) \
    _(SON2, 20, "SON ELEMENT 2", {}) \
    _(END, 0, NULL, {})

And, of course, remove the child_id member from the struct, since our new identifiers are the desired array indices, directly.

Edit. Wait a moment. You have identifiers already. And they're already unique. So we don't need to introduce new ones. We can simply mangle them! __VA_ARGS__ is also needed to handle the possible embedded commas in the child list.
#define CREATE_ARRAY(a, b, ...) \
    {a, b, __VA_ARGS__ },

#define ID_(x) ID ## x
#define CREATE_IDS(a, b, ...) \
    ID_(a),

#define DATA(_) \
    _(4, "FIRST_ELEMENT", {}) \
    _(6, "SECOND_ELEMENT", {}) \
    _(10, "FATHER ELEMENT", {ID15, ID20}) \
    _(15, "SON ELEMENT 1", {}) \
    _(20, "SON ELEMENT 2", {}) \
    _(0, NULL, {})

enum identifiers {
DATA(CREATE_IDS)
};

struct item items[] = {
DATA(CREATE_ARRAY)
};

cpp -P output (linebreaks added):
enum identifiers {
ID4, ID6, ID10, ID15, ID20, ID0,
};
struct item items[] = {
{4, "FIRST_ELEMENT", {} },
{6, "SECOND_ELEMENT", {} },
{10, "FATHER ELEMENT", {ID15, ID20} },
{15, "SON ELEMENT 1", {} },
{20, "SON ELEMENT 2", {} },
{0, NULL, {} },
};

For more about X-macros, see the answers to this question (one of which I wrote :P).

A: About the best I can offer--because C is absolutely not designed to keep track of this sort of metadata--is the __LINE__ constant.
__LINE__ inserts the current line number into the program, which you can use as a field in the struct item. Obviously, you need to also commit to not having any blank spaces in your definition of items and also know where items starts in the file.  The latter, you can do with something like:
int first_line = __LINE__ + 2;
const struct item items[] = {
    {4, "FIRST_ELEMENT", __LINE__},

And then remember to subtract first_line from your line_id (or whatever you want to call it) field.
It's not a good solution, but I think it's about the best that C is going to do without writing code to load the contents of one array into another and keep track of the metadata during the move.

A: First things first, you have to know that once you declare items as an array to constant item structures, which you do when you write const struct item items[];, you then won't be able to change the contents of those structures after initialization.
So, for example, you won't be able to assign anything to any of the elements of the child array inside any one of the structures inside the items array. Woah, that was big, let's give a code example:
items[2].child[0] = &( items[3] );
// or just ... items + 3;
// you won't be able to do this because items[2] is defined as a constant

I couldn't really understand what your objective is, but here's one thing that possibly maybe help you out. You can do the following:
#include <stdio.h>
#define MaximumChildCount 5 // personal preference, easier to read, change as you wish

typedef struct item{
    int id;
    char *str;
    // I left the childs_id out, since you've implied that you'd like that out
    struct item *child[MaximumChildCount];
};

int main( ){

    const struct item sons[] = {
        { 15, "SON ELEMENT 1" },
        { 20, "SON ELEMENT 2" }
    };
    // creating sons before the parent, biologically nonsense?
    // well, if you want to keep the record of child elements inside parent
    // and make them all constants, then you need to have children before

    const struct item items[] = {
        { 4, "FIRST_ELEMENT" },
        { 6, "SECOND_ELEMENT" },
        { 10, "FATHER ELEMENT", { sons, sons + 1 } },
        // sons points to first son, sons + 1 points to the second one
        // assigned them at initialization, just like you had with { 15, 20 }
        { 0, NULL }
    };

    printf( "%s", items[2].child[1]->str );

    return 0;
}

This prints "SON ELEMENT 2". You can very well make sons in the following way:
const struct item son1 = { 15, "SON ELEMENT 1" };
const struct item son2 = { 20, "SON ELEMENT 2" };

And then assign them during initialization like this:
... = {
    ...
    ...
    { ..., ..., { &son1, &son2 } },

    ...
};

I'm sorry if this was not the thing you were looking for. I really am having hard times on understanding the cause.


text:
Q: An error occurred while updating the entries. See the inner exception for details.; [INNER] Execution Timeout Expired One of our production SQL Servers the database is performing poorly. On the application side, they are experiencing this error:

An error occurred while updating the entries. See the inner exception for details.;
[INNER] Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.;
[INNER] The wait operation timed out;

These are the followings things we have tried to troubleshoot:

*

*checked if there any locking and blocking going on- there is no major blocking going on. If there is blocking going on, resources are blocked for less than 1 min and against a different DB.

*captured queries using profiler. we noticed that insert, update and select are occurring simultaneously. so we are assuming there might be internal locking going on somewhere, but can't figure out where.

*there are no fragmentation present.

*there are no errors produced in the SQL server error logs.

*captured performance counters for a week and nothing critical was shown.
Has anyone ever experienced these errors before? If so, what did you do to troubleshoot and resolve the errors?

A: By default, the .Net client has a 30-second client-side command timeout.  The error you are seeing is saying that the response from the server took more than 30 seconds.
Here's some example C# code showing the problem by executing a WAITFOR DELAY statement that waits 31 seconds:
using System;
using System.Data.SqlClient;

namespace ConnectionTimeoutTest
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder
            {
                InitialCatalog = "tempdb",
                IntegratedSecurity = true,
                DataSource = "localhost"
            };

            using SqlConnection connection = new SqlConnection();
            connection.ConnectionString = sqlConnectionStringBuilder.ConnectionString;
            connection.Open();
            using SqlCommand sqlCommand = new SqlCommand("WAITFOR DELAY '00:00:31';SELECT 'Hello World!';", connection);
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            };
        }
    }
}

And the exception:

System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Source=Core .Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at ConnectionTimeoutTest.Program.Main(String[] args) in C:\Users\Hannah.MVCT\source\repos\ConnectionTimeoutTest\ConnectionTimeoutTest\Program.cs:line 23
Inner Exception 1:
Win32Exception: The wait operation timed out.

Here's the fix to make the client wait for 60 seconds:
using System;
using System.Data.SqlClient;

namespace ConnectionTimeoutTest
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder
            {
                InitialCatalog = "tempdb",
                IntegratedSecurity = true,
                DataSource = "localhost"
            };

            using SqlConnection connection = new SqlConnection();
            connection.ConnectionString = sqlConnectionStringBuilder.ConnectionString;
            connection.Open();
            using SqlCommand sqlCommand = new SqlCommand("WAITFOR DELAY '00:00:31';SELECT 'Hello World!';", connection);
            sqlCommand.CommandTimeout = 60;  // <---- this is new
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            };
        }
    }
}

The code above is available in GitHub.

A: First steps you can take to troubleshoot your error:

*

*Try to increase Connection Timeout property in the connection string from default 15 (or 30) to 60 or more seconds

*Try to increase CommandTimeout property of the SqlCommand object (Hannah's answer has great detail on how to do it).
Up until very recently, the .NET System.Data.SqlClient driver allowed setting the CommandTimeout only via the SqlCommand object. Note that In the newer Microsoft.Data.SqlClient driver, specifically v2.1, you can now set this via the connection string, and it will be applied to any SqlCommand associated with that connection automatically
If #1 reduces or eradicates the error, then you've had a connectivity error
If #2 helps (more likely than #1), then you are having long-running query problem (over 30 secs) and you have to dig deeper to understand what creates a slowness in a query


text:
Q: Cognito Forgot password fails I've Created a user using admin create user. The user was able to change the temporary password and login into the application. But, when the user tried forgot the password, and type an email Cognito throws an error
Could not reset the password for the account, please contact support or try again

A: I was able to solve this issue, by setting
email_verified: true

in the User attribute list.


text:
Q: submit form from dropdown menu text link I have dropdown menu with some actions, but I need help to submit form on click via text link and pass the name attribute to the POST method. I have jQuery already on the page and code below works but name attribute is not sent.
<form id="myForm" name="myForm" action="" method="post">

<button class="dropdown">Actions</button>

Option 1

Option 2

... other form fields ...
</form>

A: This is not how HTML works, a link doesnt send any information other than the url you set in the href attribute, you could do this

Option 2

which does not require a form, or if you wish to Post you will need each option to be a seperate form, or you could use the solution provided by isherwood.

A:

Option 1

Option 2

<input id="linkName" type="hidden" />

$('ul_dropdown li a').on('click', function() {
    $('#linkName').val( $(this).attr('name') );
    $(this).closest('form').submit();
});


text:
Q: AJAX - jQuery vs direct XmlHttpRequest returnning script oddness I'm trying to get to the bottom of some oddness between doing AJAX with jQuery vs. manipulating XmlHttpRequest directly. The test case I've got below is classic ASP, but that's only my convienence - server-side technology shouldn't matter.
I ought to add that I've not excluded stupidity on my part -- I'm just not sure what it is :-) This may be completely trivial and I'm missing something fairly obvious, but I'm not getting my google-fu correct to actually find out what it is I'm missing.
Essentially I'm calling code that returns inline Javascript. This is injected into the HTML page, and is intended to be executed. I have full control over all the code and the server (i.e., this should not be cross-domain request).
What I'm seeing is that the jQuery version works - it executes the script returned by the AJAX page. The direct method doesn't work. The javascript does not execute.
My first thought was "XSS", and that jQuery did something specific to the headers, however I've investigated with fiddler and, I see both requests going out, both return the same code. I've also got both requests to mirror exactly, with the exception of the GET (jQuery sticks a querystring on the request - I assume this is to get around caching issues), but in essence the request looks like this:
GET http://myLocalMachine:8000/ajaxtest/ajax.asp HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-gb
Referer: http://hsl10161:8000/ajaxtest/main.html
Accept: text/html, */*
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Tablet PC 2.0; .NET CLR 1.1.4322; InfoPath.3; MATM)
Host: myLocalMachine:8000
Connection: Keep-Alive

...note that there is no Access-Control header in the request, nor is any returned in the response headers:
HTTP/1.1 200 OK
Cache-Control: No-cache
Pragma: No-cache
Content-Type: text/html
Expires: Wed, 14 Mar 2012 10:00:57 GMT
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
X-UA-Compatible: IE=EmulateIE7
Date: Wed, 14 Mar 2012 10:01:57 GMT
Content-Length: 55

The rest of this content is a test case...the behaviour described occurs on IE8 and Firefox 10.
ajax.asp

<%@ Language=VBScript %>
<%
Option Explicit
Response.CacheControl = "No-cache"
Response.AddHeader "Pragma", "No-cache"
Response.Expires = -1
%>

main.html

    <title>AJAX test</title>

    <button onclick="ajax1('ajax.asp', 'target')">With jQuery</button>
    <button onclick="ajax2('ajax.asp', 'target')">Without jQuery</button>
    <button onclick="resetdiv();">Reset</button>

ajax.js

function ajax1(strURL,target)
{
$.ajax({
    url: strURL,
    cache: false,
    dataType: "html",
    async: false,
    type: "GET",
    success: function (data) {
        $('#' + target).html(data);
    }
});
}

function ajax2(strURL,target)
{
var localAjax = new XMLHttpRequest();
localAjax.open("GET", strURL, false);
localAjax.setRequestHeader("Accept", "text/html, */*");
localAjax.setRequestHeader("x-requested-with", "XMLHttpRequest");
localAjax.onreadystatechange = function() {
    if (localAjax.readyState == 4)
    {
        var respText = localAjax.responseText;
        var targetField = document.getElementById(target);
        if (targetField != null) {
            targetField.innerHTML = respText;
        }
    }
}
localAjax.send(null);
}

A: jQuery executes the code added to the DOM when its added using .html()... JavaScript .innerHTML does not. You could use the eval() function on your code to cause it to execute


text:
Q: save decorator with morphia for a multiplayer game project that I'm building I have a little database based on morphia MongoDB.
when all the users of a game room is logged out, I want to save the Game object to the DB to save the server's RAM,
but my Game object designed as decorator (the classic design pattern with no changes)
so my object's ID is an Object that its ID is also an Object and the hierarchy length is dynamic....
is there any way to declare the ID to be the ID's ID?
for example in hierarchy of length 3 i use for read
Query<IGame> query = datastore.createQuery(IGame.class).filter("_id._id._id = ", "28");

and in hierarchy of length 4 i use
Query<IGame> query = datastore.createQuery(IGame.class).filter("_id._id._id._id = ", "28");

but i need a combination with a dynamic length of _id._id
or another way to store this hierarchy in morphia.


text:
Q: SSRS Matrix Dynamic Column Sort Looking for a way to sort my SSRS report on each of the different column groups. I want to be able to sort my row group (a list of products) with a hidden field. The report is very dynamic, in the sense that the number of column groups changes every time the report is run and I want to be able to sort on each of the groups separately. Here is what my report looks like..

I've tried added the 'Interactive Sorting' property to the 'Day Supply' Column; sorting Detail Rows by Product Rank (the hidden field) and sorting Row Groups by Product Rank. Nothing happens when I try either way.
I have searched online and there looks like there may be a way to get what I want done using various parameters, but I haven't been able to figure that way out either. Any help or suggested would be greatly appreciated!

A: Try with below way in your Interactive Sorting (Day Supply), also delete the SORTING option available in your existing group (Right Click in Group Properties > Sorting tab > Delete).

Change according to your value.


text:
Q: Let $\{A_n\}_{n=1}^\infty$ be a sequence of nonempty subsets of $\mathbb{Z}$, which of the following is uncountably infinite? Let $\{A_n\}_{n=1}^\infty$ be a sequence of nonempty subsets of $\mathbb{Z}$. Which of the following is uncountably infinite?
A) $A_1$
B) $\bigcap_{n=1}^\infty A_n$
C) $\bigcup_{n=1}^\infty A_n$
D) The set of all functions $f: \{0,1\} \to A_1$
E) The set of all functions $f: A_1 \to \{0, 1\}$
I am stupefied by this question, as none of the answers seem correct.  If $A_1$ is infinite, the answer would be $E$, but the question does not provide this further assumption.

A: "If $A_1$ is infinite, the answer would be E, but the question does not provide this further assumption."
I'd just go with that as the answer.


text:
Q: Unable to uncheck checkbox from chrome I am trying to check/uncheck a checkbox/radiobutton both from the table cell as well as the actual checkbox /radiobutton
I have written this below code to select a checkbox/radiobutton from table cell
Please refer code pen for actuall code.
The code works fine for IE 11 browser but not in Chrome. If i select the table cell then the checkbox is selected but in chrome when i check on the actual check box nothing happens .
I think it is the checkbox internally calls the PropagateBelow method.
Check/Uncheck check box for chrome(Select on the CHECKBOX itself on TABLE CELL works fine)

                <input type="checkbox" id="test" value="Test123" />

function PropagateBelow(tableCell) {
    alert(tableCell);
    var radioButtons = tableCell.getElementsByTagName('input');
    for (var i = 0; i < radioButtons.length; i++) {
        var radioButton = radioButtons[i];
        if (radioButton != null && radioButton != undefined) {
            if (radioButton.type == 'radio' || radioButton.type == 'checkbox') {
                radioButton.click();
            }
        }
    }
}

A: Not quite sure what the exact misbehavior is you're observing. What happens when I test your code is that when clicking the cell, PropagateBelow(this) is called which activates/deactivates the checkbox, based on its current state. When I click the checkbox, the checkbox is ticked, but then the click event bubbles up, again triggering PropagateBelow(this) which in turn unticks the checkbox again.
If you want to prevent that, you have to stop the propagation of the event when you click on the checkbox, like

                    <input type="checkbox" id="test" value="Test123" onclick="cancelPropagation();" />

and then implement cancelPropagation() as follows
function cancelPropagation(ev){
  var event = ev || window.event;
  event.stopPropagation();
  return false;
}

Here's your modified codepen project: http://codepen.io/anon/pen/MwEpxm
As mentioned, I'm not sure I got what you mean. If this doesn't help, let me know, so I'll delete my answer again :)

A: Instead of using a JavaScript function to propagate the click to all of the radio buttons, you can wrap the radio button in label which takes up the whole space of the table cell. Wrapping a radio button in a label will allow you to click anywhere in the label to toggle the radio button without having to use any JavaScript.
Please see example here: http://codepen.io/anon/pen/GJMWzb

                    <input type="checkbox" id="test" value="Test123" />

A: Funnily enough this does work fine for me in Chrome, but as a general rule it's better to set the checked property to true on checkboxes instead of trying to simulate clicks.
This could simply be done by replacing radioButton.click(); with radioButton.checked = true;, or if you wanted to toggle the checkbox radioButton.checked = !radioButton.checked;.
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/checked


text:
Q: Mongodb query to select all documents between two dates I am currently struggling with this topic and I tried multiple solution from this platform like this one and found no results.
Basically I have an endpoint in a nestjs application that receives via a POST request a from and a to parameter that are both dates(string that can be converted with new Date(from/to)).
I am trying to get all documents in the database between those two dates(from and to).
Here is  the query that I am making:
const data = await model.find( {
        payload: {
          timestamp: {
            $gte: new Date( from ).toISOString(),
            $lte: new Date( to ).toISOString()
          }
      }
} );

The response that I get is this error:
"Cast to date failed for value \"{ '$gte': 2023-01-03T14:15:52.767Z, '$lte': 2023-01-03T14:16:52.767Z }\" (type Object) at path \"timestamp\" for model \"data\"",

I also tried to get put the timestamp key outside the payload object so:
With error:
{payload:{timestamp: ... }}
query:
const data = await model.find( {
        payload: {
          timestamp: {
            $gte: new Date( from ).toISOString(),
            $lte: new Date( to ).toISOString()
          }
      }
} );

Without error but I get an empty array every time:
{payload:{}, timestamp: ...}
query:
const data = await model.find( {
   timestamp: {
       $gte: new Date( from ).toISOString(),
       $lte: new Date( to ).toISOString()
   }
} );

What exactly am I doing wrong?

A: Using the discussion on this issue as the clue, the problem is in the query syntax here. Since you are using embedded fields, the query should use dot notation:
const data = await model.find( {
  'payload.timestamp': {
     $gte: new Date( from ).toISOString(),
     $lte: new Date( to ).toISOString()
  }
} );

With the current syntax Mongoose is trying to construct a date object which is causing the Cast to date failed for value ... (type Object) error. This syntax isn't what you'd want anyway as the database would be searching and comparing with the object which has different semantics than what you are likely looking for.
Edit to add that more details about the query semantics on this topic can be found here in the documentation.


text:
Q: Overlay median values line graph on a barchart of counts by category in python The following code gives me bar charts that give a count per category. I would like to overlay the median value of a numeric feature per unique category.
What would I need to add to the following code?
def plot_bars(xy_merge, cols):
    for col in cols:
        fig = plt.figure(figsize=(6,6)) # define plot area
        ax = fig.gca() # define axis

        counts = xy_merge[col].value_counts() # find the counts for each unique category
        counts.plot.bar(ax = ax, color = 'blue') # Use the plot.bar method on the counts data frame

        ax.set_title('Counties and median log rental per categorical variable: ' + col) # Give the plot a main title
        ax.set_xlabel(col) # Set text for the x axis
        ax.set_ylabel('Count')# Set text for y axis

        plt.show()

plot_cols = ['state', 'rucc', 'urban_influence']
plot_bars(xy_merge, plot_cols)

data frame
bar chart