text:
Q: Get information from database When I click on artikle It needs to diretct me to page.php where I display whole article.
Problem is im not sure how to with $_GET superglobal var properly take information. I have to get ID with $_GET.
I already have included database in my index.php where I displayed several articles.
Im sending id like this:
 echo '';

//article.php
    <?php
 $servername = "localhost:3306";
 $user = "root";
 $pass = "";
 $dbo = "projekt";

// Create connection
$conn = new mysqli($servername, $user, $pass, $dbo);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM projekt";

if ($conn->query($sql)===TRUE) {
  $specID=$conn->insert_id;

        echo "id: " . $row["id"]. " - Name: " .
 $row["kategorija"]. " " . $row["naslov"]. "
";

    } else {
  echo "0 results";
}
$conn->close();
?>

A: $row_id = $row['id'];
echo 'some text';

        <?php
     $servername = "localhost:3306";
     $user = "root";
     $pass = "";
     $dbo = "projekt";

    // Create connection
    $conn = new mysqli($servername, $user, $pass, $dbo);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

      $id = isset($_GET['id']) ? (int)$_GET['id'] : '';

    $sql = "SELECT * FROM projekt WHERE id = $id";

    if ($conn->query($sql)===TRUE) {
      $specID=$conn->insert_id;

            echo "id: " . $row["id"]. " - Name: " .
     $row["kategorija"]. " " . $row["naslov"]. "
";

        } else {
      echo "0 results";
    }
    $conn->close();


text:
Q: join table1 col1 alias to table2 col2 alias Is there a way I can join on two tables like so:
.....
FROM table.col c
LEFT JOIN table1.col1 c1
ON c1.id = c2.id
LEFT JOIN table3.col2 c2 ON c1.id = c2.id

I tried this and does not work.
Wrote it wrong. Corrected main sql to show what I am trying to do. It says c2.id is not recognized in for this part ON c1.id = c2.id

A: For joining, you need to give table references, not column references.
The columns are part of the join condition.
See also the documentation: https://www.postgresql.org/docs/current/tutorial-join.html
According to your example for joining on 2 columns, you could do something like
SELECT ...
FROM table1
JOIN table2
  ON table1.col1 = table2.col1
  AND table2.col2 = table2.col2

redpajama_set_name: RedPajamaStackExchange


text:
Q: No 'Access-Control-Allow-Origin' header is present on the requeste - BUG: Access to XMLHttpRequest at 'https://*.execute-api.*.amazonaws.com/api' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requeste

*

*I have implemented Enable CORS on AWS API GATEWAY.

*At the Backend we use chalice (Python), each API returns the body as follows:

Response(
            status_code=200,
            body={
                'name_pharmacy': data['name'],
                'pharmacy_id': data['id']
            },
            headers={
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST, PUT, GET, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
            }
        )

However we can't get past the CORS . error

