text:
Q: "Speak to" vs. "Speak with" What are the differences between these two phrasal verbs and what are the best situations to use each?

A: I have seen "Speak to" being used when there is a monologue kind of a situation, A speaks and B listens. Refer Shinto's answer. This has reference to instructing, reprimanding and situations like this.
"Speak with" is a more neutral kind of a term implying a bidirectional communication.

A: These two are more or less equivalent. They can both be used for the situation where A and B speak to each other. "Speak to" can also be used for the situation where A talks and B listens without speaking.

A: hawbsl is right. You are more likely to encounter speak with in American English.
It's not really used in the UK. I have only heard speak with being used by Americans, on American TV programmes and films. I remember this because it was so unusual and odd that it surprised me.
It's the same with the words meet with. This one was particularly odd to me, because the word meet on its own is normally enough. It puzzled me for a while until I heard it used in other American TV programmes and I researched the use of it. From a British perspective, it is an unnecessary extra to add the word with to the word meet.
To answer your questions directly, it seems that the differences between these are in their use. The best situations to use them will depend on whether you are speaking American English or not. You can use them if you speak American English, but otherwise they are not necessary and sound odd — particularly to English and other British people.

A: This answer has two portions, one on to speak with/to, which is what the question asked, and one on to meet with, which came up in comments to another answer. You will note in the reference citation that speak is from the OED2 in 1989, whereas talk is from the OED3 in 2001. Only the latter is called out as now being chiefly North American in contemporary usage, and even there many illustrations from British literature of an era slightly earlier than our own are given.
 to speak with / to ━━
The OED makes does not call out either of the two phrasal verbs "to speak with ━━" or "to speak to ━━" as being more commonly seen in Britain vs elsewhere.
Here is the first sense for "to speak with ━━ ":

*

*To converse with, talk to; to consult or confer with. In Old English and early Middle English similarly with mid.

*

*971   Blickl. Hom. 241   He þæt is se þe wið me spræc.

*c1000   Ælfric Exodus xxxii. 23   Þa þu‥ wið god spæce.

*c1200   Trin. Coll. Hom. 85   Alse wise hire lerden, þanne hie wið hire speken.

*a1250   Owl & Nightingale 1553   Ne mot no mon wiþ hire speke.

*c1330  (1300)    Sir Tristrem (1886) l. 811   Wiþ morgan speke wil y And spede.

*c1426   J. Audelay Poems (1931) 17   Ȝe spekyn with Hym in spyrit.

*1470–85   Malory Morte d'Arthur ɪ. x. 48   They spak with the knyghtes & welcomed hem.

*1530   J. Palsgrave Lesclarcissement 727/2   He shalbe spoken with towchyng your cause.

*1622   in W. Foster Eng. Factories India 1622–3 (1908) 10   They both retired themselves to there privacy, soe that wee could not then speake with them.

*1675   City Mercury 18–25 Nov. 2/1   He [a Physician] is any time to be spoke with from eight in the Morning to four in the Afternoon.

*1764   S. Foote Patron ɪɪɪ. 67   Not to be spoke with! Don't tell me, Sir; he must, he shall.

*1816   Scott Old Mortality vii, in Tales of my Landlord 1st Ser. IV. 140      Your uncle‥has been spoken with, and declines visiting you.

*1847   Tennyson Princess ɪɪ. 58   Not for three years to speak with any men.
fig.

*1663   S. Patrick Parable of Pilgrim (1687) xᴠ. 134   When any temptation desires to speak with you, let the answer be ready, that there is other company within.

So if it indeed true that "speaking with someone" is now perceived to be somehow un-British, this is not reflected in the OED as of 1989, nor in the English literature citated.
The phrasal verb "to speak to ━━"  has several senses.

*

*To address words or discourse to (a person); to talk to, converse with. to speak to     (see quot. 1837), so as to have conversation or personal acquaintance with one. Freq. in the phr. 'to know (one) to speak to'.

*

*c825   Vesp. Psalter xlix. 7   [Ic] sprecu to Israhela folce.

*971   Blickl. Hom. 141   Heo spræc to þæm weorode & cwæþ [etc.].

*OE   Beowulf 1171   Þu on sælum wes‥ond to Geatum spræc mildum wordum.

*c1000   West Saxon Gospels: John (Corpus Cambr.) x. 25   Ic spece [c1160 speke] to eow & ge ne gelyfað.
  a1325  (1250)    Gen. & Exod. (1968) l. 925   After ðis spac god to abram.

*c1384   Bible (Wycliffite, E.V.) (Douce 369(2)) (1850) 1 Cor. xiv. 3   He that prophecieth, spekith to men.

*a1400  (1325)    Cursor Mundi (Vesp.) l. 11964   Sai þou; i der noght til him speke.

*c1400   Pilgr. Sowle (1483) ɪᴠ.  xxiii. 69,   I wold haue spoke to them but I ne myght nought.

*1528   Rede me & be nott Wrothe sig. i iiijv,   Thus to the Cardinall he spake.

*1581   G. Pettie tr. S. Guazzo Ciuile Conuersat. (1586) ɪ. 13 b,   If‥you resalute not a friend, he will speake no more to you.

*a1635   R. Sibbes Heavenly Conf. (1656) 15   When he speaks aloof to her, she answereth aloof to him.

*1651   T. Hobbes Leviathan ɪɪɪ. xxxv. 216   Commanded by a Voice, as one man speaketh to another.

*1751   E. Haywood Hist. Betsy Thoughtless I. xiv. 165   What reply she made I do not know, being speaking to Wildly at the same time.

*1837   J. R. Lowell Lett. (1894) I. 21   How I remember the first time I ever saw you 'to speak to'.

*1908   R. Bagot Anthony Cuthbert xxvi. 342   It was too late that night to speak to her.

*With of, on, or about (a matter, etc.).

*

*?c1200   Ormulum (Burchfield transcript) l. 10466   Þatt fir. Þatt sannt iohan bapptisste. Spacc offe to þa sanderrmenn.

*a1450  (1410)    H. Lovelich Merlin (1904) I. l. 3204   What Scholen we don of this mateer That he to vs spak of now heer?

*1530   J. Palsgrave Lesclarcissement 727/1,   I speke to him of my busynes.

*1611   Bible (A.V.) 1 Sam. ix. 17   Behold the man whom I spake to thee of.

*1737   Gentleman's Mag. Aug. 492/1,   I have‥spoke to the King of England‥about your Friend.

*1796   H. Hunter tr. J. H. B. de Saint-Pierre Stud. Nature (1799) III. 234   They spake to me of the various Works of Nature.

*1804   Med. Jrnl. 12 448,   I also spoke to the principal surgeons‥on the subject of vaccination.

*1888   'J. S. Winter' Bootle's Children iv. 30   Whatever you wish for, you have only to speak to nurse here about it.

Here is the proper citation:

speak, v.
  Second edition, 1989; online version March 2012. http://www.oed.com/view/Entry/185910; accessed 11 May 2012. Earlier version first published in New English Dictionary, 1913.

to meet with
In contrast, the OED does say that for the second of its senses, usage of "to meet with" has apparently recently waned in Britain, although it was once common enough. I'll omit the citations for all but the second sense, as that is the relevant sense for the meaning under discussion.

*

*intr. To come across, come upon by chance, find, encounter (a thing or person). Now rare with a personal or physical object.

*intr. To go to see, come together with (a person) intentionally; to have a meeting with. Now chiefly N. Amer.

*

*c1300  (1225)    King Horn (Cambr.) (1901) 155   Þe children ȝede to Tune‥Hy metten wiþ almair king.

*c1380   Sir Ferumbras (1879) 3778   Þat body forþ þai bryngeþ‥to þe pauyllouns‥& meteþ with þᵉ Amyrel.

*a1400  (1325)    Cursor Mundi (Vesp.) 20145   In þe temple wit her he met, Anurd hir and tar hir grette.

*1477   Caxton tr. R. Le Fèvre Hist. Jason (1913) 120   Whan Iason was come to this temple Medea cam & mette with him.

*1567   G. Turberville Epitaphes, Epigrams f. 123ᵛ,   So hazard thou to come Vnto the pointed place, To thwart thy Friend, and meete with him That longs to see thy face.

*1661   A. Brome Songs & Other Poems 186   Pray come to T.—bring thy beloved Sue, My Mat. and I will meet with her and you.

*1719   D. Defoe Life Robinson Crusoe 41,   I had met with the Portugal Captain.

*1816   T. Chalmers Let. in W. Hanna Mem. T. Chalmers (1850) II. 78   We fell in with Mr. Cook, who came out to meet with me.

*1828   Scott Fair Maid of Perth viii, in Chron. Canongate 2nd Ser. II. 227   An appointment to meet with the others of his company at the sign of the Griffin.

*1968   E. Cleaver Soul on Ice ɪɪ. ii. 89   Robert Kennedy called together a group of 'influential' Negro entertainers and athletes to meet with him in secret.

*1993   N.Y. Times 7 Nov. v. 9/1   Men‥wander home to meet with friends and chew until early evening.

*† intr. To confront (an enemy); = sense  6a. Obs.

*† intr. To come into or be in physical contact with; to reach; to strike. Also of a river: to merge with (another river). Obs.

*† intr. To have sexual intercourse with. Cf. sense  8. Obs.

*intr. To experience, undergo (a particular fortune or treatment); to receive (a particular reaction); = sense  2.

*† intr. To oppose, contend with (an error, objection, or malpractice), take precautions against (a danger); to provide for (an emergency). Also: to cope with (a person). Obs.

*† intr. To agree or be in accord with. Obs.

*† intr. To exact requital; to get even with, pay back, settle with.

*† intr. Sc. To pay (a creditor). Obs. rare.

The requisite source citation is:

meet, v.
  Third edition, June 2001; online version March 2012. http://www.oed.com/view/Entry/115845; accessed 11 May 2012. An entry for this word was first included in New English Dictionary, 1906.

As I mentioned in comments, for me, there can be a difference in aspect between meeting someone and meeting with someone.  The former can be used for an instance of time, while the latter can be used for a duration.
Therefore you can meet someone at a pub, or meet them for a cup of coffee, or meet them for the first time.
However, when meeting with someone, you can say how long that meeting took place, so I could meet with them for two hours.