A: To avoid CORS errors, you should proxy the calls so that the application always calls itself, then the proxy takes care of redirecting the calls.
So, first we create the proxy.conf.json.
touch proxy.conf.json`
Inside it we put an initial configuration, e.g:
{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

In the package.json we modify the start command:
"start": "ng serve --proxy-config proxy.conf.json"
Restart the application and we're there!
here you can read about the proxy.
Enjoy!


text:
Q: Utilizando setContentView em métodos estáticos Estou criando uma aplicação com utilização do Bluetooth, onde o método que recebe as mensagens é static.
Dependendo da mensagem que o dispositivo receber, gostaria que a aplicação realizasse algo além de simplesmente mostrar a mensagem num textView (também static) na tela, como por exemplo chamar uma outra tela (setContentView), criar uma Intent qualquer ou apresentar um AlertDialog.Builder.
O problema se dá quando um método static tenta utilizar-se desses recursos. Tentei através desse método static criar um objeto da classe ActivityMain para utilizar um outro método qualquer que realizasse esse processo, entretanto, também ocorre erros.
O que fazer?


text:
Q: Error Changing Value (Excel to CI PeopleSoft CMS) In the PeopleSoft Campus Solutions module, I am using the ADM_APPL_ENTRY1 Component Interface (CI) to fire some data.
The user account I am using is a clone of the PS user (i.e. full permissions). I tried with both my clone account and the actual PS account but it returns the same error {ADM_APPL_ENTRY1.ADM_APPL_PROG.ACAD_PROG}(91,34).
I double-checked security and found all permission lists and progr security are the same for my user. Can anyone help?

A: Looks like you need to set the row security for your user (which is not copied when you copy the PS).
If you want to, you can manually copy PS row level security on your user on:
Define SACR> Security > Secure Student Administration>Setup>User Security Replacement.
Enter your user on the search page, and enter PS on the page itself.


text:
Q: Center align images in ListView (Compact Framework) I am working on a mobile application where the main menu is created by a ListView. I have the following as my screen now:

I am trying to align the icons in a better way. What I need is to align the icons to the center (both horizontal and vertical)! I am looking for something like this:

I am not able to find any property or methods that can help me achieve this. Any idea how to do it on Compact framework? I am using CF 3.5 and C# to build the application.
Any idea or solution highly appreciated!

A: As far as I know that's not possible with the ListView.
The fastest way is probably to drop a bunch of PictureBoxes on your form, and implementing the Click-event. A more reusable way is to create a custom control and build your own version.
There is also the option of paying for a third party library of controls. If that's your preference then that question has been asked here before: 3rd Party UI components for .net Compact Framework?


text:
Q: How can I write to Gradle logging while processing annotations? I have a javax.annotation.processing.Processor I'm using to generate source files. This is all working fine, but I want to write some debug messaging out to the console during build. I can use the annotation Messeger class, but this does not allow me to tap into the Gradle logging. What I'd like is to control the output by Gradle logging options, so gradle -d ... writes debug messages, gradle -i ... info messages etc.
Is there any way I can get hold of the Gradle logger from within my Java bean processing class?
I've read the Gradle logging doco, and have tried using SLF4J logging but this just writes my messages to stdout, which is picked up as QUIET by Gradle:
private static final Logger log = LoggerFactory.getLogger("org.gradle.example");

messeger.printMessage(Diagnostic.Kind.NOTE, "BeanProcessor: processing " + classElem);
log.debug("===debug=== BeanProcessor: processClass {}", classElem);
log.error("===error=== BeanProcessor: processClass {}", classElem);

21:28:22.211 [QUIET] [system.out] 21:28:22.208 [main] DEBUG com.example.beans.BeanProcessor - ===debug=== BeanProcessor: processClass com.example.beans.MyBean
21:28:22.212 [QUIET] [system.out] 21:28:22.212 [main] ERROR com.example.beans.BeanProcessor - ===error=== BeanProcessor: processClass com.example.beans.MyBean
21:28:22.216 [ERROR] [system.err] Note: BeanProcessor: processing com.example.beans.MyBean

Also, the logger I get is a ch.qos.logback.classic.Logger - the Gradle doco mentions: "Logger ... extends the SLF4J Logger interface and adds a few Gradle specific methods", so I would expect to see some Gradle specific logging class.
Gradle configuration is the as per Annotation processor in Gradle outputs source files to build/classes making javadoc fail. How to fix it?
Thanks,

A: A hack that could possibly help:
You could make a new custom gradle task that all compile tasks depend on and which sets a system environment variable based on whether -i, -d, etc. was passed to gradle (perhaps reading the value of logging.captureStandardOutput will do the trick).
Then read that environment variable in the startup of your annotation processor and use it to conditionally write to standard out.


text:
Q: Accessing struct member through unique_ptr gives segmentation fault This is how I set pointer to struct. At runtime segmentation fault is thrown at second line. LoadedPDFInfo is struct in Canvas namespace
struct std::unique_ptr<Canvas::LoadedPDFInfo> pdfInfo;
pdfInfo->handle = ++currentPDFHandle;
pdfInfo->totalPageNum = FPDF_GetPageCount(doc);

A: First, std::unique_ptr is a class not a struct, so get rid of the struct prefix on the pdfInfo variable declaration.  You were probably thinking of this instead:
std::unique_ptr<struct Canvas::LoadedPDFInfo> pdfInfo;

But even when declaring variables (or type-casting) using actual struct types, you still do not need the struct prefix.  C needs that, C++ does not.
Second, your segfault is happening because you have merely declared the pdfInfo variable, but it is not actually pointing at a valid LoadedPDFInfo object, so using the -> operator is not a valid operation.  Just like a regular pointer, std::unique_ptr (and std::auto_ptr, and std::shared_ptr) have to point at something in order to access that something's members.  For example:
std::unique_ptr<Canvas::LoadedPDFInfo> pdfInfo(new Canvas::LoadedPDFInfo);


text:
Q: How to get  as an array out of database? I just try to get my own user management tool, so first of all I just want to display all users by using a table. Then I want to allow to change the roles of the  users by using <select> tags. My problem is that I want to get the current role of every user pre-selected and I want to have the possibility to change by getting an array of the possible roles by searching database. But how is this possible? Here you can see my code:
<?php

header('Content-Type: text/html; charset=UTF-8');
include("db.php"); //just the database connection
session_start();
?>

        <title></title>

<?php
    $abfrage= mysql_query("SELECT * FROM user ORDER BY Name desc");
    //$ergebnis = mysql_query($abfrage) or die( mysql_error() );
    echo "
";
    echo"
Mitglieder

";
    echo"
";
    echo "Name
          Prename
          Role	";

    while($row = mysql_fetch_object($abfrage)) {

        echo "
";
        echo "",$row->Name,"	";
        echo "",$row->Prename,"	";
        echo "<select><option value=",$row->Role,">",$row->Role,"</option></select>	";
        //Here is the Problem

        echo "
";
    }
    echo "
";
?>

It displays the table with the users and their role from database correctly. Bur I need to get the other roles selectable.
I hope someone can help me.

A: EDIT - ADD SQL QUERY:
$available_roles = [];
$available_roles_query = mysql_query("SELECT * FROM roles");

while($role = mysql_fetch_object($available_roles_query)){

    $available_roles[] = $role->Name;
}

ORIGINAL POST:
while($row = mysql_fetch_object($abfrage)): ?>

       <?php echo $row->Name; ?>
       <?php echo $row->Prename; ?>

           <select>
               <option value="none">Please Select:</option>
               <?php foreach($available_roles as $role): ?>
                   <?php if($row->Role == $role): ?>
                      <option value="<?php echo $role; ?>" selected="true"><?php echo $role; ?></option>
                   <?php else: ?>
                       <option value="<?php echo $role; ?>"><?php echo $role; ?></option>
                   <?php endif; ?>
               <?php endforeach; ?>
           </select>

<?php endwhile;

Anything you don't understand, let me know. I'm too tired to write out explanations for the most probable issues you might have.
P.S. This won't allow you to update values. You'll need to add that functionality yourself, and when you do I'd recommend using different keys for each role than its name.

A: 1.you need get all roles as array
$roles = ['admin', 'user', .....]; // or you can get roles from database

2.loop the roles
$options = "<option value=".$row->Role.">".$row->Role."</option>";
foreach( $roles as $role ){
    $options .= "<option value={$role}>{$role}</option>";
}
echo "<select>{$options}</select>	";


text:
Q: Rounding in sql server 2008 R2 I have this query
(case when a.item_no >= '77000' and a.item_no <='77099' then
    (op_drill + op_machine + op_ssd + op_freight + op_paint + ((actual_tooling * 1.2)))
    else (op_drill + op_machine + op_ssd + ((op_drill + op_machine + op_ssd) *.27) + ((op_drill + op_machine + op_ssd + op_freight + (op_curforg *1.25) + ((op_drill + op_machine + op_ssd)*.27)) * .075)+
     op_freight + (op_curforg *1.25) + op_paint)
      end)  as new_cost,

it returns 10.1201575
In vb.net I can run this statement
 dblNewCost = Math.Round(dblNewCost, 2, MidpointRounding.AwayFromZero)

which returns 10.13
Is there a way to duplicate this is sql server.  I tried round(num,2) but that didn't showup correctly

A: I think you have some other issue. SQL Servers ROUND() function works just like VB's. There is no way using Math.Round(10.1201575, 2, MidpointRounding.AwayFromZero) would return 10.13.  Compare the number that is being rounded on both side to make sure you are comparing apples-to-apples.


text:
Q: Automatically Generate Attribute Table in Qgis I am working with historical parcel data in Qgis and have the following fields in my attribute table, (name, grantee date, grantor date, parcel ID, acreage, previous owner). Unfortunately, I have around 10-15 already created parcels that does not have these fields in the table. Is there an easy way to have those fields automatically generated in those attribute tables or will I have to manually enter them?

A: if the values are same, you can enter them directly through field calculator.


text:
Q: How do I Create a Vertical Arrow with Text Annotation with Dynamic Text Positioning in Konva? I'm trying to draw some geometric shapes in the user interface via Konva and react-konva. One basic element is a vertical arrow with annotated text to show the dimension of a shape, as shown below:

It's created by the following code snippet, which was my first attempt at implementing it.
import {Stage, Layer, Group, Rect, Arrow, Text} from 'react-konva';

function AnnotatedVerticalArrow({x, y0, y1, text})
{
  return (
    <Group>
      <Arrow
        points={[x, y0, x, y1]}
        pointerAtBeginning={true}
        pointerAtEnding={true}
        fill="black"
        stroke="black"
      />
      <Text
        x={x - 35}
        y={(y1 - y0) / 2}
        text={text}
        fontSize={12}
      />
    </Group>
  )
}

function App() {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <AnnotatedVerticalArrow
          x={50}
          y0={0}
          y1={100}
          text="2.54"
        />
      </Layer>
    </Stage>
  );
}

export default App;

However, I don't know how to correctly position the text, and this implementation has several problems:

*

*The text label is not centered properly, as the origin of the text label is not the center of the text, but at the corner. In order to find its center, the dimension of the text is required.

*The spacing between the arrow and the text label is hardcoded for a font with size 12. Changing font size, using shorter text, or using longer text breaks the user interface due to excessive or insufficient spacing.
How do I calculate the size of a Text and use its dimension during rendering?
I've seen an extensive discussion about text size calculation at GitHub repository konvajs/react-konva, the suggested solution is calculating the size in componentDidMount(), then using the size to change the state of the element and force a rerender. But the example code needs an update since it's written for React classes, not React hooks. The example is also unclear about how to calculate the dimension with different font sizes. Another proposed using measureText, but one commenter claimed the result was buggy. Yet another developer suggested an extremely complicated workaround, how it works is not obvious.

A: I've found the answer by combining the answer to the question How to get a react component's size (height/width) before render? and the example code in GitHub repo konvajs/react-konva's Issue #6.
The solution is to:

*

*Represent the calculated size of the text as a state, calculatedTextSize via useState(), initialize the default values to 0.

*Create a reference to the Text as textRef via useRef().

*Set the property ref of the Text we're returning to textRef, so this component is associated with the reference and becomes accessible in code.

*Calculate the size of the Text by accessing calculatedTextSize.width and calculatedTextSize.height, as if it's already calculated.

*Perform the size calculation in React.useLayoutEffect() callback. This function is executed when the first render pass is completed. Within the function, call the measureSize() method of the Text to obtain the result, then pass the result by changing the state via setCalculatedTextSize().

*...which triggers a re-render, so the new size is used.

The new implementation of AnnotatedVerticalArrow() is:
import React from 'react';
import {Stage, Layer, Group, Rect, Arrow, Text} from 'react-konva';

function AnnotatedVerticalArrow({x, y0, y1, text})
{
  const textRef = React.useRef();
  const [calculatedTextSize, setCalculatedTextSize] =
    React.useState({width: 0, height: 0});

  React.useLayoutEffect(() => {
    if (textRef.current) {
      setCalculatedTextSize({
        width: textRef.current.measureSize(text).width,
        height: textRef.current.measureSize(text).height
      });
    }
  }, []);

  return (
    <Group>
      <Arrow
        points={[x, y0, x, y1]}
        pointerAtBeginning={true}
        pointerAtEnding={true}
        fill="black"
        stroke="black"
      />
      <Text
        ref={textRef}
        x={x - calculatedTextSize.width * 1.1}
        y={(y1 - y0) / 2 - calculatedTextSize.height / 2}
        text={text}
        fontSize={12}
      />
    </Group>
  )
}

It remains working even if fontSize has been changed, since textRef is always a reference to the Text component that we've created in the rendering code path.


text:
Q: Extender controls may not be registered after PreRender. Occurs on GridView DataBind() On our ASP.Net 4.0 C# web app I get the error above in the subject line during debug.
I'm not really doing anything funky with dynamic controls on the page as some search results indicated could have been the source of the problem.
The page has 2 ajax:CalendarExtenders and has been working fine for a while.
Although its probably related, I can see how really but this is what I was currently working on when the error came up.
We have a control on the page that raises an event on an autorefresh feature. [Its a map control].
My page subscribes to that event and upon doing so DataBinds an asp:GridView. We need to bind the data in the grid every time to ensure the grid and the map control are in sync. [Its a vehicle tracking page]
The error occurs on the DataBind command.
I have removed the Extenders only to come up with the same error.
The databind is straightforward but I'm sure the error resides elsewhere. I'll include it anyway.
this.SearchGrid.DataSource = resultsWithMetrics;

        this.SearchGrid.AllowPaging = true;
        this.SearchGrid.PageIndex = this.SearchGridPager.CurrentPage;
        this.SearchGrid.AllowPaging = this.SearchGridPager.PageSize > 0;
        this.SearchGrid.PageSize = this.SearchGridPager.PageSize > 0 ? this.SearchGridPager.PageSize : this.SearchGrid.PageSize;

        this.SearchGrid.DataBind();

Maybe its simply not understanding the page life cycle that has tripped me up, anyway would be glad of some help.

A: Use the following code in your usercontrol or  page control. It will work if you are using any ajax control.
protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (this.DesignMode == true)
        {
            this.EnsureChildControls();
        }
        this.Page.RegisterRequiresControlState(this);
    }

A: The issue was that on row databind the extender controls were added to each row and it was these extenders that caused the issue.
The event that triggered the the rebind came from a user control that used callbacks to communicate to the server and subsequently raise the event which probably arrived too late anyway in the page lifecycle.
Without fully understanding what was going on it all smelt a bit dodgy and I have changed the structure of the app a bit.


text:
Q: The path to the driver executable must be set by the webdriver.chrome.driver system property; However my path is correct java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; However my path is correct.
if (browser.equalsIgnoreCase("chrome") && OS == "Mac") {

        System.out.println("==============================================" );
        System.out.println("OS Detected : MAC , Browser Launched : Chrome" );
        System.out.println("==============================================" );

        System.setProperty("Webdriver.chrome.driver", "./lib/chromedriver");

        Boolean headlesschrome = false;

        if (headlesschrome==true) {

            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--headless");
            chromeOptions.addArguments("--start-maximized");
            chromeOptions.addArguments("--window-size=1200,800");
            dvr = new ChromeDriver(chromeOptions);
            //dvr.manage().window().fullscreen();

        }else if (headlesschrome==false)

        {
            dvr = new ChromeDriver();
            dvr.manage().window().fullscreen();
        }

    }

A: W letter in this line:
System.setProperty("Webdriver.chrome.driver", "./lib/chromedriver");

It's should:
System.setProperty("webdriver.chrome.driver", "./lib/chromedriver");

Make sure it's not uppercase

A: Please check your chrome driver version , you should use right chrome driver version according chrome browser version
https://chromedriver.chromium.org you can download version of chrome driver from this site


text:
Q: Proving the series doesn't converge: $\sum_{n=1}^{\infty}a_n$, $\lim_{n\to\infty}na_n=\infty$, $a_1=-1$
Let $\displaystyle\sum_{n=1}^{\infty}a_n$ and $\displaystyle\lim_{n\to\infty}na_n=\infty$ and $a_1=-1$. Prove the series does not converge.

From the given that $a_1=-1$ we know that there has to be at least one more negative element because the limit is positive infinity. I don't know how to use that though.
Trying something else, after applying the condensation test, we get: $2^na_{2^n}$
Obviously: $na_n<2^na_{2^n}$ so from direct comparison the original series diverges.
It's strange that I didn't use the given $a_1=-1$. Is there another way that does use this given?

A: Since $\lim na_n$ is $+\infty$, given $L>0$, there exists an index $n_0$ such that from $n \geq n_0$ we have $na_n >L$. For $L=1$ you get that from a point on we have $a_n > 1/n$. Comparing $\sum a_n$ with the harmonic series gives you the result.
The hypothesis on $a_1$ is irrelevant, since the next terms do not depend on $a_1$, and the convergence of a series is independent of the first terms.

A: Let $b_n=\frac{1}{n}$ and since $\lim_{n\to \infty} \frac{a_n}{b_n}=\infty$ and $\sum_n b_n $ diverges then $\sum_n a_n$ also diverges by the comparison test.


text:
Q: Replace fullpage image background with video (HTML5) What is the easiest way to replace a full-page image background, with a video?

video {
  position: fixed;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -100;
  transform: translateX(-50%) translateY(-50%);
  background: url('#.jpg') no-repeat;
  background-size: cover;
  transition: 1s opacity;
}
<video poster="#.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="#.mp4" type="video/mp4">
</video>

I use the Spectral template by HTML5 UP, but can't figure out how to replace the banner background with a video, in the easiest and most efficient way. (https://html5up.net/spectral)
Thank you very much in advance :-)

A: In the header you can delete or replace the header background color, in the CSS --> #header
If that's what you mean.
-moz-transition: background-color 0.2s ease;
-webkit-transition: background-color 0.2s ease;
-ms-transition: background-color 0.2s ease;
transition: background-color 0.2s ease;
//background: #2e3842; //delete or change this one
height: 3em;
left: 0;
line-height: 3em;
position: fixed;
top: 0;
width: 100%;
z-index: 10000;


text:
Q: Linux wireless: ACK implementation I have been studying the Linux wireless 802.11 driver, and this question popped up:
Assuming STA A transmits a normal data packet to STA B.
Based on the 802.11 standard, STA B will send an ACK if it successfully receives the packet from STA A. Meanwhile STA A will switch to receive state in order to receive the ACK from STA B.
My question is:
Where is the code that controls the switching from tx to rx for ACK reception at STA A?
Is it done by the hardware, or the driver?
Really appreciate it if anyone can enlighten me. Thank you!

A: Generally, ACK needs to be send in SIFS standard See (https://en.wikipedia.org/wiki/Short_Interframe_Space). The actual value of SIFS varies from protocol to protocol (eg., 802.11b its just 10uS similar can be seen in above shared link).
To technically one has to receive the packet and send ack in 10uS. Doing this in software is possible but its not encouraged because this hard time dependency. Hence generally 802.11 ACKs are generated by the hardware.

A: Found out the answer from some colleagues implementing 80211:
ACK is handled by hardware, similarly for some other lower-MAC related functions that has strict timing requirement.


text:
Q: Do we need the shutdown tag? There are 206 questions marked with shutdown.
These are related to killing servers, scripts or applets.
There doesn't seem to be a consensus around it, and other tags (plus the title in most cases) explain the situation anyway.

A: There may not be a consensus about what the tag is for, but that doesn't mean it's an inherently bad tag. It does provide some semantic information, and I can imagine people searching or categorizing questions using this tag. So I think we should keep it—or at least see little harm in keeping it around.
The best option if you want to clean things up is to go through the list of questions that have this tag (especially since it's a manageable number) and either re-tag the question to something more appropriate, remove the tag altogether, or note the most commonly-used cases or interpretations for the tag and add those to the tag wiki so that everyone knows what the tag is/should be used for.


text:
Q: Am I using Core Data properly by fetching an object once at startup and calling save when I want to persist the data? I'm diving into iOS programming and am using Core Data in my app to persist the game data, however, I'm wondering if my approach is the wrong way to use Core Data.  I have three tables in my DB, with the first two having a one-to-many relationship with the another table (i.e. UserProfile -->> Puzzle Packs -->> Puzzles).
The approach I'm taking to use and persist the data is simple, retrieve an instance of a UserProfile using a NSFetchedResultsController and store the UserProfile object as an instance var in my App Delegate.  Then I use that UserProfile object throughout the rest of the code to access and modify the state of the puzzle packs and puzzles (representing the user's progress in the game) and whenever I make a change to the objects, I just call the NSManagedObjectContext's save method to update the DB, which is is also stored in the App Delegate.
My question is, should I be fetching data from the DB anytime I need to access or modify it or is my current approach, of fetching the top object once and calling the save method often, the correct way to use Core Data?
Thanks in advance for your wisdom!  I apologize if my question is odd, I'm still a noob.

A: As long as you're only ever working with these objects with a single NSManagedObjectContext (ie, you never have to merge changes between contexts) then I don't see a problem with fetching once, and saving as needed.
That said, the moment you work with multiple contexts (for example, using NSOperation/NSOperationQueue or other multi-threading techniques, which require separate contexts), you'll want to make sure you merge changes and update other contexts so changes from one thread don't clobber something on another.


text:
Q: Where does the cofactor expression in the expansion of minors formula come from? So I know that the formula for the determinant of a matrix by expansion of minors is:
$$\sum_{c=1}^n a_{rc}a'_{rc}$$ is the expansion of minors by a row
and
$$\sum_{r=1}^n a_{rc}a'_{rc}$$ is the expansion of minors by a column.
In both expressions $a'_{rc} = (-1)^{r+c}\det(A)$ where r,c and A are respectively the row, column, and matrix $A$. I'm not sure how this expression for the cofactor is derived? Where does it come from? Is there a way to intuitively understand where it comes from?

A: It depends on what you consider to be the primary definition of determinant. If you define it with the Leibniz formula
$$ \det(A) = \sum_{\sigma \in S_n} \text{sgn}(\sigma) \prod_{i=1}^n a_{i,\sigma(i)}$$
where the sum is over all permutations of $[1,\ldots,n]$, then the minor
expansion over row $i$ is just picking out, for each element $a_{ij}$ in that row, the terms involving that element.


text:
Q: Magento emails are not sending, works only in one (store lang) scope Got strange problem, really. Option in System > System > Mail Sending Settings (Disable Email Communications) to No. I was not installing any plugins, no updates are done. I have Magento 1.8.
That is what i am getting in magento log.
exception 'Exception' with message 'This letter cannot be sent.' in /httpdocs/app/code/core/Mage/Core/Model/Email/Template.php:412
Stack trace:
#0 httpdocs/app/code/core/Mage/Core/Model/Email/Template.php(520): Mage_Core_Model_Email_Template->send(Array, Array, Array)
#1 /httpdocs/app/code/core/Mage/Core/Model/Email/Template/Mailer.php(79): Mage_Core_Model_Email_Template->sendTransactional('sales_email_ord...', 'general', Array, Array, Array, '2')
#2 /httpdocs/app/code/core/Mage/Sales/Model/Order.php(1329): Mage_Core_Model_Email_Template_Mailer->send()
#3 /httpdocs/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php(130): Mage_Sales_Model_Order->sendNewOrderEmail()
#4 /httpdocs/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Sales_OrderController->emailAction()
#5 /httpdocs/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('email')
#6 /httpdocs/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#7 /httpdocs/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#8 /httpdocs/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#9 /httpdocs/index.php(87): Mage::run('', 'store')
#10 {main}

Well it works only wheen i am on English site. Wheen i swich to other lang it does not work anymore, nor contact form or any other form. I have only two languages in my shop.

A: Okay so the answer is rather simple in the end, atleast in my case.
What you need to do is go to:

*

*app/locale/your_locale/template/email

*app/locale/your_locale/template/email/sales

and save all files as UTF-8 withot BOM


text:
Q: Spring Boot - Externalize Database Settings I have a JAVA project developed with Spring Boot.
The database settings are in the default resources/application.properties file.
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.driver-class-oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@//172.********:1521/BDHML
spring.datasource.username=********
spring.datasource.password=********

The application will run through the command:
java -jar **CONFIGURAÇÃO** app-cosolidar.jar

I need to put the database settings in a .properties file external to the project.
How can I do this?
What should the .properties file look like?
Should I change any .java files?
What setting should I put in java -jar?
Regards, Diego

A: You would be able to launch your spring boot application with the external properties file path as follows:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

A: You can provide command line arguments while running jar.
java -jar app.jar --spring.config.location=file://<path>/application.properties
You can also pass a folder location where the application will search for the files.
java -jar app.jar --spring.config.name=application,jdbc --spring.config.location=file://<path to config folder>
Refer this link for more understanding. https://www.baeldung.com/spring-properties-file-outside-jar


text:
Q: SyntaxError: Unexpected reserved word "await", node.js is correct version I am trying to run a function asynchronously 20 times.
I have the function definition:
import axios from 'axios';

async function updateUser (url, user) {
        return new Promise((resolve, reject) => {
            axios.put(url, JSON.stringify(user))
                .then(response => {
                //Folio returned code 204
                console.log('The user has been updated');
                resolve(response.data);
                }).catch((err) => {
                //Folio returned error
                console.error(`Error Text: ${err.response.data}`);
                console.error(`Error Code: ${err}`);
                });
        });
    };

  export {updateUser};

Then I am trying to loop through users in an external JSON, and update them to my system 20 at a time:
import {updateUser} from './updateUser.js';
import usersjson from './jsons/users.json';
let promises=[];
if (usersjson.users.length) {
    try {
        for (const user of usersjson.users) {
            update = new promise ((resolve,reject) => {
                updateUser(url, user)
                .then((list) => {resolve(list)})
                .catch((error)=>{reject(error)})
            });
            promises.push(update);
            if (promises.length = 20) {
                await Promise.all(promises)
                    .then((responses)=> {
                      console.log(responses);
                      promises=[];
                    }).catch((err)=> {
                      console.log(err);
                    });
            }
        }
    } catch(err)=> {
        console.log(err);
    }
}

However, I am getting an error message in the console:
await Promise.all(promises)
^^^^^

SyntaxError: Unexpected reserved word

My node version is 12.19.0 (based on previous questions, it seems it has to be at least 10, so that shouldn't be the issue).
When I run the function without await, they work correctly (i.e. the users are updated on my system).
It also seems that the for loop is asynchronous by itself, but I'm afraid that if there will be too many calls simultaneously my system will block the API, so I want to make 20-50 calls at a time, tops.

A: In order to use await you need to declare the function in which you are putting the await as async
For example:

const functionReturningPromise = (input) => {
  return new Promise((resolve, reject) => {
    if (!input) {
      return reject();
    }

    return resolve();
  });
}

const functionAwaitingPromise = async () => {
  for (let i = 0; i < 20; i +=1) {
    try {
      await functionReturningPromise(i);

      console.log(i);
    } catch (error) {
      console.log(error);
    }
  }
}


text:
Q: foreach loop to copy file into all directories in c:\users\ ... hopefully a simple one Aim: I need to copy and paste Teams backgrunds into all users profiles on lots of machines
Error: Path does not exist.
I can't figure out the issue why my path  C:\users\user1\Appdata turns into C:\Users1 Users2\Appdata
Here is the full code:
$Folders = Get-ChildItem -Directory "C:\Users"   | Where-Object {$_.Name -notlike "Public"}  | Where-Object {$_.Name -notlike "AppData"}
$Backgrounds = "\\Server1\Teams-Backgrounds\*"

Foreach($Folder in $Folders) {

Copy-Item -Path $Backgrounds -Destination "C:\Users\$($Folders.Name)\AppData\Roaming\Microsoft\Teams\Backgrounds\Uploads" -Force -ErrorAction Stop

}

A: This is what you are after.
# Combined the Where-Object filter into a single
$Folders = Get-ChildItem -Directory "C:\Users" | Where-Object {($_.Name -notlike "Public") -and ($_.Name -notlike "AppData")}
$Backgrounds = "\\Server1\Teams-Backgrounds\*"

Foreach($Folder in $Folders) {
    # Changed $Folders.Name to $Folder.Name
    Copy-Item -Path $Backgrounds -Destination "C:\Users\$($Folder.Name)\AppData\Roaming\Microsoft\Teams\Backgrounds\Uploads" -Force -ErrorAction Stop
}


text:
Q: Cant find debug toolbar in vs code using latest version of vs code, i cant see the debug toolbar.
Version: 1.66.2
i've tried changing it in the settings from floating to docked to hidden and back to floating, restarted the program and i still cant see it.

A: You should press this combination of key : CTRL+Shift+Y

A: I think ive sorted it. the toolbar only appears if debugging is in process. it disappears when it has stopped. I thought it stayed there all the time.

A: For whoever still struggles with the problem, the problem for me was that the "Run and Debug" menu was unchecked for some reason.
Right-click on the menu bar and check it.
Right Click on Menu bar


text:
Q: Remove empty lines in tab delimited file while preserving row labels I have a tab delimited file with column headers like ID, A, B, C, D as shown in the pic below, and row labels too like a, b, c, d, e show below in pic. How do I remove all the empty lines (rows) while preserving the row labels with non-empty rows? Example input and desired output is shown below. Thank you for any help!
Sample input:
ID  A  B  C  D
a      1     2
b
c   1        1
d
e   1

Desired output:
ID  A  B  C  D
a      1     2
c   1        1
e   1

[sample input and output transcribed from original image]

A: What I suggest:
$ awk 'NF>1' file
I   A   B   C   D
a       1       2
c   1           1
e   1

A: Using sed or grep
$ sed -En '/[^ \t]*[ \t]/p' input_file
ID  A  B  C  D
a      1     2
c   1        1
e   1

$ grep -E '[^ \t]*[ \t]' input_file
ID  A  B  C  D
a      1     2
c   1        1
e   1


text:
Q: Distributing a Combination of Identical and Distinct Objects in distinct boxes Q1. How many ways are there to distribute 4 distinct oranges and 6 distinct apples into 5 distinct boxes?
Approach 1: Let us assume the two tasks disjoint. So oranges go in $5^4$ ways and apples in $5^6$ ways. So total ways in which both tasks happen together is $5^4*5^6=5^{10}$
Approach 2: Assume there are together 10 distinct objects to be distributed. Answer is $5^{10}$
Q2. How many ways are there to distribute 4 identical oranges and 6 distinct apples into 5 distinct boxes?
Approach 1: The two tasks are disjoint. orange task can be done in $\binom{4+5-1}{4}$ Using Sticks and Stones for Counting number of Ways. apple task is as before. so total number of ways $=\binom{4+5-1}{4}*5^6$
Approach 2: But if i combine both tasks as in Q1, first assume that oranges are different then i have total number of ways is $5^4*5^6=5^{10}$. Now since oranges are identical, so total number of ways should be $5^{10}/4!$. This is not even a whole number.
So $\binom{4+5-1}{4}*5^6\neq 5^{10}/4!$
Why is approach 2 going wrong in Q2 and not Q1?

A: It is not always true that $4!$ ways of putting distinct oranges in correspond to one way of putting identical oranges in. This is only true if one orange was put into each of four boxes, but all four oranges may be put into one box, or two in one and two in another, and so on. The relevant divisor is not uniform across all cases.


text:
Q: How would I calculate points on the Peano curve? The Peano curve is often given as an example of a space filling curve which maps the unit line to the unit square. So, it is a function of the form $[0,1] \rightarrow [0,1]^2$? In which case can I evaluate it for given numbers like 0.2, 0.5 and 0.7? How would I calculate those points?

A: The approach I would take is to define the curve construction by a set of affine similarity transformations, each corresponding to a mapping from the unit square to part of the curve.  Write the length parameter fraction in base(number of transformations) to index a sequential compositions of transformations, and take the limit to find the corresponding point in the unit square.
Using the Hilbert curve as an example because it has fewer and simpler transformations (the same approach applies to the Peano curve with $9$ transformations):
$$
\begin{aligned}
f_0 \begin{pmatrix}x \\ y\end{pmatrix} &= \begin{pmatrix}0 & \frac{1}{2} \\ \frac{1}{2} & 0\end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} \\
f_1 \begin{pmatrix}x \\ y\end{pmatrix} &= \begin{pmatrix}\frac{1}{2} & 0\\ 0 & \frac{1}{2} \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} + \begin{pmatrix}0 \\ \frac{1}{2}\end{pmatrix}\\
f_2 \begin{pmatrix}x \\ y\end{pmatrix} &= \begin{pmatrix}\frac{1}{2} & 0\\ 0 & \frac{1}{2} \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} + \begin{pmatrix}\frac{1}{2} \\ \frac{1}{2}\end{pmatrix}\\
f_3 \begin{pmatrix}x \\ y\end{pmatrix} &= \begin{pmatrix}0 & -\frac{1}{2}\\ -\frac{1}{2} & 0 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} + \begin{pmatrix}1 \\ \frac{1}{2}\end{pmatrix}\\
\end{aligned}
$$
Weight the transformations equally across the length parameter, because each maps to the same area.  Now there are $4$ transformations, so write your parameter fraction in base $4$:
$$l = 0 . l_1 l_2 l_3 l_4 \ldots \text{ where } l_i \in \{0,1,2,3\}$$
which corresponds to a composition of transfomations:
$$f = f_{l_1} \circ f_{l_2} \circ f_{l_3} \circ f_{l_4} \circ \ldots$$
This infinite limit can be evaluated for rational length parameters using fixed point arguments, for example:
$$l = \frac{7}{12} = 0.2\overline{1}_4 \\ p_1 = f_1 (p_1) = \begin{pmatrix}0 \\ 1\end{pmatrix} \\ p = f_2 (p_1) = \begin{pmatrix}\frac{1}{2} \\ 1 \end{pmatrix}$$
For irrational length parameters, I don't know how to find the limit.


text:
Q: Is it possible to block a user?
Possible Duplicate:
Add the ability to ignore users

There is a user on SO that is young and act very immature, they take the whole point thing way to far and live on SO just to gain points.  Here lately I post some very well defined and legit questions about some concepts I am learning and trying to understand better and this person will go out of there way to post negative comments about me posting questions.  An example is last week I had a question in regards to performance of loading different kinds of files for settings, like ini, json, xml files and then today I posted a question in regards to the performance of accessing an array of setting once it is returned from one of these files and the kid is non stop complaining about me "posting the same question over and over again" when in reality the questions are completely non related to each other and just bashing me.  I have been very polite to him in my comments back and tonight someone down voted him so he starts bashing me that I down voted him and it's just getting really annoying as it is happening more and more often with this user.
So I am just asking, is there an option to block my post showing up to certain users?  If this is not an option I think it would be a really good idea!

A: With regards to your concerns, if you think a user is unfairly targeting you, then your best bet is to flag a comment that you think is inappropriate and let a moderator know why.
It's not a good idea to retaliate. It just weakens your case.
Caveat:
If you're posting questions that are quite broad or open ended (as performance questions necessarily are if you don't have a specific set of constraints in mind), then you're going to raise the ire of that part of the community that thinks you're just asking open-ended questions to gain reputation, instead of actually looking for an answer to a specific problem you have.
The community as a whole (well, the 'older members') tend to look down upon people who are using the reputation system as a game, instead of answering specific questions for specific problems.
Edit: After taking a look at your Stack Overflow profile, it does seem like you ask broad, open-ended question on a wide variety of topics, combine that with your ratio and that's a possible indicator of why this particular user targeted you.
I'm not saying it's right, but it is a plausible explanation.


text:
Q: Django Admin TabularInline Complaining About Missing Field I have the following model and TabularInline subclasses:
class SomeModel(models.Model):
    name = models.CharField(max_length=50)

class SomeModelInline(admin.TabularInline):
    model = SomeModel

class SomeOtherModelAdmin(admin.ModelAdmin):
    inlines = [SomeModelInline]

Without explicitly specifying the TabularInline's fields, Django's admin shows the fields "id" and "name". However, when I try and do:
class SomeModelInline(admin.TabularInline):
    model = SomeModel
    fields  ['id','name']

Django throws the ImproperlyConfigured exception:
'SomeModelInline.fields' refers to field 'id' that is missing from the form.

What's going on here? Why can't I explicitly specify the id, even though Django's clearly capable of accessing it?

A: Ids are non-editable, by default inline shows the editable fields, but you can show the non-editable fields as well
From django docs

fields can contain values defined in ModelAdmin.readonly_fields to be
  displayed as read-only.

So first add 'id' to readonly_fields, then add it to fields


text:
Q: How i can run faust workers and manage them I want to run faust workers from my code (run from signals). And i need manage workers (pause, kill, reload).
In the future, I would like to manage workers in docker containers. That is, 3 workers in one container, 2 in another ...
Or maybe there are ways to better run and manage workers?
I've already learned how to run them in a container, one per container manualy.
I need a daemon for a large number of workers, such as supervisor


text:
Q: macOS Catalina USB keyboard doesn't work after being taken out and in again After I upgraded to macOS Catalina on my MacBook Pro from 2013, my USB keyboard stops working every time I unplug it and plug it in again. Every time, I have to reboot with the keyboard plugged in to make it work again.
Is anybody else experiencing this issue and has a way to fix it because it is super annoying.
Info about my mac: MacBook Pro (Retina, 15-inch, Late 2013)

A: Reset NVRAM or PRAM on your Mac
Shut down your Mac, then turn it on and immediately press and hold these four keys together: Option, Command, P, and R. You can release the keys after about 20 seconds, during which your Mac might appear to restart.
Test after this.
If this doesn't help then at last try to:
Reset the SMC on Mac
First, shut down your Mac and Press Shift-Control-Option on the left side of the built-in keyboard, then press the power button at the same time. Hold these keys and the power button for 10 seconds. Release all keys. And, Press the power button again to turn on your Mac.
Start up in safe mode
Start or restart your Mac, then immediately press and hold the Shift key. The Apple logo appears on your display.
Release the Shift key when you see the login window. If your startup disk is encrypted with FileVault, you might be asked to log in twice: once to unlock the startup disk, and again to log in to the Finder.
To leave safe mode, restart your Mac without pressing any keys during startup.
This will release some kernel panic that might help to fix your issue too.

A: I just fixe my same issue. My issue would occur when my USB keyboard would stop working on my laptop after unplugging it and replugging it in while my computer was on. I would then have to reboot my computer all over again for it to work.
Restart or Start your computer in safe mode and then once you logged in try doing all the things with you keyboard that caused it not to work for yourself and if the issue goes away simply restart the computer without holding any keys and then the problem "should" go away. It worked for me and I am now able to unplug my keyboard and plug it back in and it works without having to restart everything.
Hope that helps. :)


text:
Q: Utilizing the click on point event I want to know how I could utilize the point click event on the Shield UI Chart?
What I need is to show a message to the user, consisting of the point's value and some text.

A: Below is the code that uses the event of a point being clicked on a Shield UI Chart:
   events: {
    pointSelect: function pointSelectHandler(args) {

    var Information= "Point Value: " + args.point.y;
    alert(Information);
    },

Don't forget to enable the point selection:
       enablePointSelection:true,


text:
Q: Retrieve All Employees from Kronos WFC SOAP Service I am writing an application to comunicate with Kronos WFC to get all employee list (active and inactive) including all data, labor level and personal information.
I tried this query:
<?xml version="1.0"?>
<Kronos_WFC version="1.0">
    <Request Object="System" Action="Logon" Username="User" Password="Pwd" />
    <Request Object="System" Action="Load">
        <PersonInformation>
            <Identity>
                <PersonIdentity>
                    <PersonNumber>*</PersonNumber>
                </PersonIdentity>
            </Identity>
        </PersonInformation>
    </Request>
    <Request Object='System' Action='Logoff'/>
</Kronos_WFC>

but it seems to reject '*' wildcard. Always the response is failed, so, if i send any person number request retrieve whole person information only for that person number, not all employee list, anyone can help me?

A: The best approach is to query the view 'VP_ALLPERSONV42', this view comes by default on kronos install bundle, you must contact your DBA to get a "read only" access to the 'VP_ALLPERSONV42' view.
Keep in mind: Kronos labor levels are abstract, so you must analyze the view structure to determine which fields you are looking for and make the right level projection.
Hope it helps!


text:
Q: Drag and drop элементов списка Хочу сделать перетягивания выбранного элемента списка по клику. Но возникает проблема, что бы перетянуть элемент нужно кликнуть два раза на него. А также нужно что бы при клике на элемент создавалась его копия, так как один элемент может использоваться несколько раз.
    document.querySelector('#drag-training_1').addEventListener('click', function(e){
    var id = e.target.id;
    var el = document.getElementById(id);
    var element = el;

    element.onmousedown = function(e) {
        element.style.position = 'absolute';
        element.style.cursor = 'pointer';
        moveAt(e);
        document.body.appendChild(element);
        element.style.zIndex = 1000;

        document.onmousemove = function(e) {
            moveAt(e);
        }

        element.onmouseup = function() {
            document.onmousemove = null;
            element.onmouseup = null;
        }

        element.ondragstart = function() {
            return true;
        };

        function moveAt(e) {
            element.style.left = e.pageX - element.offsetWidth / 2 + 'px';
            element.style.top = e.pageY - element.offsetHeight / 2 + 'px';
        }
    }

});

Подробнее можно увидеть jsfiddle

A: Там чуть иначе следовало бы сделать. В частности, не нужно вкладывать всю привязку событий непосредственно в onmousedown. А чтобы клонировать элемент, можно использовать метод cloneNode. У меня получилось что-то такое:
var drags = document.querySelectorAll('.drag-element > *'),
    moveAt = function(element, e) {
        element.style.left = e.pageX - element.offsetWidth / 2 + 'px';
        element.style.top = e.pageY - element.offsetHeight / 2 + 'px';
    };

for (var i = drags.length; i-- ;) {
    var drag = drags[i],
        element;

    drag.addEventListener('mousedown', function(e) {
        element = this.cloneNode(true);
        element.style.position = 'absolute';
        element.style.zIndex = 1000;
        moveAt(element, e);
        document.body.appendChild(element);
    }, false);

    document.addEventListener('mousemove', function(e) {
        element && moveAt(element, e);
    }, false);

    document.addEventListener('mouseup', function() {
        // здесь следует произвести какое-нибудь действие с `element`
        // чтобы не оставлять элемент где попало
        element = null;
    }, false);
}

ДЕМО: http://jsfiddle.net/Lk31z2q2/5/


text:
Q: How to create a program combining both Parser and Lexer I want to build a compiler using Ocamllex/Ocamlyacc and I want to create a main program to combine both of my OcamlParser and OcamlLexer. The thing is that I know how to do it using an input in the command line like the following code:
let _ =
  try
    let lexbuf = Lexing.from_channel stdin in
    while true do
      let result = Parser.main Lexer.token lexbuf in
      print_int result; print_newline(); flush stdout
    done
  with Lexer.Eof ->
    exit 0

But how can I do if I want to use a file as an input; I tried something like this:
let file ="add.txt"
    let _ =
     let ic = open_in file in
      try
        let lexbuf = Lexing.from_channel file in
        while true do
          let result = Parser.main Lexer.token lexbuf in
          print_int result; print_newline(); flush stdout
        done
      with Lexer.Eof ->
        exit 0

But it's not really working.

A: The following code works for me. In your version, you have some syntax errors.
let _ =
      let file ="add.txt" in
      let i = open_in file in
      try
        let lexbuf = Lexing.from_channel i in
        while true do
          let result = Parser.main Lexer.token lexbuf in
          print_int result; print_newline(); flush stdout
        done
      with Lexer.Eof ->
        exit 0

Putting 1+2 in "add.txt" gives me 3.


text:
Q: sproutcore change image or icon and repaint I want to change the icon/image in the statechart.js, that is display and hide it a number of times. I tried a icon to a label and a extra childview. Question: How to hide/change the icon/childview programmatically?
With the extra childview I was abled to change the value, but this change is not visible on the screen.
    SC.LabelView.design icon: 'icon-heart',
    ..
    heart: SC.ImageView.extend({
                classNames: ['icon-heart'],
                  value: 'heart.png'
                }),

MyApp.mainPage.getPath('mainPane.navigationView.heart').value = 'icon-next';

A: SproutCore uses the observer pattern to know when values have changed. In order for this to work, SproutCore requires that you use the set() and get() methods so that it will see the change and can update the display accordingly.
Try changing your last line to:
MyApp.mainPage.getPath('mainPane.navigationView.heart').set('value', 'icon-next');

Also, you should definitely look at using Bindings to easily bind the value to a controller (or even a plain SC.Object for something this simple) and have your view watch for changes there. Quick example:
myApp.myController = SC.Object.extend({
  iconValue: 'icon-heart'
})

myApp.myView = SC.ImageView.extend({
  valueBinding: SC.Binding.oneWay('myApp.myController.iconValue')
})

Now, later on, you can do the following from within your statechart:
myApp.myController.set('iconValue', 'icon-next');

and the view should automatically update.
Please post a comment if you run into issues and I'll do my best to help.


text:
Q: How to use Bootstrap for Responsive Web Design? I'm new to the web designing and Bootstrap. I want to make my web page(React app) responsive as I'm using bootstrap for my frontend. Do it require for a beginner like me to play with specific CSS Grid specifications or Flexbox? To be certain, I'm looking for the help to make my page accurately responsive. Thanks in advance.
HTML
my HTML doesn't get fit here due to character limit. So I'm skipping in writing HTML of my page.
SCSS
.Header {
  padding: 0 40px;
  padding-top: 1rem;
  padding-bottom: 1rem;
}
.Header{
  .navbar-brand {
    margin-right: 1rem;
  }
}
.SocialMedia.ms-auto.d-flex ul{

  list-style-type: none;
}

.navbar-toggler {
  padding: .25rem .75rem;
  font-size: 1.25rem;
  line-height: 1;
  background-color: transparent;
  border: 1px solid transparent;
  border-radius: .25rem;
  transition: box-shadow .15s ease-in-out;
}
.navbar-toggler-icon {
  display: inline-block;
  width: 1.5em;
  height: 1.5em;
  vertical-align: middle;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
}
.navbar-collapse {
  align-items: center;
  width: 100%;
}
.me-auto {
  margin-right: auto!important;
}
.Header .navbar-collapse .navbar-nav a {
    margin-right: 3rem;
    padding: 0;
    font-size: 18px;
    color: #232323;
}
.nav-link {
  display: block;
  padding: .5rem 1rem;
  text-decoration: none;
  transition: color .15s ease-in-out,
  background-color .15s ease-in-out,
  border-color .15s ease-in-out;
}
.Header .navbar-collapse .SocialMedia ul {
  margin-right: 3rem;
  display: flex;
  align-items: center;
  padding-left: 0;
  margin-bottom: 0;
}
.Header .navbar-collapse .SocialMedia ul li {
  float: left;
  margin-right: 10px;
}
a {
  text-decoration: none;
}
.Header .navbar-collapse .SocialMedia ul li a .Twitter {
  width: 35px;
  height: 35px;
  color: #1ea1f2;
}
.Header .navbar-collapse .SocialMedia ul li a .Facebook {
  color: #3c5998;
}
.Header .navbar-collapse .SocialMedia ul li a svg {
  width: 30px;
  height: 30px;
}
.Header .navbar-collapse .SocialMedia ul li a .Youtube {
  color: #ff0400;
  width: 35px;
  height: 35px;
}
.Header .navbar-collapse .SocialMedia .HeadSearchBar li .SearchBar {
  color: black;
  width: 30px;
  height: 30px;
}
.carousel .carousel-item {
  height: 600px;
}
.carousel-item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}
.carousel-control-prev-icon{
  height: 60px !important;
  width: 60px !important;
  background-color: pink !important;
  border-radius: 5px;
  border: 1px solid white;
  position: absolute;
  left: 550%;
  bottom: 58%;
}
.carousel-control-next-icon{
  height: 60px !important;
  width: 60px !important;
  background-color: pink !important;
  border-radius: 5px;
  border: 1px solid white;
  position: absolute;
    left: -16%;
    bottom: 46%;
}
.carousel-caption h3{
font-size: 100px;
font-weight: 700;
color: #fff;
padding-bottom: 20px;
display: inline;
line-height: 1.5;
font-family:'Playfair Display';
position: absolute;
bottom: 585%;
right: 25%;
}
.carousel-caption p{
background-color: lightgray;
color: black;
font-size: 20px;
padding:10px;
text-align: left;
position: absolute;
bottom: -30px;
left: 22%;
}
ol.carousel-indicators {
  position: absolute;
  bottom: 2%;
  margin: 0;
  border-radius: 100%;
  right: 95%;
  left: 15%;
  width: 3%;
  display: flex;
  flex-direction: column;
}
ol.carousel-indicators li{
  float: left;
  width: 33%;
  height: 10px;
  margin-bottom: 10px;
  border-radius: 100%;
  border: 0;
  background: yellow;
}

.site-aboutUs-container{
  max-width:1140px;
  padding-top: 40px;
}

.site-aboutUs-heading-paragraph{
  h2{
    font-size: 65px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding-top: 10px;
    padding-left: 20px;
  }
  p{
    font-size: 20px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding-left: 20px;
  }
  button{
    margin-left: 20px;
    margin-top: 10px;
    font-size: 20px;
    background-color: #f63269;
    color: white;
    border: none;
    border-radius: 4px;
    width: 25rem;
    text-align: center;
    line-height: 4rem;
  }
}
.site-servicesBriefing-container{
  max-width:1140px;
  padding-top: 40px;
  .card {
    position: relative;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border: none !important;
    border-radius: none !important;
}
}
.site-layout .site-servicesBriefing .site-servicesBriefing-container.container .card-deck .card .card-img-overlay .card-title.h5{
  color: var( --e-global-color-4b8b2d9d );
  font-size: 35px;
  padding: 0;
  margin: 0;
  line-height: 1;
  font-family: Playfair Display;
    font-weight: 500;
    letter-spacing: 0px;
    text-transform: none;
    color: var(--white-color);
    background: var(--primary-color);
    text-shadow: none;
color: white;
position:absolute;
top: 270px;
}
.site-clientTestimonial-container{
  max-width:1140px;
  padding-top: 40px;
}
.card-img-top{
  opacity: 0.7;
}
.site-clientTestimonial
{
  background-color: #f7f7f7;
  padding: 60px 40px;
  margin-top: 3rem;
}
.row{
  --bs-gutter-x: 1.5rem;
    --bs-gutter-y: 0;
    display: flex;
    flex-wrap: wrap;
    margin-top: calc(var(--bs-gutter-y) * -1);
    margin-right: calc(var(--bs-gutter-x)/ -2);
    margin-left: calc(var(--bs-gutter-x)/ -2);
}
.site-clientTestimonial-heading h2 {
  font-size: 45px;
  text-transform: uppercase;
  line-height: 1.2em;
  letter-spacing: 5px;
  text-align: center;
  font-family: 'playfair Display';
  margin-bottom: 4rem;
}
.row-two{

    --bs-gutter-x: 1.5rem;
    --bs-gutter-y: 0;
    display: flex;
    flex-wrap: wrap;
    margin-top: calc(var(--bs-gutter-y) * -1);
    margin-right: calc(var(--bs-gutter-x)/ -2);
    margin-left: calc(var(--bs-gutter-x)/ -2);

}
.col-lg-6{
  flex: 0 0 auto;
  width: 50%;
}
.clientTestimonial{
  background: #fff;
    box-shadow: 0 0 10px #00000011;
    position: relative;
    margin-top: 60px;
    padding-bottom: 27px;
    border-radius: 10px;
    padding: 43px 27px;
}
.clientTestimonial img{
  position: absolute;
    border-radius: 50%;
    top: -50px;
    text-align: center;
    left: 0;
    right: 0;
    margin: 0 auto;
    vertical-align: middle;

}
.clientTestimonial ul{
  list-style-type: none;
}
.clientTestimonial ul.text-center {
  text-align: center!important;
}
.clientTestimonial ul.text-center li {
  display: list-item;}
  .clientTestimonial ul.text-center li h3{
  font-size: 15px;
  font-style: normal;
  line-height: 1.6em;
  color: #5b5b5b;
  font-family: sans-serif;
  font-weight: 400;
  padding-top: 20px;
  margin-top: 3rem;}
  .clientTestimonial ul.text-center li h4{
  color: #3e3e3e;
  font-size: 16px;
  line-height: 37px;
  font-weight: 600;
  padding-top: 20px;
  font-family: 'playfair Display';
  margin-bottom: 0;}
  .clientTestimonial ul.text-center li p{
    font-size: 14px;
    text-transform: uppercase;
    color: #3e3e3e;
  }
  .site-services-heading h2 {
    font-size: 45px;
    text-transform: uppercase;
    line-height: 1.2em;
    letter-spacing: 5px;
    text-align: center;
    font-family: 'playfair Display';
    margin-bottom: 4rem;
  }
.site-services{
  padding-top: 40px;
  .service-cardDeck{
    padding-bottom: 20px;
    .service-card{
      border: none;
      .service-card-title{
padding-top: 10px;
font-size: 20px;
      }
      .service-card-description{
        font-size: 16px;
        padding-top: 10px;
      }
      .service-card-button Button{
        font-size: 15px;
margin-top: 10px;
      }
    }
  }
}
.site-salonTour{
  padding-top: 60px;
  background-color: #f2cde1;
}
.col-lg-4 ul{
  list-style-type: none;
  padding-left: unset;
}
.ReactYTPlayer{
  div{
    float: right;
    width: 640px;
    height: 360px;
    div{
      width: 100%;
      height: 100%;
      padding-bottom: 20px;
    }
  }
}
.col-lg-4{
  flex: 0 0 auto;
    width: 33.3333333333%;
}
.col-lg-4 ul li h1 {
  font-size: 35px;
  color: #fff;
  font-family: 'playfair Display';
  font-weight: 600;

}
.col-lg-4 ul li p{

    font-size: 17px;
    color: #fff;
    font-family: sans-serif;
    line-height: 30px;

}
.col-lg-4 ul li a {
    color: #000000d1;
    background: #fff;
    height: 40px;
    float: left;
    display: block;
    line-height: 40px;
    padding: 0 21px;
    border-radius: 5px;
    font-weight: 500;
    font-family: sans-serif;
    letter-spacing: 1px;
    margin-top: 1rem;
    font-size: 15px;
    &:hover{
      text-decoration: none;
    }
}
.site-blog{
  padding-top: 40px;
}
.site-blog-heading h2{
  font-size: 45px;
  text-transform: uppercase;
  line-height: 1.2em;
  letter-spacing: 5px;
  text-align: center;
  font-family: 'playfair Display';
  margin-bottom: 4rem;
}
.blog-card-title{
  padding: 10px;
}
.blog-card-avatar{
  padding: 10px;
}
.blog-card-author{
  padding-left: 10px;
  padding-right: 5px;
  font-size: 10px;
  &:hover{
    text-decoration: none;
  }
}
.blog-card-time{
  padding-left: 5px;
  padding-right: 5px;
  &:hover{
    text-decoration: none;
  }
}
.forward-slash{
font-size: 10px;
}
.ago{
  font-size: 10px;
}
.blog-card-description{
padding-left: 10px;
font-size: 15px;
padding-right: 10px;
}
.blog-card-continueReading{
  padding-bottom: 15px;
  a{
    padding: 10px;
    color: red;
    font-size: medium;
    text-decoration: underline;
    &:hover{
      color:blue;
    }
}}
.site-footer{
  padding-top: 20px;
  background-color: #f7f7f7;
  margin-top: 30px;

}
.content-6-left-description{
  font-size: 16px;
  padding-top: 10px;
}
.content-6-middle-title h3{
  font-size: 20px;
}
.content-6-middle-description p{
font-size: 13px;
}
.content-6-right-title h3{
  font-size: 20px;
  margin-bottom: 5px;
}
.content-6-right-description input{
  font-size: 15px;
  margin-bottom: 10px;
  border: 2px solid black;
  border-radius: 4px;
}
.content-6-right-description1 Button{
  font-size: 15px;
}

Please access http://192.168.1.20:3000/ for my React app on localhost.

A: You don't need to play with any bootstrap native classes. Bootstrap is a mobile first framework and don't need customizations in major cases and your localhost URL will not work on any other device

A: Bootstrap is developed to help you and is responsive out of the box. The way to achieve that is using Bootstrap in the intended way.
So, instead of overwriting Bootstrap use html structure and classes from Bootstrap. Two simplified examples to explain:
// instead of
  button{
    margin-left: 20px;
    margin-top: 10px;
    font-size: 20px;
    background-color: #f63269;
    color: white;
    border: none;
    border-radius: 4px;
    width: 25rem;
    text-align: center;
    line-height: 4rem;
  }
// use bootstrap
<button class="btn btn-primary btn-lg>My Buttons</button>
(Or use same classes on >a>-tag.)

//instead of
.col-lg-6{
  flex: 0 0 auto;
  width: 50%;
}
// use bootstrap

* NOTE SECOND EXAMPLE: it is just to show how settings can be achieved by using existing Bootstrap classes even that code does not make sense. Setting width to a Bootstrap col leads to conflicts which prevents the correct responsive effect ;-)

As Bootstrap is a powerfull framework it indeed is very extensive and need a little bit learning. The best way to start with it honestly is to have a closer look to the docs: https://getbootstrap.com/docs/4.6/getting-started/introduction/
Just use prepared elements with it's html structure and classes and to add extra styling by bootstrap classes. They are developped to work/play together.
Hint: Of course there are scenarios you need to add extra code ... but they are really rare and mostover not as extensive as done in your code. Most extras can be realized by theming the framework settings the Bootstrap vars and extending the maps.


text:
Q: Getting New Session Id before session expires,checkout/session car is empty even cart has item I have a local module, which adds product to cart.To add to cart i have some conditional check before adding to cart,and i am using getSingleton('checkout/session')->getQuote() object for getting number of items in cart.
My code, initially checks number of items in cart in that session,by below code.
if(Mage::getSingleton('checkout/session')->getQuote()->hasItems())
{
}

adding Product to cart code,
$cart = Mage::getModel('checkout/cart');
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
$cart->addProduct($product, $params);
$cart->save();
$this->_getSession()->setCartWasUpdated(true);

My Question is , sometimes hasItems() returns false even my cart has products.
EDIT
I tried logging session_id(), an i found that this session_id changed unexpectedly. That means new session is created , so my cart is empty in this new session.
My Question?
I dont create any session in my code, then why new session is created before the session timeout?

A: You are calling checkout/session model in wrong way. It should be
 Mage::getSingleton('checkout/session');

So your condition will look like
if (Mage::getSingleton('checkout/session')->getQuote()->hasItems()) {
    //do your stuff here
}


text:
Q: Error response from daemon: driver failed programming external connectivity on endpoint Galera alguém já passou por esse erro?
Estou tentando rodar o postgres via docker mas imprime um erro.
sudo docker start database

Error response from daemon failed programming external connectivity on endpoint database (9dcb5288477f88c9ff1ed918beccf6fa2710bb052aca5a278788bd83be5ea80a): Error starting userland proxy: listen tcp 0.0.0.0:5432: bind: address already in use
Error: failed to start containers: database

A: O endereço que você esta tentando direcionar a porta 5432 ja esta em uso por outra aplicação se estiver utilizando o docker-compose, utilize a tag
port:
- 5431:5432


text:
Q: Web Server statistics script in javascript I need a script in javascript (or c#) which cal log the statistics of a web server (cPanel based)
There is inbuild script in cPanel - Awstats. but its in PHP and perl.
That would be fine if there is any service layer available which gives PHP data in XML.
I need suggestion ASAP.

A: It is not cPanel integrated but you can try Google Analytics


text:
Q: $W^{k,2}(\mathbb{R}^n) \hookrightarrow L^\infty(\mathbb{R}^n)$ Let $k,n \in \mathbb{N}$ such that $k>\frac{n}{2}$. How can one prove that $u\in W^{k,2}(\mathbb{R}^n)$ may be embedded into $L^\infty(\mathbb{R}^n)$?

A: We can use Fourier analysis. First, if $u$ is a test function, we can write
$$u(x)=C\int_{\Bbb R^n}\widehat u(t)e^{itx}(1+|t|^2)^{k/2}(1+|t|^2)^{-k/2}dt.$$
Then using Cauchy-Schwarz inequality, we have
$$|u(x)|^2\leqslant C^2\lVert u\rVert_{H^k}^2\int_{\Bbb R}(1+|t|^2)^{-k}dt=C^2\lVert u\rVert_{H^k}^2\omega_n^2\int_{\Bbb R}(1+s^2)^{-k}s^{n-1}ds.$$
Then we conclude by density of test functions (using a sequence converging also almost everywhere).


text:
Q: Open multiple instance of a file- How can I open multiple different instances of file in Emacs? That is to say, the instances are totally independent of each other but write to the same file.
I actually want to have a reference to the original file in one buffers side-by-side with the buffer in which I will be editing while referring to the original content. I don't find opening a temporary buffer, yanking the entire original content into it and have it side-by-side, as an elegant solution.
Other solutions are welcome as well.
I have tried using clone-indirect-buffer and C-x C-v but it doesn't server the purpose.

A: You can create a new buffer (C-xb*new*) and insert the content of the file to it with C-xifilename.

A: As I read through the find-file code, I see this warning coded into it:
"The file %s is already visited normally.
You have asked to visit it literally,
meaning no coding system decoding, format conversion, or local variables.
But Emacs can only visit a file in one way at a time.

Do you want to revisit the file literally now? "

Something that would imply that Emacs' code specifically tries to protect against the situation when the same file is visited multiple times, but the buffers are out of sync with each other. However... you could open two copies of Emacs, in which case they would not know about each other visiting the same file and so would allow this situation to happen.
I can understand that the above isn't a very nice option, but it looks like adding that kind of functionality will require some time understanding the reasons behind it being specifically prevented in the first place.
I've tried this:
M-:(switch-to-buffer (find-file-noselect-1 (create-file-buffer (buffer-file-name)) (buffer-file-name) t nil (buffer-file-name) 1))
And it seems like it would work, but I'm not sure of consequences - maybe different major modes may rely on the original Emacs treatment of files and their editing history, so use with care. The last number 1 is the number to be displayed after the file name, as in Foo.bar<1> So, you'd need to change that, if you need more copies.

A: As mentioned, you might be able to use clone-buffer, although you'll have to let-bind buffer-file-name around the call since clone-buffer otherwise will refuse to clone it.  Another option is to do:
M-x set-visited-file-name RET toto RET
C-x C-f thefile RET
C-x b RET
M-x set-visited-file-name RET thefile RET

the last set-visited-file-name should ask you if you really want to do that, but you can answer that you do and Emacs will accept your choice.  Arguably, clone-buffer should not reject to do it, so you might like to submit a bug-report asking to make it behave similarly to what set-visited-file-name does.

A: You may have some luck with clone-buffer, depending on your mode. It has certain limitations that you can read about in the docs.
Otherwise, here's something quick and dirty:
(defun dodgy-clone-buffer ()
  "Clone the current buffer. The clone will write to the original file."
  (interactive)
  (switch-to-buffer-other-window
   (eval `(with-current-buffer
              ;; Create a new buffer or clear an existing one.
              (get-buffer-create ,(format "*clone: %s*" (buffer-name)))
            (delete-region (point-min) (point-max))
            (insert ,(buffer-string))
            (setq buffer-file-name ,(buffer-file-name))
            (funcall ',major-mode)
            (current-buffer)))))


text:
Q: Enforce two permissions to activity in android I came across with the following issue. I have an activity that uses to permissions: recording audio and writing to external storage and returns the result to those activities that started it with an intent.
I want to make sure that only those other apps could launch it, that have both uses-permissions.
I tried the following declaration in manifest file, but it seems to be incorrect, as android does not allow double use of android permission attribute in activity.
<activity
    android:name="some_name"
    android:label="some_label"
    android:permission="android.permission.RECORD_AUDIO"
    android:permission="android.permission.WRITE_EXTERNAL_STORAGE"
</activity>

Is there any way to make this possible with android?

A: You can crate a custom permission which can be android.permission.RECORD_AUDIO and android.permission.WRITE_EXTERNAL_STORAGE (Both in one permission) and then put that permission in your Activiy.


text:
Q: BackgroundWorker gives threading error when executing In a WPF application I have an SQL query that takes some times to execute and I want to implement a BackgroundWorker with a progress bar so that the user can see when it's finished.
Here's the XAML part :
<Grid Grid.Row="2">
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <ProgressBar x:Name="BgProgBar" Margin="5"/>
    <TextBlock x:Name="Perc_TB" HorizontalAlignment="Center"
               VerticalAlignment="Center"
               Text="{Binding Path=Value,ElementName=BgProgBar}"/>