A: Yes, we can see from the OED entries that both "speak to" and "speak with" have been in use in British English for quite a while. However, this is another famous example of a divide between BrE and AmE. In BrE the more common preposition in the twentieth century was "speak TO somebody". Martin Parrott argues that "speak to" is standard (British) English, whereas "speak with somebody" has been stigmatised as a lower-class variant. Under the influence of AmE, the variant "speak with somebody" is considered more acceptable in BrE. Looking forward to ngrams or BNC results! :)
However, even in AmE there is a difference between "speak with" and "speak to". For example, the President of the US speaks to the nation.
As for "meet somebody" and "meet with somebody" - also another famous example - I'll post a quote from Pocket Fowler's:
"meet. There are two uses that deserve attention.   1. It is a transitive verb and so it is possible to meet someone, or simply meet. Idiomatically one meets with a circumstance rather than a person, typically something unpleasant or unwelcome; or one meets with a response or reaction, again often unfavourable (This may not meet with the approval of the parents / Her appointment as chief vet met with sniffiness among some farmers).
Now meet is increasingly used with the link word with (or up with, based on meet up) when people are involved, typically in contexts involving prolonged discussion or dealings (the people who will be meeting with the Secretary of State / A few weeks later I met up with them again). This is not entirely a new use: it is recorded in the OED from the 17c in the sense of casual or accidental encounter, including this quotation of 1740 from David Hume: 'Tis…rare to meet with persons, who can pardon another any opposition he makes to their interest'. It is true to say however that meet with has become fashionable again in contexts of intentional or arranged meeting under the influence of AmE, and tends to be used in contexts where plain meet would be more usual" [emphasis mine - Alex B.]
"meet"  Pocket Fowler's Modern English Usage. Ed. Robert Allen. Oxford University Press, 2008. Oxford Reference Online.

A: You are more likely to encounter speak with in American English, which employs the verb + with construction (speak with, meet with) very much more than British English does.
I remember hearing a clip of Laura Bush speaking on the radio (I think to the people of Afghanistan) and saying how pleased she was to be "speaking with you" and to British English ears it sounded very odd. On the radio, how are you doing anything other than speaking to your audience?


text:
Q: Pass cv::Mat to labview i try to build an DLL with the OpenCV PCA included to make it usable under Labview.
I have defined the the function:
extern "C" __declspec(dllexport) int __cdecl doPCA(float *input,int32_t input_rows,int32_t input_cols,double maxComponents,float *output);

And wrote it like:
int __cdecl doPCA(float *input,int32_t input_rows, int32_t input_cols,double maxComponents,float *output)

{

   Mat pcaset = Mat(input_rows,input_cols, CV_32FC1, &input);  //CV_32FC1 is for float valued pixel

   PCA pca(pcaset,                // pass the data
            Mat(),               // we do not have a pre-computed mean vector, // so let the PCA engine to compute it
            CV_PCA_DATA_AS_ROW,  // indicate that the vectors// are stored as matrix rows// (use PCA::DATA_AS_COL if the vectors are // the matrix columns)
            2                    // specify, how many principal components to retain
            );

  int i, j;
  for(i = 0; i < input_rows; i++)
  {
    for(j = 0; j < input_cols; j++)
    {
      output[(i * input_cols) + j] = pca.eigenvectors.data[(i * input_cols) + j];       // Write Values to 1D output array
    }
  }

    if(pca.eigenvectors.empty()){return 0;}     // is empty
    if(!pca.eigenvectors.empty()){return 1;}    // is not empty
}

At Labview side I access the function by the compiled DLL:

But I can´t figure it out, how to pass value the from pca.eigenvectors cv::Mat to the 1D float output array.
 int i, j;
  for(i = 0; i < input_rows; i++)
  {
    for(j = 0; j < input_cols; j++)
    {
      output[(i * input_cols) + j] = pca.eigenvectors.data[(i * input_cols) + j];       // Write Values to 1D output array
    }
  }

Could anyone give a hint?

A: I learn how to do PCA from the page that Miki gives.
This is my code to do the similar thing.
///! Convert pointer to cv::Mat, do PCA, and convert back.
///! 2017.10.05 10:28:25 CST

int doPCA(float* data, int rows, int cols, int maxC, float* eigenvecs ) {
    // convert pointer to Mat, CV_32FC1 is for float valued pixel.
    Mat pcaset = Mat(rows,cols, CV_32FC1, data);
    // let opencv compute the eigenvectors, and treat data as row, extract the first 2 principle components.
    // pca.means : eigenvalues as row matrix
    // pca.eigenvectors: eigenvectors as row matrix

    maxC = (maxC >0 && maxC <= rows)?maxC:rows;
    PCA pca(pcaset, Mat(), CV_PCA_DATA_AS_ROW,maxC);
    cout << "Eigen values:\n"<< pca.mean <<endl;
    cout << "Eigen vectors:\n"<<pca.eigenvectors<<endl;

    if(pca.eigenvectors.empty()) {
        return 0;   // is empty
    }

    float *pvec = eigenvecs;
    // get eigenvector in revered order
    for(int i=maxC-1; i>=0; --i){
        for(int j=0; j<cols; ++j){
            *pvec++ = pca.eigenvectors.at<float>(i,j);
        }
    }
    return 1;
}

int testPCA(){
    // row first
    float data[4] = {1.0,2.0,2.0,5.0};
    int cols = 2;
    int rows = 2;

    // alloc two eigenvectors length: 2x2=4
    float eigenvecs[4]={0};
    // max components nums
    int maxC = 2;
    int res = doPCA(data, rows, cols, maxC, eigenvecs);
    Mat eigenvalues(Size(cols, rows), CV_32FC1, eigenvecs);

    cout << "Flag:\n" << res << endl;
    cout << "Principle Components:\n"<< eigenvalues<<endl;
    return 0;
}

Result:
Eigen values:
[1.5, 3.5]
Eigen vectors:
[0.31622776, 0.94868332;
 0.94868332, -0.31622776]
Flag:
1
Principle Components:
[0.94868332, -0.31622776;
 0.31622776, 0.94868332]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Easiest or Best Free Way to Scan to PDF in Windows XP I have a scanner (part of an HP PSC 1315 multifunction printer, if that makes any difference).  I've recently paved my Windows XP machine and appear to have lost the software for the printer.  This has meant that I have to use Windows Image Acquisition or Microsoft Word to scan images and documents.
The main problem that I have with this scenario is that WIA only scans to images, not to PDF, and I would prefer to have my documents scanned to PDF (the HP software scanned to PDF and
did OCR as well).  I haven't actually used the Word integration (as I'd prefer not to have Word fully installed), but I'm open to using it if it can help me.  I have Word 2002/XP available.
I'm not really interested in finding a solution enough to have to buy something.
So, are there any free utilities for Windows XP which will let me scan to PDF?  Extra points for OCR, great software, or ease of use.

A: if you're happy with the HP software for your scanner, you can download the Officejet and PSC Full Feature Software (364 MB) from the HP support website.
other than that, you can print to to PDF from ANY application with a PDF printer driver (e.g. CutePDF)
and here's a list of Free OCR Software Dowloads, take your pick :)