</Grid>

and here's my BackgroundWorker in code behind :
  public partial class Supp_Stocks : Page
  {
    private string _user = Settings.Default.User;
    private DataTable dt;
    SqlConnection conn;
    SqlCommand comm;
    SqlConnectionStringBuilder connStringBuilder;
    BackgroundWorker Bg = new BackgroundWorker();
    public Supp_Stocks()
    {
        InitializeComponent();
        ConnectToDB();
        Bg.DoWork += Bg_DoWork;
        Bg.ProgressChanged += Bg_ProgressChanged;
        Bg.WorkerReportsProgress = true;

    }

    #region BackGroundWorker
    private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        BgProgBar.Value = e.ProgressPercentage;
    }

    private void Bg_DoWork(object sender, DoWorkEventArgs e)
    {
        for(int i = 0; i < 100; i++)
        {
            try
            {
                comm = new SqlCommand("select STOCK_ENT.ENT_ID,ENT_DATE_ENT,ENT_NUMPAL,CLI_NOM,ART_LIBELLE1,ENT_PICKING,SUM(det_pnet)" +
                " as POIDS_NET from STOCK_DET, STOCK_ENT, CLIENTS, FICHES_ARTICLES, MVTS_SEQUENCE where SEQ_STATUT <> 'V' and" +
                " STOCK_ENT.ENT_ID = STOCK_DET.ENT_ID and STOCK_ENT.ENT_PROP = CLI_CODE and STOCK_ENT.ART_CODE = FICHES_ARTICLES.ART_CODE" +
                " and STOCK_ENT.ENT_ID = MVTS_SEQUENCE.ENT_ID group by STOCK_ENT.ENT_ID, ENT_DATE_ENT, ENT_NUMPAL, CLI_NOM, ART_LIBELLE1, ENT_PICKING order by ART_LIBELLE1", conn);
                SqlDataAdapter dap = new SqlDataAdapter(comm);
                dt = new DataTable();
                dap.Fill(dt);
                Stocks_DT.ItemsSource = dt.DefaultView;
                Bg.ReportProgress(i);
            }
            catch (Exception ex)
            {

                var stList = ex.StackTrace.ToString().Split('\\');
                Messages.ErrorMessages($"ERREUR : \n{ex.Message}\n\nException at : \n{stList[stList.Count() - 1]}");
            }

        }
    }
    private void GenerateStk_Btn_Click(object sender, RoutedEventArgs e)
    {
        Bg.RunWorkerAsync();
    }
    #endregion

    private void ConnectToDB()
    {
        connStringBuilder = new SqlConnectionStringBuilder
        {
            DataSource = @"VM-VISUALSTORE\SQLEXPRESS,1433",
            InitialCatalog = "GSUITE",
            Encrypt = true,
            TrustServerCertificate = true,
            ConnectTimeout = 30,
            AsynchronousProcessing = true,
            MultipleActiveResultSets = true,
            IntegratedSecurity = true,
        };
        conn = new SqlConnection(connStringBuilder.ToString());
        comm = conn.CreateCommand();
    }
}

but when executing the code its returns an error:

Sorry it's in French but it says that "The thread cannot access this object because another thread owns it.

A: You didn't say which line in your code throws the error, but I'm pretty sure it's this one, right?
Stocks_DT.ItemsSource = dt.DefaultView;

And Stocks_DT is a control on your window, right?
That's the source of your problem. As the error says, you can only access UI elements from the UI thread (the main thread). Since you are running the above code on the background thread, it's throwing this exception.
Instead, you need to pass the results of the query back to the main thread and then assign it to Stocks_DT.ItemsSource. I would recommend using the DoWorkEventArgs.Result property. I would suggest using the DataTable as your result so the code would be e.Result = dt. You can access the Result from the BackgroundWorker.RunWorkerCompleted event.

The above will solve the exception, but there are a number of other things I feel I should go over in your code, purely in the interest of helping you out.
First of all, you seem to be looping the same exact query 100 times without any changes. This seems like it would be a waste of time since you'd just get the same result 100 times. If this is the case, you probably don't need a progress bar at all.
Secondly, it is generally considered best practice to open a new SqlConnection when one is needed and close it when it's finished, instead of keeping one connection open for the lifetime of the program/window. This is especially true as you get into multi-threading. You can find more information in this question. When creating these connections, they should be enclosed in a using statement.
Third, C# supports multi-line strings as shown in this question. Using this method will make the SQL query more readable by getting rid of all the "..." + "..."