text:
Q: Android running ant script on device by executing test cases and generage code coverage report I am very new to ANT script. I am working an android application and I have created corresponding Junit android test application. Now I have following in my build.xml file of my test project
<property name="src.dir" location="src" />
    <property name="test.dir" location="tests" />

    <property name="build.dir" location="bin" />
    <property name="build.test.dir" location="bin/tests" />

    <!-- Variables used for JUnit testin -->

    <property name="test.report.dir" location="testreport" />

    <!-- Define the classpath which includes the junit.jar and the classes after compiling-->
    <path id="junit.class.path">
        <pathelement location="libs/junit.jar" />
        <pathelement location="lib/hamcrest-core-1.3.jar" />
        <pathelement location="${build.dir}" />
    </path>

    <!-- Deletes the existing build, docs and dist directory-->
    <target name="clean">
        <delete dir="${build.dir}" />
        <delete dir="${test.report.dir}" />
    </target>

    <!-- Creates the  build, docs and dist directory-->
    <target name="makedir">
        <mkdir dir="${build.dir}" />
        <mkdir dir="${build.test.dir}" />
        <mkdir dir="${test.report.dir}" />
    </target>

    <!-- Compiles the java code (including the usage of library for JUnit -->
    <target name="compile" depends="clean, makedir">
        <echo>compile:clean, makedir</echo>
        <javac srcdir="${src.dir}" destdir="${build.dir}">
            <classpath refid="junit.class.path" />
        </javac>

        <javac srcdir="${test.dir}" destdir="${build.test.dir}">
            <classpath refid="junit.class.path" />
        </javac>

    </target>

    <!-- Run the JUnit Tests -->
    <!-- Output is XML, could also be plain-->
    <target name="junit" depends="compile">
          <echo>junit: compile</echo>
        <junit printsummary="on" fork="true" haltonfailure="yes">
            <classpath refid="junit.class.path" />
            <classpath>
                <pathelement location="${build.test.dir}"/>
              </classpath>
            <formatter type="xml" />
            <batchtest todir="${test.report.dir}">
                <fileset dir="${test.dir}">
                    <include name="**/*Test*.java" />
                </fileset>
            </batchtest>
        </junit>
    </target>

    <target name="main" depends="compile, junit">
        <description>Main target</description>
    </target>

When I run the above code by right click on build.xml->run as ant, I am able to execute Junit test scripts, but test case results are alwasys errors or failures. I guess, I need to execute the these test scripts on device. How can I execute these test scripts on device and at the same time I need to get code coverage report also. Please help me on this.


text:
Q: Renaming specific files in windows batch file [I have searched for a similar question but I did not find what I was looking for, so I am posting a new one.]
I want in my .bat file to SET a directory in a variable and I want to find all the files inside this directory (which all start with the same name) and rename them according to this pattern.
e.g file_location1.wml   -> file1.wml
    file_location2.wml   -> file2.wml
    file_location3.wml   -> file3.wml

Till now I am trying something like this:
    SET counter=1
    FOR /R %%f IN (C:\Documents\testFiles\*.*) DO (
        FOR /F "DELIMS=_ TOKENS=1,*" %%m IN ("%%~nxf") DO (
            REN "%%f" "%%m%counter%"
            SET counter=counter+1
        }
    }

It does not work. What am I doing wrong? I specify that i want to iterate over the files and rename each one with the first token + the counter's value.


text:
Q: Django / React Router DOM - Landing on a url not specified in django I'm building an app with django as the backend api and react as the frontend framework. When landing on an empty pathname url such as www.fakeapp.com/ django shows a frontend app view which renders an index page built with react.
Inside the react SPA I have <Link>s which update the <BrowserRouter>s <Route>s and might send you to the path /user/register (which is working fine). However, if I refresh the page with the new pathname www.fakeapp.com/user/register django doesn't recognize the url and throws an error.
I'm not sure the best path to take here since this is my first django project and my first time using react-router-dom. Should I specify more/different urlpatterns in the urls.py file for my frontend app, redirect back to the index, or something else?
I can post any code needed.

A: Your Django app needs to be able to recognize any URL that your react app needs to render. Usually you can do this with a wildcard in the Django urlconf

A: This happens because Django is handling the initial render. Unfortunately you can't do both. Either go all the way React for your routes or all the way Django for the routes with a corresponding React component for each Django route.


text:
Q: Issue in calling VB6 native dll from VB.net Project I have a vb6 project in which I use a dll library to do some tasks. For that, I add a module which declares all functions of that library such as:
Declare Function myFunction Lib "abcdapi.dll" (ByVal hVar1 As Long, ByVal hVar2 As Long) As Long

When I call this function (and many other similar) I'm able to do the work and correct Long pointer is returned. But when I try to do the same thing by VB.net (by importing the same library using dllimport and calling the same function), I get no result. although it does return some pointer but that doesn't produce correct result.
Private Const ABCD As String = "abcdapi.dll"
<DllImport(ABCD)>

Public Shared Function myFunction(ByVal hVar1 As IntPtr, ByVal hVar2 As IntPtr) As IntPtr
End Function

When I try to call the above function, it doesn't work. I even tried creating a dll in my vb6 project using the function and try to use imports keyword to call that new dll but that doesn't work either. What could be the issue and how do I make it work.

A: The docos you referenced show:
TM1IMPORT TM1_BOOL TM1API TM1ValBoolGet(TM1U hUser, TM1V vBool );

Is it possible that TM1U and TM1V are defined as 32 bit data types in that API and you are running your .NET code on a 64 bit machine, making your IntPtr a 64 bit data type?  (If the API came with C header files you can see how those data types are defined).  Try recompiling your .NET code to "x86" and try it again.
I just copied this code from your comment above:

the function call is below:

ibOK = TM1ValBoolGet(hUser, voTemp)

In VB.net:  <<< I assume here you meant VB6

Declare Function TM1ValBoolGet Lib "tm1api.dll" (ByVal hUser As Long, ByVal vBool As Long) As Integer

In vb.net:

<DllImport(TM1APIDLL)> Public Shared Function TM1ValBoolGet(ByVal hUser As IntPtr, ByVal vBool As IntPtr) As Integer
End Function

It is probably a typo, but that return type in your VB6 is not the same as the one in VB.NET.  A VB6 Integer is 16 bits and an Integer in VB.NET is 32 bits.


text:
Q: Support Multiple Environments in Angular 9 with .net core 3.1 project There are two files by default in Environments environment.ts and environment.prod.ts in Angular.
I want to create new environment.qa.ts file and get configuration from them.
I am using Angular 9 with .net core 3.1.
Where to write code ? OR Do we need to change any code in startup.cs file  ?
Post some code.
Any help Appericiated.

A: Just add the new environment file, in your case create environment.qa.ts in environment directory. Usually you can use environment.ts file as base file, and the modifications for the scenario.
After adding the new environment, you need to modify angular.json file accordingly. That will depend on what you want to achieve. Take a look that there is a configuration part in each architect command. For this, production configuration can guide you.


text:
Q: Appearance proxy affected by upgrade to iOS 6 My app implements a custom segmented control background image using:
// customise the segmented controls
    UIImage *segmentSelected = [[UIImage imageNamed:@"segcontrol_sel.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 15)];
    UIImage *segmentUnselected = [[UIImage imageNamed:@"segcontrol_uns.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 15)];
    UIImage *segmentSelectedUnselected = [UIImage imageNamed:@"segcontrol_sel-uns.png"];
    UIImage *segUnselectedSelected = [UIImage imageNamed:@"segcontrol_uns-sel.png"];
    UIImage *segmentUnselectedUnselected = [UIImage imageNamed:@"segcontrol_uns-uns.png"];

    [[UISegmentedControl appearance] setBackgroundImage:segmentUnselected forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [[UISegmentedControl appearance] setBackgroundImage:segmentUnselected forState:UIControlStateDisabled barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setDividerImage:segmentUnselectedUnselected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segmentSelectedUnselected forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segUnselectedSelected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

It was perfectly working before I updated to XCode 4.5 and iOS6. Now it's like that:

as you can see the background images size were altered. Did any anybody have the same problem?
Also some of the background images for some screen look shorter the requested. In one of them for example I have a blank space.

A: Make sure you name your images with @2x if they're at that resolution.
I had a similar-looking problem which was fixed when I added that.


text: Q: Are there any specific examples of the application of Lewis-Riesenfeld procedure to time dependent Hamiltonians in QM? Lewis-Riesenfeld invariant theory is a theory applicable to solve time-dependent Schrodinger equations. I have always encountered the theory related to the procedure, however never encountered any examples, where it is applied. Please let me know if there are any examples.


text:
Q: Length of a string using conditionals (using Python) I was trying a code where upon entering a string, we get the length of the string. However, if we enter an integer or float data type we get the "Wrong data type" message. Please find my code below:
def string_length(word):
    if type(word) == int:
        return "This is wrong data type"
    elif type(word) == float:
        return "Wrong data type again!"
    else:
        return len(word)

word = input("Enter the string: ")
print(string_length(word))

The program is running fine for string input, however, for integers it is returning the number of digits ("characters") instead of the message. Please find below the output terminal window:
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hellooo
7
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hello there
11
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 123
3
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 12.20
5

Can you please help me identify / rectify the mistake?
Thanks in advance.

A: As your input can be int and float you can use:
def string_length(input_string):
    if input_string.isdigit():
        return "Integer"
    elif input_string.startswith("-") and input_string.count('-') == 1:
        str_ = input_string.replace('-','')
        if input_string.replace('-','').isdigit():
            return "Integer"
        elif input_string.count('.') == 1 and str_.replace('.','').isdigit():
            return "Float"
    elif input_string.count('.') == 1 and input_string.replace('.','').isdigit():
        return "Float"
    else:
        return len(word)

A: Did you mean to have a function which tries these types for you?
def tryTypes(word):
    try:
        print(string_length(int(word)))
        return
    except ValueError as e:
        pass

    try:
        print(string_length(float(word)))
        return
    except ValueError as e:
        pass

    print(string_length(word))

word = input("Enter the string: ")
tryTypes(word)


text:
Q: Create instance from string by reinterpret cast My C++ is a bit rusty, for refreshing I am attempting to write a fcgi handler. I want to provide a class to hold the header fields. Since the header comes as a char[] from the socket and is 64 bits, I would like to have a constructor that simply copies the first 8 bytes into the instance data and is done. While I have some ideas how to this element wise I am afraid this might result in more than one copy operation on a 64 bit machine. I also would like to employ the initialiser list to prevent default construction overhead (which might not exist for chars). Since I find it hard to describe it in words here is the problem in C++, at first the class basic layout:
#include <boost/cstdint.hpp>

class header {
    const boost::uint8_t version;
    const boost::uint8_t type;

    const union {
        boost::uint16_t requestId;
        struct {
            boost::uint8_t requestIdB1;
            boost::uint8_t requestIdB0;
        };
    };

    const union {
        boost::uint16_t contentLength;
        struct {
            boost::uint8_t contentLengthB1;
            boost::uint8_t contentLengthB0;
        };
    };
    const boost::uint8_t paddingLength;
    const boost::uint8_t reserved;

    header(char* header);
    ~header();

    //utility methods/getter
};

Now the constructor has to be written. I could write something like:
header::header(char* header) : version(header[0]), type(header[1]) , ..., reserver(header[7]) {}

however I am afraid that this will involve mulitple byte copies rather than one 8-Byte Word copy. Is there a better way to write this? I would still like to be able to write header theHeader(&socketBuffer) rather than header theHeader=&reinterpret_cast<header*>(&socketBuffer) [socketBuffer is a char[]].
Considering C++11 also the following might work, however I am wondering if there is a better way.
C++11 forwarding to default copy constructor after cast:
header::header(char* header) : header(*reinterpret_cast<header*>(&socketBuffer)) {}


text:
Q: Group by user id in Model relation I have two models: Report and User. This is what I have in my User model
public function userReport() {
    return $this->hasMany('App\Report', 'user_id','id');
}

And this is in Report model
public function user() {
    return $this->hasOne('App\User', 'id', 'user_id');
}

Controller
public function details( $item_id ){

    $report = Item::find($item_id)->report;
    return view('details', compact('report'));
}

In view
{!! $report->user->name !!}

In view I show all the users who are reported single Item .. which I query by $item_id.
The problem is that if same user is reported single item 1+ time I see this user 1+ time in the table on the page.
Is it possible to somehow grouped by user_id or count the user_id and show User1 ( 4 time reported ) ...? Where should I group them?
Update: users table
id | username | password

reports table
report_id | id | user_id | date

item table
id | user_id | category | date_added | image

Update2: Image of records in db. Here user with user_id=3 has reported item_id=14 total of 14 times. User with user_id=5 has reported same item_id=14 total of 3 times. So I should see on page user_id=3 ( 14 ) and user_id=3 ( 3 ). Instead I see 17 times user_id=3. Bellow are images

And on page

A: There should be several ways how to solve your problem
One way is (your controller should look like)
public function details( $item_id ){
    $report = Item::find($item_id)->report->unique('user_id');
    return view('details', compact('report'));
}

Second way should be to use @foreach in view and there check for unique values.
Third way should be to use foreach in controller and prepare unique data with calculated summarizes inside controller and then pass that prepared data to view.
Which soulution you want to use is just a matter of choice.
Hope it helps you

A: Just try this. Hope it helps
Report::where('item.id', $item_id)
    ->select('item.*','users.*',DB::raw('count(reports.report_id) as total'))
    ->join('item', 'item.id', '=', 'reports.id')
    ->join('users', 'users.id', '=', 'reports.user_id')
    ->groupBy('reports.report_id','reports.id')
    ->get();


text:
Q: Is true == 1 && false == 0 always true in C? There are many questions of this kind on SO so I apologize for this additional one.
stdbool.h defines this:
#define true  (1)
#define false (0)

However I've seen many other declarations in bad code such as
#define true  (0xFF)
#define false (!true)

Or even worse
#define true  (0xAAAAAAAA)
#define false (~true)

In a real context we could imagine a variable int istrue used somewhere in a bad C program:
istrue = 1;

Because the code I am looking at is pretty ugly, I cannot assume I won't see things like:
if (istrue == 1)

That will make me refrain from replacing istrue = 1 with istrue = true.
So my question is:
In C, is true always equal to 1 and false always equal to 0 for any C compiler, and should this assumption always be valid in any case?


text:
Q: Kubernetes nginx ingress can't access pod in different namespace
I am trying to setup the kuard demo app in the namespace example-ns exposed by nginx ingress.
Exposing it in the default namespace works but when I expose it in the namespace example-ns I get:  ```503 Service Temporarily Unavailable```
These are to service, deployment and ingress yamls I use for kuard:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kuard
  namespace: example-ns
spec:
  selector:
    matchLabels:
      app: kuard
  replicas: 1
  template:
    metadata:
      labels:
        app: kuard
    spec:
      containers:
      - image: gcr.io/kuar-demo/kuard-amd64:1
        imagePullPolicy: Always
        name: kuard
        ports:
        - containerPort: 8080

---

apiVersion: v1
kind: Service
metadata:
  name: kuard
  namespace: example-ns
spec:
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
  selector:
    app: kuard

---

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: kuard
  namespace: example-ns
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: htpasswd
    nginx.ingress.kubernetes.io/auth-realm: "Enter your credentials"

spec:
  tls:
  - hosts:
    - example.mydomain.dev
    secretName: quickstart-example-tls
  rules:
  - host: example.mydomain.dev
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: kuard
            port:
              number: 80

As you can see everything is in the same namespace and describing the ingress results in:
❯ kubectl describe ingress kuard -n example-ns
Name:             kuard
Labels:           <none>
Namespace:        example-ns
Address:          192.168.69.1
Ingress Class:    <none>
Default backend:  <default>
TLS:
  quickstart-example-tls terminates example.mydomain.dev
Rules:
  Host                    Path  Backends
  ----                    ----  --------
  example.mydomain.dev
                          /   kuard:80 (10.69.58.226:8080)
Annotations:              cert-manager.io/cluster-issuer: letsencrypt-prod
                          kubernetes.io/ingress.class: nginx
                          nginx.ingress.kubernetes.io/auth-realm: Enter your credentials
                          nginx.ingress.kubernetes.io/auth-secret: htpasswd
                          nginx.ingress.kubernetes.io/auth-type: basic
Events:
  Type    Reason             Age                From                       Message
  ----    ------             ----               ----                       -------
  Normal  CreateCertificate  28m                cert-manager-ingress-shim  Successfully created Certificate "quickstart-example-tls"
  Normal  Sync               27m (x2 over 28m)  nginx-ingress-controller   Scheduled for sync
  Normal  Sync               27m (x2 over 28m)  nginx-ingress-controller   Scheduled for sync

I also read same issues like this but this solution is not working as seen here.
Anyone has an idea whats wrong here?
Thanks in advance!
SOLUTION:
I checked the logs of the ingress controller and saw that the auth secret was in the default namespace. Thats why only pods from default namespace were acessible. Moving the secret into the proper namespace solved the issue!

A: First of all you should not use the Annotation kubernetes.io/ingress.class anymore as it's deprecated. Instead use .spec.ingressClassName to refer to your desired Ingress Controller:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-myservicea
spec:
  ingressClassName: nginx
  rules:
  ...

It seems like that your Ingress in your desired Namespace can't seem to sync with the Controller, so if there is any Netpols in your example-ns and the Namespace where your Controller resides; back them up and delete them, to make sure the connection isn't being blocked.
Next you should check the logs of your Ingress Controller itself, if the connection reaches it; you will see surely the reason in the logs why the Ingress resource doesn't work. Also sharing your Config for the Ingress Controller would be helpful.


text:
Q: Pandas select rows when column value within range from another row column value I'm trying to create subset from dataframe(100k-500k rows)
with the following format
d = {'time':[1,2,3,5,7,9,9.5,10], 'val':['match','match','match','not','not','match','match','match']}
df = pd.DataFrame(d)

   time    val
0   1.0  match
1   2.0  match
2   3.0  match
3   5.0    not
4   7.0    not
5   9.0  match
6   9.5  match
7  10.0  match

I want to select a subset that include all rows when time  are within
limited range.
For example if range is <=1 the first and last three rows are selected
And my desired output:
   time    val
0   1.0  match
1   2.0  match
2   3.0  match
5   9.0  match
6   9.5  match
7  10.0  match

A: In one line it would look like this:
df.loc[(df['time'].diff()<=1)|(df['time'].diff(-1)>=-1)]

A: I got a solution, but i think it is not the best solution
dfasc=df.sort_values(['time'], ascending=1)
dfdesc=df.sort_values(['time'], ascending=0)

print (df[(dfasc['time'].diff()<=1.0) | (dfdesc['time'].diff()>=-1.0)])

   time    val
0   1.0  match
1   2.0  match
2   3.0  match
5   9.0  match
6   9.5  match
7  10.0  match

A: If you want to do it so it is vectorized this will work. You may want to used vectorized operations since your DF is so large. You may also want to put it into a function to save memory since I make a few variables below.
import numpy as np
import pandas as pd
df = pd.DataFrame({'time':[1,2,2.5,3,9,9.5,10,11,12],'val':
['not','match','match','match','match','match','match','not','not']})
'''
df
   time    val
0   1.0    not
1   2.0  match
2   2.5  match
3   3.0  match
4   9.0  match
5   9.5  match
6  10.0  match
7  11.0    not
8  12.0    not
'''
x = df.time.values
tmp = (x[1:] - x[:-1]) < 1
fst = tmp[0]
lst = tmp[-1]
mid = np.any([tmp[1:],tmp[:-1]],axis =0)
ans = np.concatenate([[fst],mid,[lst]])
df  = df[ans]
''' Output
   time    val
1   2.0  match
2   2.5  match
3   3.0  match
4   9.0  match
5   9.5  match
6  10.0  match
'''


text:
Q: How to argue this integral over this semicircle vanishes as $R\to \infty$? I want to evaluate the inverse Laplace transform of the function $$F(s)=\frac{A(s)}{B(s)},\quad B(s)=(s-s_1)\cdots (s-s_n),\quad s_i\neq s_j,\forall i\ne j.$$
I want to use the inversion formula together with contour integration. My starting point is the inversion formula $$\mathcal{L}^{-1}[F(s)]=\dfrac{1}{2\pi i}\int_{\gamma-i\infty}^{\gamma+i\infty}e^{st}F(s)ds,$$
where $\gamma \in \mathbb{R}$ is any number so that all singularities of $F(s)$ lie to its left in the complex plane.
In that case, assuming $A(s)$ has no singularities, the singularities are exactly $\{s_i\}$, so we take any $\gamma > \max \{\operatorname{Re}(s_i)\}$.
Next, I consider a contour $\Gamma$ made up of two pieces:

*

*$C_1(T)$: a vertical line $z(\lambda)=\gamma+i\lambda$ for $\lambda \in [-T,T]$. As $T\to \infty$ this one gives what we need.

*$C_2(T,R)$: a semicircle starting at $\gamma+iT$ and ending at $\gamma - iT$.
We then have set $$g(z)=\dfrac{1}{2\pi i}e^{zt}F(z).$$ We then have
$$\int_{C_1(T)} g(z)dz = \oint_{\Gamma}g(z)dz-\int_{C_2(T,R)}g(z)dz.$$
The integral over the closed contour can be done with the residue theorem. My issue is the last integral. We must take $T,R\to \infty$ but for the Laplace transform I don't see how to proceed.
I mean, I have the intuition. Call $z = x+iy$, along $C_2(T,R)$ if $R\to \infty$, then $x\to -\infty$. Then $e^{zt} = e^{xt}e^{iyt}\to 0$ as $R\to \infty$, so it should make the integral decay as well. But that is not really rigorous.
So how can I proceed here and show the integral on the semicircle $C_2(T,R)$ vanishes as $T,R\to \infty$?

A: You want to show that
$$\left | \int_{C_2(T,R)} dz \, e^{z t} F(z) \right | \to 0$$
as $R \to \infty$.  On $C_2(T,R)$, $\left | e^{z t} \right | = e^{R t \cos{\theta}}$ where $\theta \in [\pi/2, 3 \pi/2]$.  Thus, the integral is bounded by
$$\begin{align} \max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | \int_{\pi/2}^{3 \pi/2} d\theta \,  e^{R t \cos{\theta}} & = \max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | \int_0^{\pi} d\theta \,  e^{-R t \sin{\theta}} \\ &= 2 \max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | \int_0^{\pi/2} d\theta \,  e^{-R t \sin{\theta}} \\ &\le 2 \max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | \int_0^{\pi/2} d\theta \,  e^{-2 R t \theta/ \pi} \\ &\le \frac{\pi}{R t} \max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | \end{align}$$
As long as $\max_{\theta \in [\pi/2, 3 \pi/2]} \left | F \left ( R e^{i \theta} \right ) \right | = o(R)$ as $R \to \infty$, then the integral over $C_2(T,R)$ vanishes in this limit.


text:
Q: UIViewController present another UIViewController I Have a UIViewController 1 on it UIButton (added as subview), after I pressed Button (see pic.1 below) on it adding another UIViewController 2 with animation from the bottom to top after some action:
[[[UIApplication sharedApplication] keyWindow] addSubview:self.view];

And it overlaps UIButton, how can I add this subview that it does not cover UIButton(see pic.2 below)
pic.1:

pic. 2:

A: You haven't shown the animation code but I assume you add the subview off-screen, then change it's frame (animated) to slide it into view.
Add the new subview using insertSubview:belowSubview: instead, passing your button as the second argument. This way the button will overlap the new view, instead of the other way round. addSubview: always puts the new view on top of any others.
EDIT
From your comments it seems that you're adding the second view controller to the screen using presentModalViewController: so the above method won't work. As far as I know there is no way to keep an element from the original view controller on top of the new view controller's view if you are presenting it this way.
You may have to create a new UIWindow and set it's windowLevel to UIWindowLevelAlert to hold your button. This will keep it on top of any of the views underneath. Add this window as a subview to the main window.

A: {
SecondViewController *objComing=[[SecondViewController alloc] init];
[self.view addSubview:objComing.view];

objComing.view.backgroundColor=[UIColor blueColor];

objComing.view.frame=CGRectMake(0,420, 320, 0);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];

[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
objComing.view.frame=CGRectMake(0,0, 320, 420);

[UIView commitAnimations];

}
Put this code in the button action and replace secondViewController with your ViewController.


text:
Q: MailKit IMAP Idle - How to access 'done' CancellationTokenSource in CountChanged Event I am working with the IMAP Idle sample code found here
The sample requires a Console.ReadKey to cancel the CancellationTokenSource but makes a suggestion that it could be cancelled in the CountChanged event at the time new mail arrives so long as the event has access to the CancellationTokenSource.
How do I get access to the CancellationTokenSource in the CountChanged event?
Here is the snippit of code from the above link...
// Keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived).
client.Inbox.CountChanged += (sender, e) => {
    // Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged.
    var folder = (ImapFolder)sender;

Console.WriteLine("The number of messages in {0} has changed.", folder);

    // Note: because we are keeping track of the MessageExpunged event and updating our
    // 'messages' list, we know that if we get a CountChanged event and folder.Count is
    // larger than messages.Count, then it means that new messages have arrived.
    if (folder.Count > messages.Count) {
        Console.WriteLine("{0} new messages have arrived.", folder.Count - messages.Count);

        // Note: your first instict may be to fetch these new messages now, but you cannot do
        // that in an event handler (the ImapFolder is not re-entrant).
        //
        // If this code had access to the 'done' CancellationTokenSource (see below), it could
        // cancel that to cause the IDLE loop to end.
                // HOW DO I DO THIS??
    }
};

Console.WriteLine("Hit any key to end the IDLE loop.");
using (var done = new CancellationTokenSource()) {
    // Note: when the 'done' CancellationTokenSource is cancelled, it ends to IDLE loop.
    var thread = new Thread(IdleLoop);

thread.Start(new IdleState(client, done.Token));

    Console.ReadKey();
    done.Cancel();
    thread.Join();
}

A: All you need to do is rearrange the code a bit so that your event handlers have access to the done token.
Here's an example of how you could do this:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using MailKit;
using MailKit.Net.Imap;
using MailKit.Security;

namespace ImapIdle
{
    class Program
    {
        // Connection-related properties
        public const SecureSocketOptions SslOptions = SecureSocketOptions.Auto;
        public const string Host = "imap.gmail.com";
        public const int Port = 993;

        // Authentication-related properties
        public const string Username = "username@gmail.com";
        public const string Password = "password";

        public static void Main (string[] args)
        {
            using (var client = new IdleClient ()) {
                Console.WriteLine ("Hit any key to end the demo.");

                var idleTask = client.RunAsync ();

                Task.Run (() => {
                    Console.ReadKey (true);
                }).Wait ();

                client.Exit ();

                idleTask.GetAwaiter ().GetResult ();
            }
        }
    }

    class IdleClient : IDisposable
    {
        List<IMessageSummary> messages;
        CancellationTokenSource cancel;
        CancellationTokenSource done;
        bool messagesArrived;
        ImapClient client;

        public IdleClient ()
        {
            client = new ImapClient (new ProtocolLogger (Console.OpenStandardError ()));
            messages = new List<IMessageSummary> ();
            cancel = new CancellationTokenSource ();
        }

        async Task ReconnectAsync ()
        {
            if (!client.IsConnected)
                await client.ConnectAsync (Program.Host, Program.Port, Program.SslOptions, cancel.Token);

            if (!client.IsAuthenticated) {
                await client.AuthenticateAsync (Program.Username, Program.Password, cancel.Token);

                await client.Inbox.OpenAsync (FolderAccess.ReadOnly, cancel.Token);
            }
        }

        async Task FetchMessageSummariesAsync (bool print)
        {
            IList<IMessageSummary> fetched;

            do {
                try {
                    // fetch summary information for messages that we don't already have
                    int startIndex = messages.Count;

                    fetched = client.Inbox.Fetch (startIndex, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId, cancel.Token);
                    break;
                } catch (ImapProtocolException) {
                    // protocol exceptions often result in the client getting disconnected
                    await ReconnectAsync ();
                } catch (IOException) {
                    // I/O exceptions always result in the client getting disconnected
                    await ReconnectAsync ();
                }
            } while (true);

            foreach (var message in fetched) {
                if (print)
                    Console.WriteLine ("{0}: new message: {1}", client.Inbox, message.Envelope.Subject);
                messages.Add (message);
            }
        }

        async Task WaitForNewMessagesAsync ()
        {
            do {
                try {
                    if (client.Capabilities.HasFlag (ImapCapabilities.Idle)) {
                        // Note: IMAP servers are only supposed to drop the connection after 30 minutes, so normally
                        // we'd IDLE for a max of, say, ~29 minutes... but GMail seems to drop idle connections after
                        // about 10 minutes, so we'll only idle for 9 minutes.
                        using (done = new CancellationTokenSource (new TimeSpan (0, 9, 0))) {
                            using (var linked = CancellationTokenSource.CreateLinkedTokenSource (cancel.Token, done.Token)) {
                                await client.IdleAsync (linked.Token);

                                // throw OperationCanceledException if the cancel token has been canceled.
                                cancel.Token.ThrowIfCancellationRequested ();
                            }
                        }
                    } else {
                        // Note: we don't want to spam the IMAP server with NOOP commands, so lets wait a minute
                        // between each NOOP command.
                        await Task.Delay (new TimeSpan (0, 1, 0), cancel.Token);
                        await client.NoOpAsync (cancel.Token);
                    }
                    break;
                } catch (ImapProtocolException) {
                    // protocol exceptions often result in the client getting disconnected
                    await ReconnectAsync ();
                } catch (IOException) {
                    // I/O exceptions always result in the client getting disconnected
                    await ReconnectAsync ();
                }
            } while (true);
        }

        async Task IdleAsync ()
        {
            do {
                try {
                    await WaitForNewMessagesAsync ();

                    if (messagesArrived) {
                        await FetchMessageSummariesAsync (true);
                        messagesArrived = false;
                    }
                } catch (OperationCanceledException) {
                    break;
                }
            } while (!cancel.IsCancellationRequested);
        }

        public async Task RunAsync ()
        {
            // connect to the IMAP server and get our initial list of messages
            try {
                await ReconnectAsync ();
                await FetchMessageSummariesAsync (false);
            } catch (OperationCanceledException) {
                await client.DisconnectAsync (true);
                return;
            }

            // keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived).
            client.Inbox.CountChanged += OnCountChanged;

            // keep track of messages being expunged so that when the CountChanged event fires, we can tell if it's
            // because new messages have arrived vs messages being removed (or some combination of the two).
            client.Inbox.MessageExpunged += OnMessageExpunged;

            // keep track of flag changes
            client.Inbox.MessageFlagsChanged += OnMessageFlagsChanged;

            await IdleAsync ();

            client.Inbox.MessageFlagsChanged -= OnMessageFlagsChanged;
            client.Inbox.MessageExpunged -= OnMessageExpunged;
            client.Inbox.CountChanged -= OnCountChanged;

            await client.DisconnectAsync (true);
        }

        // Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged.
        void OnCountChanged (object sender, EventArgs e)
        {
            var folder = (ImapFolder) sender;

            // Note: because we are keeping track of the MessageExpunged event and updating our
            // 'messages' list, we know that if we get a CountChanged event and folder.Count is
            // larger than messages.Count, then it means that new messages have arrived.
            if (folder.Count > messages.Count) {
                int arrived = folder.Count - messages.Count;

                if (arrived > 1)
                    Console.WriteLine ("\t{0} new messages have arrived.", arrived);
                else
                    Console.WriteLine ("\t1 new message has arrived.");

                // Note: your first instict may be to fetch these new messages now, but you cannot do
                // that in this event handler (the ImapFolder is not re-entrant).
                //
                // Instead, cancel the `done` token and update our state so that we know new messages
                // have arrived. We'll fetch the summaries for these new messages later...
                messagesArrived = true;
                done?.Cancel ();
            }
        }

        void OnMessageExpunged (object sender, MessageEventArgs e)
        {
            var folder = (ImapFolder) sender;

            if (e.Index < messages.Count) {
                var message = messages[e.Index];

                Console.WriteLine ("{0}: message #{1} has been expunged: {2}", folder, e.Index, message.Envelope.Subject);

                // Note: If you are keeping a local cache of message information
                // (e.g. MessageSummary data) for the folder, then you'll need
                // to remove the message at e.Index.
                messages.RemoveAt (e.Index);
            } else {
                Console.WriteLine ("{0}: message #{1} has been expunged.", folder, e.Index);
            }
        }

        void OnMessageFlagsChanged (object sender, MessageFlagsChangedEventArgs e)
        {
            var folder = (ImapFolder) sender;

            Console.WriteLine ("{0}: flags have changed for message #{1} ({2}).", folder, e.Index, e.Flags);
        }

        public void Exit ()
        {
            cancel.Cancel ();
        }

        public void Dispose ()
        {
            client.Dispose ();
            cancel.Dispose ();
            done?.Dispose ();
        }
    }
}

A: Following the previous Answer, I made it work as a background service for an Api
public class InboxMessageSubscriptionService : BackgroundService
{
    public IServiceProvider Services { get; }
    public IConfiguration Configuration { get; }

    private IdleClient client;
    public InboxMessageSubscriptionService(IServiceProvider services, IConfiguration configuration)
    {
        /*
         * Outlook Ports and info : https://support.microsoft.com/en-us/office/pop-imap-and-smtp-settings-for-outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
         *
         *
         * Outlook Imap Server Name: "outlook.office365.com"
         * Outlook IMAP Port: 993
         *
         *
         * Following example: https://stackoverflow.com/questions/57834770/mailkit-imap-idle-how-to-access-done-cancellationtokensource-in-countchanged
         *
         */

        Services = services;
        Configuration = configuration;
    }

    public override Task StartAsync(CancellationToken cancellationToken)
    {
        using (var scope = Services.CreateScope())
        {
            var settings = Configuration.GetSection(SettingsOptions.SettingsPath).Get<SettingsOptions>();
            client = new IdleClient("outlook.office365.com", 993, settings.Emails.Sender, settings.Emails.Password);
        }

        return base.StartAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await client.RunAsync();
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        try
        {
            client.Exit();
            client.Dispose();
        }catch (Exception ex)
        {
            Console.Error.WriteLine("Error when disposing the IdleClient");
        }

        return base.StopAsync(cancellationToken);
    }
}

class IdleClient : IDisposable
{
    List<IMessageSummary> messages;
    CancellationTokenSource cancel;
    CancellationTokenSource done;
    bool messagesArrived;
    ImapClient client;
    private readonly string host;
    private readonly int port;
    private readonly string email;
    private readonly string password;

    public IdleClient(string host, int port, string email, string password)
    {
        this.host = host;
        this.port = port;
        this.email = email;
        this.password = password;

        client = new ImapClient();
        messages = new List<IMessageSummary>();
        cancel = new CancellationTokenSource();
    }

    async Task ReconnectAsync()
    {
        if (!client.IsConnected)
            await client.ConnectAsync(host, port, true, cancel.Token);

        if (!client.IsAuthenticated)
        {
            await client.AuthenticateAsync(email, password, cancel.Token);

            await client.Inbox.OpenAsync(FolderAccess.ReadOnly, cancel.Token);
        }
    }

    async Task FetchMessageSummariesAsync(bool print)
    {
        IList<IMessageSummary> fetched;

        do
        {
            try
            {
                // fetch summary information for messages that we don't already have
                int startIndex = messages.Count;

                fetched = client.Inbox.Fetch(startIndex, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId, cancel.Token);
                break;
            }
            catch (ImapProtocolException)
            {
                // protocol exceptions often result in the client getting disconnected
                await ReconnectAsync();
            }
            catch (IOException)
            {
                // I/O exceptions always result in the client getting disconnected
                await ReconnectAsync();
            }
        } while (true);

        foreach (var message in fetched)
        {
            if (print)
                Console.WriteLine("{0}: new message: {1}", client.Inbox, message.Envelope.Subject);
            messages.Add(message);
        }
    }

    async Task WaitForNewMessagesAsync()
    {
        do
        {
            try
            {
                if (client.Capabilities.HasFlag(ImapCapabilities.Idle))
                {
                    // Note: IMAP servers are only supposed to drop the connection after 30 minutes, so normally
                    // we'd IDLE for a max of, say, ~29 minutes... but GMail seems to drop idle connections after
                    // about 10 minutes, so we'll only idle for 9 minutes.
                    using (done = new CancellationTokenSource(new TimeSpan(0, 9, 0)))
                    {
                        using (var linked = CancellationTokenSource.CreateLinkedTokenSource(cancel.Token, done.Token))
                        {
                            await client.IdleAsync(linked.Token);

                            // throw OperationCanceledException if the cancel token has been canceled.
                            cancel.Token.ThrowIfCancellationRequested();
                        }
                    }
                }
                else
                {
                    // Note: we don't want to spam the IMAP server with NOOP commands, so lets wait a minute
                    // between each NOOP command.
                    await Task.Delay(new TimeSpan(0, 1, 0), cancel.Token);
                    await client.NoOpAsync(cancel.Token);
                }
                break;
            }
            catch (ImapProtocolException)
            {
                // protocol exceptions often result in the client getting disconnected
                await ReconnectAsync();
            }
            catch (IOException)
            {
                // I/O exceptions always result in the client getting disconnected
                await ReconnectAsync();
            }
        } while (true);
    }

    async Task IdleAsync()
    {
        do
        {
            try
            {
                await WaitForNewMessagesAsync();

                if (messagesArrived)
                {
                    await FetchMessageSummariesAsync(true);
                    messagesArrived = false;
                }
            }
            catch (OperationCanceledException)
            {
                break;
            }
        } while (!cancel.IsCancellationRequested);
    }

    public async Task RunAsync()
    {
        // connect to the IMAP server and get our initial list of messages
        try
        {
            await ReconnectAsync();
            await FetchMessageSummariesAsync(false);
        }
        catch (OperationCanceledException)
        {
            await client.DisconnectAsync(true);
            return;
        }

        // keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived).
        client.Inbox.CountChanged += OnCountChanged;

        // keep track of messages being expunged so that when the CountChanged event fires, we can tell if it's
        // because new messages have arrived vs messages being removed (or some combination of the two).
        client.Inbox.MessageExpunged += OnMessageExpunged;

        // keep track of flag changes
        client.Inbox.MessageFlagsChanged += OnMessageFlagsChanged;

        await IdleAsync();

        client.Inbox.MessageFlagsChanged -= OnMessageFlagsChanged;
        client.Inbox.MessageExpunged -= OnMessageExpunged;
        client.Inbox.CountChanged -= OnCountChanged;

        await client.DisconnectAsync(true);
    }

    // Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged.
    void OnCountChanged(object sender, EventArgs e)
    {
        var folder = (ImapFolder)sender;

        // Note: because we are keeping track of the MessageExpunged event and updating our
        // 'messages' list, we know that if we get a CountChanged event and folder.Count is
        // larger than messages.Count, then it means that new messages have arrived.
        if (folder.Count > messages.Count)
        {
            int arrived = folder.Count - messages.Count;

            if (arrived > 1)
                Console.WriteLine("\t{0} new messages have arrived.", arrived);
            else
                Console.WriteLine("\t1 new message has arrived.");

            // Note: your first instict may be to fetch these new messages now, but you cannot do
            // that in this event handler (the ImapFolder is not re-entrant).
            //
            // Instead, cancel the `done` token and update our state so that we know new messages
            // have arrived. We'll fetch the summaries for these new messages later...
            messagesArrived = true;
            done?.Cancel();
        }
    }

    void OnMessageExpunged(object sender, MessageEventArgs e)
    {
        var folder = (ImapFolder)sender;

        if (e.Index < messages.Count)
        {
            var message = messages[e.Index];

            Console.WriteLine("{0}: message #{1} has been expunged: {2}", folder, e.Index, message.Envelope.Subject);

            // Note: If you are keeping a local cache of message information
            // (e.g. MessageSummary data) for the folder, then you'll need
            // to remove the message at e.Index.
            messages.RemoveAt(e.Index);
        }
        else
        {
            Console.WriteLine("{0}: message #{1} has been expunged.", folder, e.Index);
        }
    }

    void OnMessageFlagsChanged(object sender, MessageFlagsChangedEventArgs e)
    {
        var folder = (ImapFolder)sender;

        Console.WriteLine("{0}: flags have changed for message #{1} ({2}).", folder, e.Index, e.Flags);
    }

    public void Exit()
    {
        cancel.Cancel();
    }

    public void Dispose()
    {
        client.Dispose();
        cancel.Dispose();
        done?.Dispose();
    }
}


text:
Q: Error while compiling firebase based project in objective c I am trying to use Firebase with Objective-C.
I get following error when trying to compile my project. My code looks fine. The issue is originated from Firebase.h:

Error:  property with 'retain (or strong)' attribute must be of object
  type in file FConfig.h

it is showing error in the following line of the file
@property (nonatomic, strong) dispatch_queue_t callbackQueue;

FConfig.h is included in Firebase.h.

A: Firebase Engineer here,
Sounds like the problem here has to do with older versions of the iOS SDK, where dispatch_queue_t is not an object in iOS 5, but is an object in iOS 6 (due to ARC being more fully rolled out).
Therefore, in iOS 5 and prior, we would need to use:
@property (nonatomic, assign) dispatch_queue_t callbackQueue;

Rather than in iOS 6+:
@property (nonatomic, strong) dispatch_queue_t callbackQueue;

More info on this is in this Stack Overflow Question.
As iOS adoption on new versions is generally fairly high, Firebase doesn't support iOS 5 and before (and generally won't fix issues with iOS6), as it's estimated that the share of devices running these OS's is relatively small (~5%). Is there a particular reason you're targeting iOS 6 (or earlier)?

A: I found a temporary fix for it:
In your podfile where You see
target 'Runner' do
  use_frameworks!

comment user_frameworks!
target 'Runner' do
  # use_frameworks!

and go to path /ios of the project
run
pod install
and cheers


text:
Q: Display decrypted or empty value in configuration I have a configuration value that I encrypt upon save, but when I look at it again in the configuration (UI), I get the encrypted string. I would like to show an empty string (production) or the correct decrypted value (for testing), but cannot quite figure out how to do this.
The logical way I know of is to write a source model, but those seem to only work for select elements. This is a simple text field. I need a way to receive the original data, decrypt with (with Magento\Framework\Encryption\EncryptorInterface), and display the decrypted value; either that or an empty value.

A: Partial answer:
Turns out, in this specific case, it's possible to have Magento decrypt the value automatically on display / retrieval, by setting a backend model in config.xml too. For example:
<section>
    <group>
        <field backend_model="Magento\Config\Model\Config\Backend\Encrypted" />
    </group>
</section>

However, it does not answer the question's general case (especially the blank value), an answer addressing this would be appreciated!


text:
Q: Prometheus TimeStamp with too many characters I am using the go remote writer here: https://github.com/prometheus/prometheus/blob/master/documentation/examples/remote_storage/example_write_adapter/server.go
This line
fmt.Printf("  %f %d\n", s.Value, s.Timestamp)

Prints this timestamp 1526415583412 and it's date is 9/3/50340
Which is impossible.
But if a remove three characters it works
1526415583

A: Prometheus timestamps are in milliseconds.

A: You can use time.Second/time.Millisecond to convert from Milliseconds to Seconds:
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Unix(1526415583412/int64(time.Second/time.Millisecond),0))
}

Prints 2018-05-15 20:19:43 +0000 UTC
Or, just divide by 1000.
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Unix(1526415583412/1000,0))
}


text:
Q: Is the filter executed first then the validator in the Zend Framework If I had this code
$field = new Zend_Form_Element();
$field->addValidator(new Zend_Validate_Alnum());
$field->setFilter(new Zend_Filter_StringToLower());

is the check for only alphanumeric characters executed after the string has been transformed to lower case?

A: Yes. The filter is activated by the element's getValue() method.

A: In Zend/Form/Element.php, method isValid:
    $this->setValue($value);
    $value = $this->getValue();

getValue call the filters on the data, before the value is passed to the validators. So yes, the value is filtered before validation. You can test it with:
$field = new Zend_Form_Element('test');
$field->addValidator(new Zend_Validate_Alnum());

// Display bool(false)
var_dump($field->isValid('A,B'));

$field->addFilter(new Zend_Filter_Alnum());

// Display bool(true)
var_dump($field->isValid('A,B'));


text:
Q: How to generalize a method I have a method which I want to generalize. I want to use following Deserialize function for any object type, as belew:
ExportDefinition _expDefinition = new ExportDefinition("a.ini");
DeliveryDefinition _delDefinition = new DeliveryDefinition("b.ini");

ExportDefinition expDef = Deserialize(_expDefinition);
DeliveryDefinition devDef = Deserialize(_delDefinition);

public SomeType Deserialize(SomeType?? tp)  // What should I use instead of SomeType?
{
    try
    {
        FileStream readFileStream = new FileStream(definitionFile, FileMode.Open, FileAccess.Read, FileShare.Read);

        XmlSerializer serializerObj = new XmlSerializer(typeof(tp));
        tp loadedObj = (tp)serializerObj.Deserialize(readFileStream);
        readFileStream.Close();
     }
     catch (Exception ex)
     {
        throw new Exception(ex.Message);
     }

     return loadedObj;
}

Any ideas, how to achieve this?

A: Use generics:
    public T Deserialize<T>(string filePath)
    {
        Stream stream = null;

        try
        {
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlSerializer serializerObj = new XmlSerializer(typeof(T));

            return (T)serializerObj.Deserialize(stream);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (stream != null)
            {
                stream.Close();
            }
        }
    }

The non-generic version based on the useful comment of Marc Gravell:
public object Deserialize(string filePath, Type type)
{
    Stream stream = null;

    try
    {
        stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        XmlSerializer serializerObj = new XmlSerializer(type);

        return serializerObj.Deserialize(stream);
    }
    catch (Exception)
    {
        // Put something useful here
        throw;
    }
    finally
    {
        if (stream != null)
        {
            stream.Close();
        }
    }
}


text:
Q: How to convert UTCSeconds to TimeString? How to Convert UTC Seconds to This format:
00 h, 00 min, 00 sec

This code won't work:
concat(floor(Duration/DurationUTC div 360) mod 24,' h ',
       floor(Duration/DurationUTC div 60) mod 60,' min ',
       Duration/DurationUTC mod 60,' sec')

I'm using XPath 1.0.

A: It should work if your seconds are in a structure such as this:
<Duration><DurationUTC>84341</DurationUTC></Duration>

And if you are calling the XPath expression in the correct context.
But everytime you reach 24 hours, it becomes zero. Perhaps that's the error you are encountering. If you don't want that behaviour just remove the mod expression:
concat(
    floor(/Duration/DurationUTC div 3600),' h ',
    floor(/Duration/DurationUTC div 60) mod 60,' min ',
    /Duration/DurationUTC mod 60,' sec')

Now, for the example above, it will generate:
23 h 25 min 41 sec

There is no number formatting in XPath 1.0 but if you want padding for two digits in the format you described 00 h, 00 min, 00 sec, there is a hack you can use. It uses the converted result as a predicate to select or not the node where the value is stored, then gets one of the digits that are in the node, converts it to a 0 and uses that character for padding when the calculated values are less than 10:
concat(
    translate(substring(/Duration/DurationUTC[floor(/Duration/DurationUTC div 3600) < 10],1,1),'0123456789','0000000000'),
    floor(/Duration/DurationUTC div 3600),' h ',
    translate(substring(/Duration/DurationUTC[floor(/Duration/DurationUTC div 60) mod 60 < 10],1,1),'0123456789','0000000000'),
    floor(/Duration/DurationUTC div 60) mod 60,' min ',
    translate(substring(/Duration/DurationUTC[floor(/Duration/DurationUTC mod 60) < 10],1,1),'0123456789','0000000000'),
    /Duration/DurationUTC mod 60,' sec'
)

Now, if you have:
<Duration><DurationUTC>3970</DurationUTC></Duration>

instead of:
1 h 6 min 10 sec

you get:
01 h 06 min 10 sec


text:
Q: genetic algorithm with outer fitness function in Matlab I am trying to use genetic algorithm in Matlab app in order to solve an optimization problem.i don't have the fitness function.what i have is a model from Vensim software.population enter to the Vensim model and the output is fitness function.we have 10 chromosome that have 10 value for fitness function.what kind of commands we can use in Matlab that match each fitness value with its own chromosome.
for example:
my new population is : [1 2 3;4 5 6;7 8 9]
my fitness function values is: [100;200;300]
i want calculate chromosome(1,2,3) with 100 values fitness function. or first rows of matrix population = first of rows matrix fitness function.

A: population = [1 2 3;4 5 6;7 8 9];
fitness_function = [100;200;300];
for ii = 1:length(fitness_function)
    chromosome = population(ii,:);
    fitness_value = fitness_function(ii);
    result = calculate(chromosome, fitness_value);
end


text:
Q: Why I can't connect QAction SIGNAL with QFileDialog SLOT? I'm trying to write application's menu for my text editor, but I don't understand why signal triggered does not working. It should open a QFileDialog::getOpenFileName, but it does not happen. Why?
main.cpp
#include "mainwindow.h"
#include "centralwidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow      *mainWindow     = new MainWindow;
    CentralWidget   *centralWidget  = new CentralWidget;

    mainWindow->setCentralWidget(centralWidget);
    mainWindow->show();

    return a.exec();
}

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QStatusBar>
#include <QAction>
#include <QFileDialog>
#include <QString>

class MainWindow : public QMainWindow
{
public:
    MainWindow();

public slots:
    void slotFileDialog();
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"

MainWindow::MainWindow()
{
    QMenu *fileMenu = new QMenu("File");
    QAction *openAction = new QAction(tr("&Open..."), this);
    connect(openAction, SIGNAL(triggered()),
                            this, SLOT(slotFileDialog()));
    fileMenu->addAction(openAction);

    QMenuBar *mainMenu = new QMenuBar;
    mainMenu->addMenu(fileMenu);
    mainMenu->show();

    QStatusBar *mainStatusBar = new QStatusBar;

    setMenuBar(mainMenu);
    setStatusBar(mainStatusBar);
}

void MainWindow::slotFileDialog()
{
    QString fileName = QFileDialog::getOpenFileName(
                this, tr("Open File"),"/home",tr("Text (*.txt)"));
}

A: You haven't included the Q_OBJECT macro in the class definition, so the moc will not generate the associated files for it.


text:
Q: SHOW FULL COLUMNS isn't returning utf8_mb3_collation as expected in MySQL8.0.28 I've just downloaded MySQL 8.0.28 and I was expecting to see my collations changed as specified in the documentation:
https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8mb3.html
But I'm still getting utf8_my_collation while using SHOW FULL COLUMNS FROM table; instead of the expected utf8mb3_my_collation. Is that normal? Did I misunderstood the doc?


text:
Q: If Statement doesn't recognize string I was trying to see if A was "x" but the code I used did't work, it seems like A wasn't "x" even when I typed in x. can someone tell me what did I get wrong?
import sys
A=(sys.stdin.readline)
if A == "x":
   ''' Code here'''

When I type in x the if statement still won't go off

A: Did you realize that Ais a reference to the readline function in your sample code? This is because it will never be equal to the character "x".
Edit:
Also, if you want to compare input string, I think you should trim the input string.
import sys
A=(sys.stdin.readline())

if A.strip() == "x":
    # Code...


text:
Q: PostgreSQL doesn't work in ubuntu 20.04 Django Docker My docker-compose works fine and runs on Windows 10 but when i tried to run it from ubuntu 20.04 i get the DB errors.
My django settings.py file:
DATABASES = {
    'default': {
        'ENGINE': env('SQL_ENGINE'),
        'NAME': env('SQL_DATABASE'),
        'USER': env('SQL_USER'),
        'PASSWORD': env('SQL_PASSWORD'),
        'HOST': env('SQL_HOST'),
        'PORT': env('SQL_PORT'),
    }
}

my .env file:
SQL_ENGINE=django.db.backends.postgresql
SQL_DATABASE=my_db
SQL_USER=my_admin
SQL_PASSWORD=my_api
SQL_HOST=db
SQL_PORT=5432

My 'docker-compose.yml` file:
version: '3.9'
services:
  web:
    build: ./pets
    command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/app/web/staticfiles
      - media_volume:/home/app/web/mediafiles
    expose:
      - 8000
    env_file:
      - .env
    depends_on:
      - db
  db:
    image: postgres:12.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - .env
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/home/app/web/staticfiles
      - media_volume:/home/app/web/mediafiles
    ports:
      - "1337:80"
    depends_on:
      - web
volumes:
  postgres_data:
  static_volume:
  media_volume:

My Dockerfile:
FROM python:3.10.0-alpine
WORKDIR /usr/src/app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN pip install --upgrade pip
RUN apk update
RUN apk add postgresql-dev gcc python3-dev musl-dev
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY entrypoint.sh .
RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir $HOME
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
COPY .. $APP_HOME
RUN mkdir $APP_HOME/staticfiles
RUN mkdir $APP_HOME/mediafiles
RUN chmod +x /usr/src/app/entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

First error i got:
FATAL: role "my_admin" does not exist

When i change the SQL_USER to postgres i've got the next error:
FATAL: database "my_db" does not exist

After this i change the SQL_DATABASE to postgres, but still i've got:
django.db.utils.ProgrammingError: relation "auth_user" does not exist"

What's wrong? Why it doesn't work on ubuntu 20.04, but perfectly works on windows 10?


text:
Q: How to extract fields from 'Layout' JSON file of Power BI tool with Python? I request a code modification that extracts columns from a (nested) JSON file inside a '.PBIX' file (Power BI tool) in Python. The details are below:

*

*Original code to extract some columns written by Mr Umberto Grando:

*Code on GitHub: https://github.com/Inzaniak/pybistuff/tree/master/pbixExtractor

*Explanation of the code on Medium: https://python.plainenglish.io/extracting-measures-and-fields-from-a-power-bi-report-in-python-1b928d9fb128

*I extracted the Layout file for your convenience in Google Drive: https://drive.google.com/drive/folders/1Z5cqgE-iuS0__G5hCl7Ge-MZW9WKmJu7?usp=sharing
Request:

*

*I need to extract the 'visualType' field as well in a similar format in the GitHub code above for Business Documentation. To be able to extract parameters like this in a table automatically will save hours of time in documentation.

I tried:

*

*JS Beautify
JSON dumps, JSON LOADS, JSON Normalize, Different Encoding types, Adding ['visualTypes'] in code but didn't know how to append. I have trouble understanding the structure of the JSON file here, too.

Other tries :
!cd "path/Layout"
import json

# Opening JSON file
f = open('path/Layout', encoding='utf-16 le')

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data:
    print(i)

###Output: ###

*

*id sections pods config reportId resourcePackages layoutOptimization
publicCustomVisuals

A: Main reason this was downwoted what that you did not post any code or errors when you tried to solve this.
When I tried I got this error:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
and:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 9380: invalid start byte
This you can most likely find lots of answers to with google:
When you see byte errors in json.load() it is most likely encoding, so chardet will help you:
#!/usr/bin/env python3
import json
import chardet
raw = "C:\\Users\\mobj\\Downloads\\Layout"

with open(raw, 'rb') as FI:
    print(chardet.detect(FI.read()))

dat = {}
# encoding from chardet:
with open(raw, 'r', encoding='utf-16le', errors='ignore') as FI:
    dat = json.load(FI)

print(json.dumps(dat, indent=2, sort_keys=True))


text:
Q: Node.js script fails to run from flask python subprocess.run I have a node.js script running on ubuntu (stripped down to only include issue):
import axios from 'axios';
console.log("axios import ok")

This can be run fine from command line using node /home/verifier/verify.js
and outputs "axios import ok" to the console.
We need to execute this node script via api using flask:
from subprocess import check_output, call, run, PIPE

@api.route('/cbor', methods=['POST'])
def cbor():
    #res = request.json

    #cbor = res["cbor"]
    p = run(f"node /home/verifier/verify.js", shell = True,stdout = PIPE, stderr = PIPE, universal_newlines = True)

    return str(p), 200

The flask file (api.py) is in the same directory as verify.js
This returns a string of the CompletedProcess object:
stderr="/home/verifier/verify.js:2\nimport axios from 'axios';\n ^^^^^\n\nSyntaxError: Unexpected identifier\n at
Module._compile (internal/modules/cjs/loader.js:723:23)\n at Object.Module._extensions..js
(internal/modules/cjs/loader.js:789:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad
(internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at
Function.Module.runMain (internal/modules/cjs/loader.js:831:12)\n at startup (internal/bootstrap/node.js:283:19)\n at
bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n")

So when we try to run the node script from within flask the import fails with
Unexpected identifier atModule._compile (internal/modules/cjs/loader.js:723:23)

into stderr
The stack is direct. Flask is directly receiving from the port rather than using nginx / gunicorn.
so just
api = Flask(__name__)
if __name__ == '__main__':
    api.run(host='DropletIP removed')

I assumed it was a path issue. But the node script appears to be being started in the correct dir as if i run
p = run(f"pwd", shell = True,stdout = PIPE, stderr = PIPE, universal_newlines = True)

    return str(p), 200

It returns
CompletedProcess(args='pwd', returncode=0, stdout='/home/verifier\n', stderr='')
does anyone have a suggestion as to why when running the script through subprocess.run it causes the node.js imports to fail? I can run normal js code but cannot import when opened via flask.


text:
Q: How can I use mockito to verify that a function has never been called, with any argument? I want to verify that a function has never been called using mockito. I am aware of the verifyNever function, but that does not seem to work in my case, or I'm not using it correctly.
My test currently looks like this:
test('when the string is less than 3 characters api is not called', () async {
  var databaseService = getAndRegisterDatabaseService();
  var model = ViewModel();

  model.searchPatient('sk');

  // Wait for futures to finish.
  await Future.delayed(Duration(seconds: 0));

  verifyNever(databaseService.searchPatient('sk'));
});

but I get an error when running the test:
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)

To me it seems like verifyNever won't work if the function has never been called, just that it has never been called with a specific argument. Is that correct? In that case, is there another way to test what I want?

A: The verifyNever examples from package:mockito's README.md cover your case:

// Or never called
verifyNever(cat.eatFood(any));

So, in your case, assuming that databaseService is a Mock object, you should be able to use verifyNever(databaseService.searchPatient(any)); to verify that the .searchPatient method is never called, regardless of the arguments.

A: After trying to write a minimal reproducible example it turns out that the problem was that I read the output incorrectly.
In the following output I read the top row as the title for the failed test, when in fact it is the bottom row that is the name of the failed error than corresponds to the above output.
✓ ViewmodelTest - searchPatient - when the string is less than 3 characters api is not called
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api                                     fail
_VerifyCall._checkWith
package:mockito/src/mock.dart:672
_makeVerify.<fn>
package:mockito/src/mock.dart:954
main.<fn>.<fn>.<fn>
test/viewmodel_tests/viewmodel_test.dart:144
✖ ViewmodelTest - searchPatient - api is called with correct and cleaned query


text:
Q: how to make key of map to variable name In java,i have a Map that contains certain values. I want to create a String variable that having the name of the key of the map. How it is possible in java?
Map<String,String> values=new HashMap<String, String>();
values.put("dataSource", "bloomberg");
values.put("dataProvider", "bloomberg");
values.put("observationTime", "close");

this is the map. And i want to make the variables with values :
String dataSource="bloomberg";
String dataProvider="bloomberg";
String observationTime="close";

How it is possible in java?

A: Java doesn't support dynamic variable names. All the variables have to be present at compile time (this means that only the containers would be made at compile time) and at runtime, values are simply assigned and changed according to the logic of the program.
A few languages support creating variables with dynamic names, but it is not possible in Java

A: Try this
String dataSourceKey = "dataSource";
String dataSourceValue = "bloomberg";
values.put(dataSourceKey, dataSourceValue);

Now, when reading the values from the map
String dataSource = values.get(dataSourceKey);

Hope this helps


text:
Q: java.lang.IndexOutOfBoundsException for ArrayList I get an java.lang.IndexOutOfBoundsException for this code.
private List<Integer> LoeschenX = new ArrayList<Integer>();
private List<Integer> LoeschenY = new ArrayList<Integer>();

for (int i : LoeschenY) LoeschenX.add(LoeschenY.get(i));

A: When you do
for (int i : LoeschenY)

you are looping over the elements of LoeschenY, not on indexes. You may want to iterate over indexes so you can use get(i):
for (int i = 0; i < LoeschenY.size(); i++)
    LoeschenX.add(LoeschenY.get(i));

Remember that get(index) will return the value in an specific index.
Edit: You can also try
for (int i : LoeschenY)
    LoeschenX.add(i);

since i takes the values of the elements of LoeschenY, you will add these values to LoeschenX.

A: You seem to be iterating over the elements in the Y array, but the get method actually uses the element as an index the way you're doing it.
Try
for(int i : LoeschenY)
    LoeschenX.add(i);

Or
for(int i = 0; i < LoeschenY.size(); i++)
    LoeschenX.add(LoeschenY.get(i));


text:
Q: Looping over attributes of model instance I have an instance people = Person.all and would like to loop over it to get the first_name attribute for each person. I have tried the following:
people.each do |first_name|
  puts #{first_name}
end

How to construct the loop as to output all of the First Names?

A: Redo your code so it looks like this:
people.each do |person|
  puts person.first_name
end

In this code, person is the name of the individual object you are looping over. So calling person.first_name will call the first_name of that individual.

A: people = Person.all
puts people.map(&:name).join(' ')

A: What if, instead of looping, we fetch all the first names in one query?
puts Person.pluck(:first_name).join("\n")

If it needs to be an array of people, this would work too
puts people.map(&:first_name).join("\n")


text:
Q: Which constructor is called here, move or copy? In the code below, which constructor will be called, the move constructor or copy constructor?
#include <iostream>
using namespace std;

void called(std::string value)
{
    cout << "Value is " << value << endl;
}

int main()
{
    called("I am good");
}

A: A std::string is constructed from your const char[], therefore we then have a temporary. This will then be moved from or the constructor call will be elided altogether before C++17. As of C++17, elision is guaranteed and no move or copy constructor will be called. See: description on cppreference.com


text:
Q: Google Data Studio report not refreshing from MySql I have experimented with connecting Google Data Studio to one of our Mysql servers (Amazon RDS) and created a couple of reports. Everything is working great except that the reports are not refreshing automatically. I have to do it manually by pressing the "refresh data" button on the report.
Have anyone else experienced similar issues?

A: Luckely, I've found the workaround solution:

*

*Install a plugin Data Studio Auto Refresh

*Configure plugin on regular update (e.g. each 5 min)

*Open Datastudio report in the background

*After each 5 min - connections will be automatically refreshed.

*Hooray! Use up-to-date reports.

P.S. IN GDS tracker - opened bug to resolve autoupdate issue without any timelines :(


text:
Q: How does the following code actually work? I am currently working on a rather simple Windows Form that lets me type in information such as name and number into text fields and then add that to a list view. The information is entered in another Form and I had some issues figuring out how to access the listView in Form1 from Form2.
I found the following code to work just fine
Form1:
private void button1_Click(object sender, System.EventArgs e)
{
     Form2._Form1 = this;
     Form2 form2 = new Form2();
     form2.Show();
}

Form2:
    public static Form1 _Form1;

Now, I simply wonder 2 things. What does this actually do? and do I HAVE to use static?
Sorry if this is a very vague question, just wanna know what I'm actually doing.

A:
What does this actually do?

It sets the static field (shared by all instances of Form2) to the form1 instance. Then creates a Form2 instance and shows it.

do I HAVE to use static?

No - you would only use static if all instances of Form2 should share the same reference back to the same Form1.
Since that's most likely not necessary, I think an instance field and a constructor parameter (to ensure that the field is set) is more appropriate:
private Form1 _Form1;
public Form2(Form1 form1)
{
   this._Form1 = form1;
}

Then in your click event handler:
private void button1_Click(object sender, System.EventArgs e)
{
     Form2 form2 = new Form2(this);
     form2.Show();
}

I would also encourage more descriptive form/field names as well :)


text:
Q: How to pass a field bigger than 2000 characters from a SuiteScript script to a Suitelet script in Netsuite I have coded a suiteScript (V1.0) form that loads a sublist. I check some lines in this sublist and I need to create a file with this line and another information and save it into the the file cabinet.
I was thinking create the field and populate the data with SuiteScript functions and pass the info by POST to the Suitelet script but I don't know how to.

A: Do you mean a Suitelet with a sublist?
If so,if the list is editable, you can get the sublist values through NetSuite api (request.getLineItemValue) on the POST action, you don't have to send it manually.


text:
Q: How do I convert 'llvm::BasicBlock' to 'pred_iterator'? I am trying to get all the predecessor basic blocks  from an IR file not during a pass. I can iterate over all the basic blocks using
for (auto iter1 = m->getFunctionList().begin();
     iter1 != m->getFunctionList().end();
     iter1++)
{
  for (auto iter2 = f.getBasicBlockList().begin();
       iter2 != f.getBasicBlockList().end();
       iter2++)
  {
    BasicBlock &bb = *iter2;

    std::cout << "    BasicBlock: " << bb.getName().str() << std::endl;
  }
}

However, when I add for (BasicBlock *Pred : pred_iterator(bb)) {} from this link, I get an error
for (auto iter1 = m->getFunctionList().begin();
     iter1 != m->getFunctionList().end();
     iter1++)
{
  for (auto iter2 = f.getBasicBlockList().begin();
       iter2 != f.getBasicBlockList().end();
       iter2++)
  {
    BasicBlock &bb = *iter2;

    std::cout << "    BasicBlock: " << bb.getName().str() << std::endl;
    for (BasicBlock *Pred : pred_iterator(bb)) {}
  }
}

The errors are shown below
test2.cpp:63:37: error: no matching conversion for functional-style cast from 'llvm::BasicBlock' to 'pred_iterator' (aka 'PredIterator<llvm::BasicBlock, user_iterator_impl<llvm::User> >')
        for (BasicBlock *Pred : pred_iterator(bb)) {
                                ^~~~~~~~~~~~~~~~

Here is some additional Information:
/usr/local/include/llvm/IR/CFG.h:48:19: note: candidate constructor not viable: no known conversion from 'llvm::BasicBlock' to 'llvm::BasicBlock *' for 1st argument; take the address of the
      argument with &
  explicit inline PredIterator(Ptr *bb) : It(bb->user_begin()) {
                  ^
Additional Informatino is below.
/usr/local/include/llvm/IR/CFG.h:30:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'llvm::BasicBlock' to 'const
      llvm::PredIterator<llvm::BasicBlock, llvm::Value::user_iterator_impl<llvm::User> >' for 1st argument
class PredIterator : public std::iterator<std::forward_iterator_tag,
      ^
/usr/local/include/llvm/IR/CFG.h:30:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'llvm::BasicBlock' to
      'llvm::PredIterator<llvm::BasicBlock, llvm::Value::user_iterator_impl<llvm::User> >' for 1st argument
/usr/local/include/llvm/IR/CFG.h:47:3: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
  PredIterator() {}
  ^
/usr/local/include/llvm/IR/CFG.h:51:10: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
  inline PredIterator(Ptr *bb, bool) : It(bb->user_end()) {}

How do I convert from 'llvm::BasicBlock' to a 'pred_iterator'?

A: As shown in the error message you posted, pred_iterator constructor takes BasicBlock*, not BasicBlock&.
The other problem with your example is that in order to iterate with a range-based loop, you need a range, not an iterator. You should use a helper called llvm::predecessors for that.
Fixing these errors, we arrive at the following:
for (BasicBlock *Pred : predecessors(&bb)) {}