text:
Q: How to access a resource in Java project using Gradle? I have a javafx project I'm building using a Gradle file, and I'm writing everything in Intellij. In it, I use javafx.scene.media.Media and javafx.scene.media.MediaPlayer to play some music.
public SoundPlayer(String filename) {
    String soundLocation = "\\src\\main\\resources\\sound\\" + fileName;
    String absolute = new File("").getAbsolutePath() + soundLocation;
    System.out.println(absolute);
    Media soundMedia = new Media(new File(absolute).toURI().toString());
    mediaPlayer = new MediaPlayer(soundMedia);
}

The project directory I had been working out of was:
src/
|---main/
|---|---java/
|---|---|---sound.SoundPlayer
|---|---resources/
|---|---|---sound/
|---|---|---|---click.mp3
|---|---|---|---bgm.mp3
however, when I went to compile and turn it into a jar file, Gradle changed the directory into this (within the jar file, top level):
sound/
|---SoundPlayer.class
|---click.mp3
|---bgm.mp3
That made it throw a Media Exception: MEDIA UNAVAILABLE. I've tried changing the file to both of the following:
Media soundMedia = new Media(new File("sound\\" + fileName).toURI().toString());

and
Media soundMedia = new Media(new File(fileName).toURI().toString());

... but I always get the same exception. What's going on?

A: What Gradle did is completely expected. The src/main/java and src/main/resources directories store code and resources respectively. The resources folder contains all the non-java code like images,sound etc.
When creating the jar file, the contents of the resources directory will be copied as is (maintaining the package structure). Note that click.mp3 and bgm.mp3 are members of the sound package.
So, when you want to load a resource, it should (generally) not be done using file paths. Instead use, package structure to do so. Here, as the sounds and SoundPlayer have the same package, i.e. sound, you can use the SoundPlayer class to load resources like following:
public SoundPlayer(String filename) {
    URL resource = SoundPlayer.class.getResource(filename);
    Media soundMedia = new Media(resource.toExternalForm());
    mediaPlayer = new MediaPlayer(soundMedia);
}

From Javadocs

public String toExternalForm()
  Constructs a string representation of this URL. The string is created by calling the toExternalForm method of the stream protocol handler for this object.

In essence, the toExternalForm() function creates the appropriate URL for a given resource.
Here is a complete example.
// build.gradle
apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

mainClassName = 'sound.Main'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.10'
}

jar { manifest { attributes 'Main-Class': 'sound.Main' } }

and the modified SoundPlayer
//sound.SoundPlayer
package sound;

import java.net.URL;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class SoundPlayer {

    private MediaPlayer mediaPlayer;

    public SoundPlayer(String filename) {
        URL resource = SoundPlayer.class.getResource(filename);
        Media soundMedia = new Media(resource.toExternalForm());
        mediaPlayer = new MediaPlayer(soundMedia);
    }

    public void play(){
        mediaPlayer.play();
    }
}

and the Main class to use SoundPlayer
// sound.Main
// This class does not actually create a JavaFX UI. Instead, it is
// only creating a JavaFX application to use Media
package sound;

import javafx.application.Application;
import javafx.stage.Stage;

/**
 *
 * @author aga53
 */
public class Main extends Application{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        SoundPlayer s = new SoundPlayer("test.mp3");
        System.out.println("Hello World");
        s.play();
    }

}


text:
Q: custom Auto increment in Mysql table I have three customer Id in my table, Let's Say A,B,C.I want to create order table for managing orders from these customers. I want to create orderID columns in such away that it must be auto increment with cunstomer Id appended eg. orderID column records :
A_1  --->A's 1st order,
A_2  --->A's 2nd order,
B_1  --->B's 1st order,
C_1  --->C's 1st order,
A_3  --->A's 3rd order,
C_2  --->C's 2nd order,
C_3  --->C's 3rd order,
B_2  --->B's 2nd order,
A_4  --->A's 4th order,
A_5  --->A's 5th order

A: CREATE TABLE IF NOT EXISTS `orders` (
  `order_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `customer_id` BIGINT UNSIGNED NOT NULL,
  `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `fk_customer_orders` (`customer_id` ASC)
);

This allows you to easily INSERT your orders without ever thinking about the generated identifier. The additional created row will allow you to sort them and give them the number's you'd like.
$result = $mysqli->query("SELECT * FROM `orders` WHERE `customer_id` = 1 ORDER BY `created`");

$orders = array();
while ($row = $result->fetch_assoc()) {
    $orders[] = $row;
}

echo count($orders) , PHP_EOL; // 42

foreach ($orders as $delta => $order) {
    echo "Your order #" , ($delta + 1) , " with the unique identifier {$order["order_id"]}." , PHP_EOL;
}

Just an example.


text:
Q: Postgres Rails DB Bug I have just created a new RoR project on a Godaddy VPS running Ubuntu. The app is set up to run Postgres, which is installed and running.
Wwhen I do the INITIAL rake, I get:
server$ bin/rake db:create db:migrate
FATAL:  role "root" does not exist
Run `$ bin/rake db:create db:migrate` to create your database
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:898:in `rescue in connect'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:888:in `connect'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:568:in `initialize'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:41:in `new'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:41:in `postgresql_connection'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:435:in `new_connection'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:445:in `checkout_new_connection'
/usr/local/rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/........

Here is my database yml
development:
  adapter: postgresql
  encoding: utf8
  database: project_development
  pool: 5
  username: philip
  password: ###
test: &TEST
  adapter: postgresql
  encoding: utf8
  database: project_test
  pool: 5
  username: philip
  password: ### - not real

production:
  adapter: postgresql
  encoding: utf8
  database: project_production
  pool: 5
  username: philip
  password: ###

I have tried root and philip.
And I have created roles and users in PG for both.

A: In Ubuntu, PostgreSQL by default is configured to allow local connections over Unix socket only to authenticate with the same username as the connecting Unix user.
You are running your app as root in your OS. And PostgreSQL forces you to use root as a database user name. If you want it to use a different database account, you need to run your app as a different user.
Apparently, your PostgreSQL server doesn't have a root account.

*

*Ubuntu wiki page about PostgreSQL setup
A dirty fix could be authentication over TCP/IP: set a host to 127.0.0.1 in your database.yml, and these restrictions won't have any effect.
Another way to circumvent it is to edit pg_hba.conf to not require "the same user" for local connections.

A: You need to create the roles and database by hand:
SSH into the vps and then ...
Switch into the default user:
sudo su – postgres

Once logged in as this user, you can create the new role:
createuser
Enter name of role to add: philip
Shall the new role be a superuser? (y/n) y

To outfit your user with a password, you can add the words –pwprompt to the createuser command:
createuser --pwprompt

Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-12-04

A: I started over by deleting all roles in PG.  I recreated what I needed and it is all good


text:
Q: How to ensure evaluation order and formal parameter order for named argument lists? Working on a compiler, I am facing a problem related to named argument lists and evaluation order. Basically, the language ensures that for the following function and function call:
int call(int first, int second) = first - second

int sideEffect(int i) { println(i); return i }

println(call(second: sideEffect(0), first: sideEffect(1)))

The output will be
0
1
1

although the arguments are given in reverse order. I am working on the JVM, so they must be sorted on the bytecode level to match the signature of call. In stack-based pseudo-bytecode:
push 0
call sideEffect(int)
push 1
call sideEffect(int)
swap
call call(int, int)

As you can see, a swap bytecode instruction is required here to make sure they are both evaluated and passed in the right order. This can be drawn as a graph:
Actual:   second   first
                \ /
                swap
                / \
Formal:    first   second

There is only one swap instruction that can swap the top two elements on the stack, so for more elements the compiler needs to generate local variables.
Actual: third   second   first
          |       |  /¯¯¯¯
        local0   swap    local0
            ____/ |        |
Formal: first   second   third

In bytecode:
third...
store local0
second...
first...
swap
load local0
call ...

Of course this can be expanded to arbitrary amounts of actual and formal parameters.
What I am now looking for is some kind of algorithm that determines if and where I should insert these swap or local variable instructions. A reference to a compiler implementation would also be helpful.

Note that it is not part of my problem which actual argument belongs to which formal parameter. That is already solved by my compiler. To simplify, the problem could be looked at like this:
Given two arrays of the same sizes containing the same elements in different order, which elements can be swapped or shifted from the first array to get the order of the second one.

A: With registers only, there's basically only one solution. Iterate through the arguments in desired stack order. If the current argument is already computed, load it from a local. Otherwise, compute the uncomputed arguments before it in execution order, storing them in registers, and then compute the current argument.
The presence of a swap operation means that we can use the top of the stack as a de facto local variable. Python code below.
import heapq
import itertools

class Allocator:

  def __init__(self):
    self.free_heap = []
    self.next_free = 0

  def allocate(self):
    if self.free_heap:
      return heapq.heappop(self.free_heap)
    i = self.next_free
    self.next_free += 1
    return i

  def free(self, i):
    heapq.heappush(self.free_heap, i)

  def is_allocated(self, i):
    return i < self.next_free and i not in self.free_heap

def loads_and_stores(perm):
  perm = list(perm)
  n = len(perm)
  assert set(perm) == set(range(n))
  location = {}
  allocator = Allocator()
  i = iter(perm)
  # "location 0" is the top of the stack
  for j in range(n):
    if j in location:
      if location[j] != 0:
        # not top of stack; need an actual load
        print 'load', location[j]
        if allocator.is_allocated(0):
          # need to maintain the top of the stack
          print 'swap'
      allocator.free(location[j])
    else:
      while True:
        k = next(i)
        print 'compute', k
        if k == j:
          if allocator.is_allocated(0):
            # need to maintain the top of the stack
            print 'swap'
          break
        location[k] = allocator.allocate()
        if location[k] != 0:
          # not top of stack; need an actual store
          print 'store', location[k]
  return perm

def test(n):
  for perm in itertools.permutations(range(n)):
    print perm
    loads_and_stores(perm)

test(4)

There are some interesting optimizations to do here, because allocate can return any free local. An optimal algorithm would consider the execution cost of making each allocation.


text:
Q: Laravel - Blade comments , blade rendering causing page to crash I'm rendering a page that is primarily a form with view::make in Laravel and it is crashing, causing ERR_CONNECTION_RESET. After a long investigation and many red herrings, I started erasing (not commenting) random sections out of the blade file for the view and realized that if I
a) erase 2 of the {{Form}} calls inside this section of the form
b) remove the {{-- and --}} from around this section of the form
    {{--

      {{ Form::label('foo', 'foo:') }}
      {{ Form::text('foo') }}

      {{ Form::label('foo', 'foo:') }}
      {{ Form::text('foo') }}

      {{ Form::label('foo', 'foo') }}
      {{ Form::text('foo') }}

    --}}

the page will render. I am not sure what exactly the cause here is. There are other blocks above and below, although this is a 3-div commented out section which none of the others are.
Anyone have a clue what is causing this? Running on WAMP if that matters.

A: Blade comments should only be used for simple remarks or to comment out single-line Blade functions. A single Blade comment cannot be used to comment out multiple lines of code.

Use PHP Block Comments instead. They are still usable in a blade.php file
<?php /*
{{ HTML::form("foo") }};
{{ HTML::form("bar") }};
*/ ?>

Alternatively, comment out your Blade one line at a time:
{{-- HTML::form("foo") --}};
{{-- HTML::form("bar") --}};

Examples of Valid Blade Comments:
Single Blade Function:
{{-- Form::text('foo') --}}

Remark:
{{-- Form Section 1 --}}

Examples of Invalid Blade Comments:
Incorrect syntax:
{{-- Form::text('foo') --  }}

"@" Inside of Blade comment
{{-- @Form::text('foo') --}}

Nested PHP:
{{-- <?php
echo "foo";
echo "bar
?> --}}

Nested Blade:
{{--
{{ HTML::form("foo") }};
{{ HTML::form("bar") }};
--}}

Internals:
Using the sample code from the question, Laravel's Blade Compiler will generate a temporary PHP file containing the following PHP and HTML:
<?php /*

      <?php echo Form::label('foo', 'foo:'); ?>

<?php echo Form::text('foo'); ?>

    <?php echo Form::label('foo', 'foo:'); ?>

    <?php echo Form::text('foo'); ?>

    <?php echo Form::label('foo', 'foo'); ?>

    <?php echo Form::text('foo'); ?>

*/ ?>

The Blade code inside of the Blade comments are still parsed into PHP. The PHP end tags inside of the PHP block-comment can cause compilation issues:

?> breaks out of PHP mode and returns to HTML mode, and // or #
cannot influence that.

A: I have same problem with laravel 5.1 and PHP 7 (new homestead). The work around was to use this:
<?php /* XXX */?>

instead of this:
{{-- XXX -- }}.

A: I have a similar symptom and it seems to be related to the length of the comment alone. I tested it with a comment that doesn't contain any PHP code or blade statements at all:
{{--
0123456789abcdef
0123456789abcdef
0123456789abcdef
--}}

I kept adding copies of the repeated line until it crashed. The comment was lexically followed by a blade @if statement, and the corresponding <php if(...): ?> did not end up in the compiled template, but the closing <?php endif; ?> did, resulting in a syntactically invalid compiled template.
It seems to be a bug in the blade compiler and I will report it.
The workaround is to split long blade comments with --}}{{--.

A: Comments in Blade are very simple!
{{-- Blade comments that wil not appear in the rendered HTML output --}}

You can either do normal PHP comments:
<? /* some comment here */
// or single line comments
# or these :)
?>

A: I have Tried the
Nested PHP:
{{-- <?php
echo "foo";
echo "bar";
?> --}}

@TonyArra

While using . It is Not Commenting the Content and prevents from Compiling as HTML
and this is the htmlsource
{{-- foobar --}}
Which i have got
Thats Because If You want To Comment the php Code inside Blade
Try this

OR

and  try to view the page source

A: Blade comments like this one, were the problem in my case:
{{--
    @if ($test)

something

    @else

something else

    @endif
--}}

A: Simply we have to use a double curly bracket followed by a double hyphen.
This will work for the single line as well multiple lines.
{{--     --}}

A: Blade Comments
{{-- This comment will not be present in the rendered HTML --}}

Referene: https://laravel-news.com/laravel-blade-comments


text:
Q: send html report with row collapsed I'm trying to email pytest html report, however javascript in email is disabled. So the html report expand all rows by default and makes the email content quite long. Where can I set the row collapsed by default?
I've tried to add a custom css to collapse. but that will also make the report collapsed when javascript is enabled.
.results-table-row tr:nth-child(2) {
    display: none;
}

A: I resolved by adding collapsed class to <tr> manually before sending the html report content... - -!


text:
Q: Get Outlook Message (using VSTO, EWS or Redemption) with only the Internet Message ID value I've got the Internet Message ID values from x number of emails. I need to write some C# code to open and display the Outlook messages with only the Internet Message ID value to identify them.
Is it possible to get an Outlook message (using VSTO, EWS or Redemption) with only the Internet Message ID value to identify the email?

A: Sure, if you know the folder where the message resides, you can use RDOFolder.Items.Find(" ""http://schemas.microsoft.com/mapi/proptag/0x1035001F"" = '<SomeValue>' ")