text:
Q: Trying to implement the QuickSort on python : NameError: global name 'x' is not defined I'm learning to use Python, and to start I'm coding some sorts.
I tried one hundred possible changes, but I don't know how to fix it.
Here's my code:
from random import *
from time import *

L = []
for m in range(0,100):
    L.append(randint(0,100))

def quicksort(L, first, last):

    i = first
    j = last
    pivote = (L[i] + L[j]) / 2

    while i < j:
        while L[i] < pivote:
            i+=1
        while L[j] > pivote:
            j-=1
        if i <= j:
            x == L[j]
            L[j] == L[i]
            L[i] == x
            i+=1
            j-=1

    if first < j:
        L == quicksort(L, first, j)
    if last > i:
        L == quicksort(L, i, last)

    return L

start = time()
print ("Disordered:" , L)
L = quicksort(L, L[0], L[len(L)-1])
print ("Ordered:" ,L)
print ("%.2f seconds" % (time() - start))

AND this is the error:
Traceback (most recent call last):
  File "/Users/Ricardo/Desktop/QuickSortR.py", line 48, in <module>
    L = quicksort(L, L[0], L[len(L)-1])
  File "/Users/Ricardo/Desktop/QuickSortR.py", line 28, in quicksort
    x == L[j]
NameError: global name 'x' is not defined

Thanks for helping me!

A: I think you wanted to assign to x:
x = L[j]

You are using ==; a comparison, instead. You do this in several places; == evaluates to a boolean value (when the two items are considered equal), while = assigns to a variable.
In python, you can swap variables directly without a temporary:
if i <= j:
    L[j], L[i] = L[i], L[j]

A: In several places you are using == instead of = in assignment, like x == L[j], this is how you compare to items.  To assign to x you should have x = L[j].
Note that there are several other lines like this that you will need to fix as well.


text:
Q: Reading a File without line breaks using Buffered reader I am reading a file with comma separated values which when split into an array will have 10 values for each line . I expected the file to have line breaks so that
line = bReader.readLine()

will give me each line. But my file doesnt have a line break. Instead after the first set of values there are lots of spaces(465 to be precise) and then the next line begins.
So my above code of readLine() is reading the entire file in one go as there are no lined breaks. Please suggest how best to efficiently tackle this scenario.

A: One way is to replace String with 465 spaces in your text with new line character "\n" before iterating it for reading.

A: I second Ninan's answer: replace the 465 spaces with a newline, then run the function you were planning on running earlier.
For aesthetics and readability I would suggest using Regex's Pattern to  replace the spaces instead of a long unreadable String.replace("                         ").
Your code could like below, but replace 6 with 465:
 // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    String content = "DOG,CAT      MOUSE,CHEESE";
    Pattern p = Pattern.compile("[ ]{6}",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    String newString = p.matcher(content).replaceAll("\n");
    System.out.println(newString);
  }

A: My suggestion is read file f1.txt and write to anther file f2.txt  by removing all empty lines and spaces then read f2.txt something like
FileReader fr = new FileReader("f1.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("f2.txt");
String line;

 while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
if (!line.equals("")) // don't write out blank lines
{
    fw.write(line, 0, line.length());
}

}
Then try using your code.

A: You might create your own subclass of a FilterInputStream or a PushbackInputStream and pass that to an InputStreamReader. One overrides int read().
Such a class unfortunately needs a bit of typing. (A nice excercise so to say.)
private static final int NO_CHAR = -2;
private boolean fromCache;
private int cachedSpaces;
private int cachedNonSpaceChar = NO_CHAR;

int read() throws IOException {
    if (fromCache) {
        if (cachecSpaces > 0) ...
        if (cachedNonSpaceChar != NO_CHAR) ...
        ...
    }
    int ch = super.read();
    if (ch != -1) {
        ...
    }
    return ch;
}

The idea is to cache spaces till either a nonspace char, and in read() either take from the cache, return \n instead, call super.read() when not from cache, recursive read when space.

A: My understanding is that you have a flat CSV file without proper line break, which supposed to have 10 values on each line.
Updated:
1. (Recommended) You can use Scanner class with useDelimiter to parse csv effectively, assuming you are trying to store 10 values from a line:
    public static void parseCsvWithScanner() throws IOException {

    Scanner scanner = new Scanner(new File("test.csv"));

    // set your delimiter for scanner, "," for csv
    scanner.useDelimiter(",");

    // storing 10 values as a "line"
    int LINE_LIMIT = 10;

    // implement your own data structure to store each value of CSV
    int[] tempLineArray = new int[LINE_LIMIT];

    int lineBreakCount = 0;

    while(scanner.hasNext()) {

        // trim start and end spaces if there is any
        String temp = scanner.next().trim();
        tempLineArray[lineBreakCount++] = Integer.parseInt(temp);

        if (lineBreakCount == LINE_LIMIT) {

            // replace your own logic for handling the full array
            for(int i=0; i<tempLineArray.length; i++) {
                System.out.print(tempLineArray[i]);
            } // end replace

            // resetting array and counter
            tempLineArray = new int[LINE_LIMIT];
            lineBreakCount = 0;
        }
    }
    scanner.close();
}

*Or use the BufferedReader.
You might not need the ArrayList to store all values if there is memory issue by replacing your own logic.
public static void parseCsv() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    // your delimiter
    char TOKEN = ',';
    // your requirement of storing 10 values for each "line"
    int LINE_LIMIT = 10;
    // tmp for storing from BufferedReader.read()
    int tmp;
    // a counter for line break
    int lineBreakCount = 0;
    // array for storing 10 values, assuming the values of CSV are integers
    int[] tempArray = new int[LINE_LIMIT];
    // storing tempArray of each line to ArrayList
    ArrayList<int[]> lineList = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    while((tmp = br.read()) != -1) {
        if ((char)tmp == TOKEN) {
            if (lineBreakCount == LINE_LIMIT) {
                // your logic to handle the current "line" here.
                lineList.add(tempArray);
                // new "line"
                tempArray = new int[LINE_LIMIT];
                lineBreakCount = 0;
            }
            // storing current value from buffer with trim of spaces
            tempArray[lineBreakCount] =
                    Integer.parseInt(sb.toString().trim());
            lineBreakCount++;
            // clear the buffer
            sb.delete(0, sb.length());
        }
        else {
            // add current char from BufferedReader if not delimiter
            sb.append((char)tmp);
        }
    }
    br.close();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get msdeploy to create App_Data if it doesn't exist, but not delete any contents of the remote directory? I have an application setup with the following Package/Publish Web settings:

*

*Only files needed to run this application

*(unchecked) Exclude generated debug symbols

*(checked) Exclude files from the App_Data folder

*(checked) Include all databases configured in Package/Publish SQL tab - note I do not have any databases configured

*(unchecked) include IIS settings as configured in IIS Express

In the project, I have an App_Data folder setup, primarily to handle application logs.
The behavior I'd like to see (and expect) is the following:

*

*On initial deploy to a brand new server, the application is copied and an App_Data folder is created with write permissions assigned for the application.

*On subsequent deployments, the App_Data folder is ignored because it already exists and the "Exclude files from the App_Data folder" is checked.

However, msdeploy does not appear to do step #1 (step 2 is fine if I create the folder manually).  I've been unable to find any documentation on the web besides this unanswered so question that seems to confirm the behavior I see.
How do I get msdeploy to create App_Data and assign permissions on initial deployment in this scenario?

A: Web Deploy won't create a folder if there are no files to copy to it.  One workaround in your scenario would be to not use the Exclude files from the App_Data folder check box, put a dummy file in App_Data (such as a .txt file with nothing in it), and specify file exclusion rules for whatever else you have in the App_Data folder (such as your .sdf file).
On excluding individual files (you can use wildcards), see the first question in the deployment FAQ on MSDN:
http://msdn.microsoft.com/en-us/library/ee942158.aspx#can_i_exclude_specific_files_or_folders_from_deployment
On using the dummy file method for causing a folder to be created, see Making Sure that the Elmah Folder gets Deployed in this tutorial:
http://www.asp.net/web-forms/tutorials/deployment-to-a-hosting-provider/deployment-to-a-hosting-provider-configuring-project-properties-4-of-12

A: I managed to get it working when using the Publish Web dialog from within Visual Studio. Note: it works for any folder and not only App_Data.
This is the basic .pubxml profile:
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit http://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
<AfterAddIisSettingAndFileContentsToSourceManifest>AddCustomSkipRules</AfterAddIisSettingAndFileContentsToSourceManifest>
    <WebPublishMethod>MSDeploy</WebPublishMethod>
    <LastUsedBuildConfiguration>Local</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <MSDeployServiceURL>localhost</MSDeployServiceURL>
    <DeployIisAppPath>SuperCoolAwesomeAppName</DeployIisAppPath>
    <RemoteSitePhysicalPath />
    <SkipExtraFilesOnServer>False</SkipExtraFilesOnServer>
    <MSDeployPublishMethod>InProc</MSDeployPublishMethod>
    <EnableMSDeployBackup>False</EnableMSDeployBackup>
    <UserName />
    <_SavePWD>False</_SavePWD>
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
  </PropertyGroup>

  <PropertyGroup>
    <UseMsDeployExe>true</UseMsDeployExe>
  </PropertyGroup>

  <Target Name="CreateEmptyFolders">
    <Message Text="Adding empty folders to Files" />
    <MakeDir Directories="$(_MSDeployDirPath_FullPath)\Files\Folder 1" />
    <MakeDir Directories="$(_MSDeployDirPath_FullPath)\Files\Folder 2" />
    <MakeDir Directories="$(_MSDeployDirPath_FullPath)\Files\Folder 3\Test"/>
  </Target>

  <Target Name="AddCustomSkipRules" DependsOnTargets="CreateEmptyFolders">
    <Message Text="Adding Custom Skip Rules" />
    <ItemGroup>
      <MsDeploySkipRules Include="SkipFilesInFilesFolder">
        <SkipAction>Delete</SkipAction>
        <ObjectName>filePath</ObjectName>
        <AbsolutePath>$(_DestinationContentPath)\\Files\\.*</AbsolutePath>
        <Apply>Destination</Apply>
      </MsDeploySkipRules>

      <MsDeploySkipRules Include="SkipFoldersInFilesFolders">
        <SkipAction></SkipAction>
        <ObjectName>dirPath</ObjectName>
        <AbsolutePath>$(_DestinationContentPath)\\Files\\.*\\*</AbsolutePath>
        <Apply>Destination</Apply>
      </MsDeploySkipRules>

    </ItemGroup>
  </Target>

</Project>

Here's a detailed post explaining it:
Using MsDeploy publish profile .pubxml to create an empty folder structure on IIS and skip deleting it with MsDeploySkipRules

A: Getting App_Data deployed when starting from scratch
@tdykstra got this part right.  To get App_Data out there (and ACLs set automatically), I did the following:

*

*Adding a placeholder file in App_Data

*Set the build action to content on the placeholder (my placeholder file has text in it to let people stumbling across it know why it's there).

*Unchecked "Exclude files from the App_Data folder" on the Package/Publish Web tab of the project properties in VS 2010

This gets my App_Data folder created and ready for use on the server.  However, it will result in all my files getting deleted whenever I republish.  This is problem #2 in my question above, and pretty closely resembles this other SO question/answer.
Preventing data on the server from being deleted on subsequent publish events
There are two mechanisms in MsDeploy that can get confused (at least I confused them):

*

*Excluding files

*MsDeploy skip rules

These can both be used to solve the problem, depending on the scenario:

*

*@tdykstra's solution will likely work if you:

*

*Know the names of the files in App_Data in advance (e.g. a sqllite database)

*Have the files included in the App_Data folder in your project

*The use MsDeploy skip rules to tell MsDeploy to completely skip all deletes on the server for that directory and files in that directory.  This solves the problem in all cases, but is much more involved.

Implementing MsDeploy skip rules
To implement skip rules you'll have to abandon the right-click, Deploy option in VS 2010 in favor of right-click, Package, go into a command line, re-jigger a batch file and run a command line).  If you're willing to put up with this experience (I am, because I'm automating it all through a CI process), here are the details:

*

*Edit the project file and add the following.  Note that the AbsolutePath argument is a regular expression, so you can get way fancy:
<Target Name="AddCustomSkipRules">
    <ItemGroup>
      <MsDeploySkipRules Include="SkipDeleteAppData">
        <SkipAction>Delete</SkipAction>
        <ObjectName>filePath</ObjectName>
        <AbsolutePath>$(_Escaped_PackageTempDir)\\App_Data\\.*</AbsolutePath>
        <XPath>
        </XPath>
      </MsDeploySkipRules>
      <MsDeploySkipRules Include="SkipDeleteAppData">
        <SkipAction>Delete</SkipAction>
        <ObjectName>dirPath</ObjectName>
        <AbsolutePath>$(_Escaped_PackageTempDir)\\App_Data\\.*</AbsolutePath>
        <XPath>
        </XPath>
      </MsDeploySkipRules>
    </ItemGroup>
</Target>

*Package, do not deploy the project.  This will create a zip file and .cmd file in the target directory (defined by "Location where package will be created" on the Package/Publish Web Tab).  By default, this is obj\Debug\Package (or obj\Release\Package)

*Deploy the site using the the resulting command file

In my testing, you must package and run the command file.  The project file tweaks will tell msbuild to put the necessary -skip rule into the command file.  However, using the "publish" feature straight from VS 2010 doesn't seem to run the command file (see the warning on this walkthrough)...it calls msdeploy directly and doesn't seem to honor the project file skip rules.  I believe this is the difference between VS using msbuild -T:Package and msbuild -T:MsDeployPublish to build the project, but I have not tested this.
Finally, the command file isn't quite correct, at least in VS 2010 SP1.  There's a great description of what goes wrong in this SO answer, but basically, VS (or maybe the /t:Package target is a better culprit) sets up the command file to publish to the machine without specifying a site.  To fix that, you'll need to somehow get "?site=sitename" (probably this is ?site=Default+Web+Site, for a full URL of https://machine:8172/MsDeploy.axd?site=Default+Web+Site) onto the end of the computerName argument.
The problem I had was that the command file (batch file) has a hard time with using site= anything on the command line since it mis-parses the command line argument (even if escaped).  I don't see a way around this problem other than modifying the cmd file directly, but for testing I copied the msdeploy.exe output I saw from my failed test run and modified that to call msdeploy.exe directly without the script.
Now that it's working, my intention is to work this into my CI build processes.  What I'll be doing for the final solution is:

*

*Change my build script to use /T:Package (right now it's /T:MsDeploy)

*Have a scripted search/replace routine alter the generated cmd deployment script

*Run the altered deployment script

This really should be easier.
Update
Here's the scripted search/replace routine I've come up with in PowerShell:
(Get-Content "project.deploy.cmd")
  -replace('^set _ArgComputerName=$'
           ,"set  ArgComputerName=https://server:8172/MsDeploy.axd?Site=Default+Web+Site")
  | Out-File -Encoding ascii deploy.cmd

Once that is run, deploy.cmd can be called (without the /M option) and it will work as expected.

A: Summarizing and simplifying Emil and Leniel answers in a concise one, if you just want to allow App_Data deploy for adds and updates, but prevents deletes, add this to your .pubxml.
<Project>
  ...

  <PropertyGroup>
    <UseMSDeployExe>true</UseMSDeployExe>
    <ExcludeApp_Data>False</ExcludeApp_Data>
  </PropertyGroup>

  <Target Name="AddCustomSkipRules"
          AfterTargets="AddIisSettingAndFileContentsToSourceManifest">
    <Message Text="Adding Custom Skip Rules" />
    <ItemGroup>
      <MsDeploySkipRules Include="SkipDeleteAppData">
        <SkipAction>Delete</SkipAction>
        <ObjectName>filePath</ObjectName>
        <AbsolutePath>App_Data\\.*</AbsolutePath>
      </MsDeploySkipRules>
      <MsDeploySkipRules Include="SkipDeleteAppData">
        <SkipAction>Delete</SkipAction>
        <ObjectName>dirPath</ObjectName>
        <AbsolutePath>App_Data</AbsolutePath>
      </MsDeploySkipRules>
    </ItemGroup>
  </Target>
</Project>

<UseMSDeployExe>true</UseMSDeployExe> is really needed or it will fail complaining Unrecognized skip directive 'skipaction'.


text:
Q: Scala Swing image How do I load and display an image in a Scala Swing component?

A: I usually use Label with ImageIcon for that ... like:
val label = new Label {
  icon = new ImageIcon("path to the image file")
}

A: Here is an implementation of an ImagePanel that extends scala's Panel
import swing._

import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

class ImagePanel extends Panel
{
  private var _imagePath = ""
  private var bufferedImage:BufferedImage = null

  def imagePath = _imagePath

  def imagePath_=(value:String)
  {
    _imagePath = value
    bufferedImage = ImageIO.read(new File(_imagePath))
  }

  override def paintComponent(g:Graphics2D) =
  {
    if (null != bufferedImage) g.drawImage(bufferedImage, 0, 0, null)
  }
}

object ImagePanel
{
  def apply() = new ImagePanel()
}

Usage:
object ImagePanelDemo extends SimpleSwingApplication
{

  def top = new MainFrame {
    title = "Image Panel Demo"

    contents = new ImagePanel
    {
      imagePath = ("../testImage.jpg")
    }
  }
}


text:
Q: How to guarantee the execution of an event in java I have two classes, the first is updating data in a database and the second sends an email to inform user about the update.
updateTable(){
   // update table code
}

sendEmail(){
   // send email
}

I use them in a function that executes them both once the event is triggered.
function(){
    updateTable();
    sendEmail();
}

My question is how can I be sure that the email was sent when the update was executed successfully?

A: You can't guarantee that a mail was sent successfully. There can be several issues with sending the mail that are simply out of the scope of your application.
What you can do is roll back the changes if the sending of the mail fails. I suggest you look into database transactions.
With transactions you can run a query, do some other actions (or other queries) and either commit the changes or roll them back when you know whether everything ran successfully or not.


text:
Q: Firebase Analytics event logging error I use Firebase Analytics and my app logs some events with this code:
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "SOME_ID")
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "SOME_TYPE");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

And it seem to work well most of the time. In logcat I have something like this:
Logging event (FE): select_content, Bundle[{_o=app, content_type=SOME_TYPE, item_id=SOME_ID}]

But for some events I receive
Logging event (FE): select_content, Bundle[{_o=app, _ev=item_id, _err=4, content_type=SOME_TYPE}]

Apparently, _err=4 is some kind of error code. What does it mean?

In that cases with error my item_id was a pretty long string (20-30 symbols). Maybe there is a limitation on the length of the item_id?

A: According to Official Documentation:

Param names can be up to 40 characters long, may only contain
  alphanumeric characters and underscores ("_"), and must start with an
  alphabetic character. Param values can be up to 100 characters long.

So, they have length constraints on both Key and Value.
Key: 40 characters long
Value: 100 characters long

A: Yes, They have a restriction on the length of the item_id. In my case as well while I was integrating it with my app, got the same errors when my item_id was long.

A: You are logging event with a parameter that exceeds the maximum value limit. There was accompanying FA/Error log message with more details that you probably missed.
Here is the list of the Firebase Analytics error codes:
1 - Invalid Firebase project id.
2 - Event name is invalid (empty, too long, invalid characters).
3 - Event parameter name is invalid (empty, too long, invalid characters).
4 - Event parameter value is too long.
5 - Event has more than 25 parameters.
6 - User property name is invalid (empty, too long, invalid characters).
7 - User property value is too long.
8 - App Instance logs more than 500 unique event types.
9 - App Instance sets more than 25 unique user properties.
10 - App Instance exceeds conversion event limit in a single day.
13 - Event name is reserved.
14 - Event parameter name is reserved.
15 - User property name is reserved.
11, 12, 16 - Internal error.

A: Please refer to error code values in Official Google Docs. It clearly states that error 4 means "Event parameter value is too long". Hope this helps someone with different error code too.


text:
Q: Javafx loading FXML into TitledPane is blurred I am trying to loading a FXML into TitledPane. but it look like very blurred.
I dont know the reason.
My code include 2 files like below:
MainTitlePane.java
public class MainTitlePane extends Application {

  public static void main(String[] args) {
      launch(args);
  }

  @Override
  public void start(Stage stage) throws IOException {
    stage.setTitle("TitledPane");
    Scene scene = new Scene(new Group(), 500, 800);
    scene.setFill(Color.GHOSTWHITE);

    //Load AnchorPane from FXML file
    FXMLLoader loader1 = new FXMLLoader(getClass().getResource("ChildPane.fxml"));
    AnchorPane childPane = (AnchorPane) loader1.load();

    //Add pane to TitledPane
    TitledPane tps1 = new TitledPane("First",childPane);
    Accordion acc = new Accordion (tps1);

    acc.setExpandedPane(tps1);

    //Add button outside of TitledPane
    Button btnTest = new Button("Button Direct");
    btnTest.setLayoutX(250.0);
    btnTest.setLayoutY(250.0);

    Group root = (Group)scene.getRoot();
    root.getChildren().addAll(acc, btnTest);
    stage.setScene(scene);
    stage.show();
  }
}

and ChildPane.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1">
<children>
  <ScrollPane layoutX="673.0" prefHeight="380.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
    <content>
      <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="300.0" prefWidth="189.0">
           <children>
              <Label layoutX="31.0" layoutY="22.0" text="Hello world" />
              <Button layoutX="49.0" layoutY="159.0" mnemonicParsing="false" text="Submit" />
           </children>
        </AnchorPane>
    </content>
  </ScrollPane>

 </children>
</AnchorPane>

When i run my code, the app look like the image below:

How I can fix my problem?
Thanks!

A: Unfortunately it's not quite clear what you want to achieve with this layout hierarchy. Anyway, simply remove the AnchorPane anchors or set them to 0.5 just like below.
AnchorPane.bottomAnchor="0.5" AnchorPane.rightAnchor="0.5" AnchorPane.topAnchor="0.5"

A: I have found the reason, i am using ScrollPane in ChildPane.fxml, the scroll bar will zoom the screen, i think that is the reason.
It worked if i remove ScrollPane . Thanks

A: This is unfortunately an unresolved issue afaik. (https://bugs.openjdk.java.net/browse/JDK-8089499)
Text contents inside ScrollPane are getting blurry. There are couple workarounds;

*

*As @wzberger mentioned, setting anchor constraints to 0.5 could solve this (I don't know why but it gets blurry again with 0.0 or 1.0)

*Second solution would be via binding the ScrollPane width to AnchorPane
scrollPane.prefWidthProperty().bind(anchorPane.widthProperty());
scrollPane.prefHeightProperty().bind(anchorPane.heightProperty());

If you think it goes a bit over, you can substract from the width property
scrollPane.prefWidthProperty().bind(anchorPane.widthProperty().subtract(100));
scrollPane.prefHeightProperty().bind(anchorPane.heightProperty().subtract(100));


text:
Q: Why do I get the error FromIterator<&{integer}> is not implemented for Vec when using a FlatMap iterator? Consider this snippet:
fn main() {
    let arr_of_arr = [[1, 2], [3, 4]];
    let res = arr_of_arr
        .iter()
        .flat_map(|arr| arr.iter())
        .collect::<Vec<i32>>();
}

The compiler error is:
error[E0277]: the trait bound `std::vec::Vec<i32>: std::iter::FromIterator<&{integer}>` is not satisfied
 --> src/main.rs:6:10
  |
6 |         .collect::<Vec<i32>>();
  |          ^^^^^^^ a collection of type `std::vec::Vec<i32>` cannot be built from an iterator over elements of type `&{integer}`
  |
  = help: the trait `std::iter::FromIterator<&{integer}>` is not implemented for `std::vec::Vec<i32>`

Why does this snippet not compile?
In particular, I'm not able to understand the error messages: what type represents &{integer}?

A: {integer} is a placeholder the compiler uses when it knows something has an integer type, but not which integer type.
The problem is that you're trying to collect a sequence of "references to integer" into a sequence of "integer".  Either change to Vec<&i32>, or dereference the elements in the iterator.
fn main() {
    let arr_of_arr = [[1, 2], [3, 4]];
    let res = arr_of_arr.iter()
        .flat_map(|arr| arr.iter())
        .cloned() // or `.map(|e| *e)` since `i32` are copyable
        .collect::<Vec<i32>>();
}


text:
Q: Get multiple relation with same name in laravel I want to get 4 relations on User Model with same name, this is for blade file where I have to show profile data for all users
So I can do $user->person->location;
I am getting this error:
Call to undefined relationship [Doctor AS Person] on model [App\User].

If there is another good solution please suggest it
Controller
    public function profile()
    {
        $curr_user = Auth::user();

        if($curr_user->hasrole('Doctor'))
        {
            $user = $curr_user->with('Doctor AS Person')->get();
        }
        elseif($curr_user->hasrole('Patient'))
        {
            $user = $curr_user->with('Patient AS Person')->get();
        }
        if($curr_user->hasrole('Pharmacy'))
        {
            $user = $curr_user->with('Pharmacy AS Person')->get();
        }
        if($curr_user->hasrole('Lab'))
        {
            $user = $curr_user->with('Lab AS Person')->get();
        }

        return view('admin.profile', compact('user'));
    }

User Model
    public function doctor()
    {
        return $this->hasOne('App\Doctor');
    }

    public function patient()
    {
        return $this->hasOne('App\Patient');
    }

    public function pharmacy()
    {
        return $this->hasOne('App\Pharmacy');
    }

    public function lab()
    {
        return $this->hasOne('App\Lab');
    }

A: laravel eager load does not support alias, so you can reassign relationship name
$user = $curr_user;
if($curr_user->hasrole('Doctor'))
{
    $user->Person = $user->Doctor;
}
else if ($curr_user->hasrole('Patient'))
{
    $user->Person = $user->Patient;
}...


text:
Q: mplayer dumpstream sometimes fails I'm trying to rip the video at http://videolectures.net/ecml07_getoor_isr/, so I can play it at a faster speed.  I paste http://193.2.4.216/2007/pascal/ecml07_warsaw/getoor_lise/ecml07_getoor_isr_01.wmv into a firefox browser in Windows and MediaPlayer plays the thing.  However if I try mplayer -dumpstream, it gets stuck into an infinite loop trying to play the file.
If I use wget to download the link, I get a small text file which basically points to the same URL.  How can I get mplayer to download this stream?

A: I don't know how to make the mplayer plugin capture a stream, but mplayer itself can capture streams fairly well.  Try running from the command line.  Either:
wget < your url > -O - | mplayer -cache 8192 -

or
mplayer < your url > -dumpstream -dumpfile < out file >


text:
Q: PHP if statement from mysql results I'm attempting to read results from a mysql db, determine when the result is a 1 or a 0 and then set a variable to either green.png or red.png:
$result = mysql_query("select * from ping limit 1") or die(mysql_error());
               $row = mysql_fetch_array($result);

                                $beckton = $row['beckton'];
                                if ($beckton = '1'){
                                    $beckton_status = "";
                                }
                                else if ($beckton = '0'){
                                    $beckton_status = "";
                                }

In my table 'ping' there is a column called 'beckton' which will be either a 1 or a 0. however when i load the page, all images are set to green.png, when i can clearly see in the DB that some are 0's.
i'm then just doing this: echo "Beckton	" . $beckton_status . "	";

A: if($beckton == '1')

Not
 if($beckton = '1')

At a cursory glance it seems to me you are setting the $beckton variable, not comparing it.

A: It's also worth mentioning (although @Jason Benson is 100% correct), that you don't have a loop in your code at all. The code you've written will only return the first result of the database, and nothing more. You'll probably need a while() loop to iterate over all the database results, if your table has more than one entry in it (which I think you mentioned).

A: In your comment, you write that you only need your latest result, in this case, you should use some kind of ORDER BY timestamp=latest in your SQL, to ensure you always get the latest result


text:
Q: Storybook documentation code only shows template When I look at the code of my component in Storybook, I only see the template that was used for the component. The arguments (attributes) are not filled out. How can I solve this?

Code
<Meta
        title="svelte-component-kit/Heading"
        component={Heading}
        argTypes={{
          text: { control: "text" },
          level: { control: "text" },
        }}
/>

<Template let:args let:text>
    <Heading {...args}>{text}</Heading>
</Template>

<Story name="H1" args={{
        level: "1",
        text: "Hello, World!",
}}/>

<Story name="H2" args={{
        level: "2",
        text: "Hello, World!",
}}/>

<Story name="H3" args={{
        level: "3",
        text: "Hello, World!",
}}/>


text:
Q: JQuery DirtyForms and Bootstrap Nav tabs My page contains multiple forms in several tabs. Tabs are implemented with bootstrap Navs (https://getbootstrap.com/docs/4.0/components/navs/) .
Dirty form dialog is non activated when I click a tab anchor (e.g. <a href="#divTab1" class="nav-link" ..). Why ?
My final goal is to have dirtyforms detect the dirty state of a tab and popup the dialog. And if finally user decides to procceed i will clean the dirty state of the leaving tab before switching to the new one.
I tried already the answer I found here and partially it made the job but it pops up the dialog every time I click on any tab.
The environment :

*

*Dirty forms V2.0

*Dirtyform Dialog Bootstrap V2,0

*Bootstrap V4.6

*JQuery V3.5.1

Thanks in advance


text:
Q: iterate linux file ldif Im trying to retrieve some user for a ldif file containing some specific attribute.
The input file will look like:
# entry-id: 2
dn: uid=xxx,ou=xx,cn=xx,o=xx,c=xx,o=xx
uid: xxx
cn: Paul
SUKsoft: Windows
SUKsoft: Linux
...
# entry-id: 3
dn: uid=yyy,ou=yy,cn=yy,o=yy,c=yy,o=yy
uid: yy
cn: Jones
SUKsoft: Windows
...

# entry-id: 3
dn: uid=zzz,ou=zz,cn=zz,o=zz,c=zz,o=zz
uid: zz
cn: John
SUKsoft: Linux
...
# entry-id: 4
dn: uid=www,ou=ww,cn=ww,o=ww,c=ww,o=ww
uid: ww
cn: John2

...
# entry-id: 5
dn: uid=mmm,ou=mm,cn=mm,o=mm,c=mm,o=mm
uid: mm
cn: John3
SUKsoft: Linux
...

The result file should filter for the user with the SUKsoft: Windows attribute:
uid|cn
xx|Paul
yy|Jones

I dont have much experience with linux shell bash, i am trying to read iterate the file first to obtain suksoft and uid attributes ad then reprocess it again to compone the final file getting just the uid with the SUKsoft below:
cat 1.txt | while read line
do
   egrep -w  '^uid|SUKsoft' $line > output.txt
done

Now the output looks like:
uid: xxx
SUKsoft: Windows
SUKsoft: Linux
uid: yy
SUKsoft: Windows
uid: zz
SUKsoft: Linux
uid: ww
uid: mm
SUKsoft: Linux

Now i would like to process the file get the uid line ultil i have one SUKsoft: Windows and copy them to the final file.
Could you help me here please?
Thanks
Regards

A: For something very quick and dirty, I'd go for awk instead:

#!/usr/bin/env bash

awk -F ': ' '
    BEGIN               { print "uid|cn" }
    $1 == "uid"         { uid = $2 }
    $1 == "cn"          { cn  = $2 }
    /SUKsoft: Windows/  { print uid "|" cn }
' "$@"

But the above is crude, and makes assumptions about structure of the lines in the input ldif file: fields appearing in a usable order (uid and cn entries before SUKsoft, etc.).
Hardening left as a further exercise, I guess.
Edit: one such hardening. Track a bit of state, clearing uid and cn variables at the start of entry ("dn"), printing a SUKsoft: Windows entry only if both uid and cn have been seen.

#!/usr/bin/env bash

awk -F ': ' '
    BEGIN               { print "uid|cn" }
    $1 == "dn"          { uid = cn = "" }
    $1 == "uid"         { uid = $2 }
    $1 == "cn"          { cn  = $2 }
    /SUKsoft: Windows/  { if (uid != "" && cn != "") { print uid "|" cn } }
' "$@"

Note that if crude approaches like this are expected to handle arbitrary LDIF, these approaches should simply be abandoned and an LDIF parser be used.


text:
Q: PreparedStatementCallback; bad SQL grammar in JDBC Spring I have an update method to update the content of a table based on a specific field and I am getting following exception.
Code is :
public void updateTaxoActive(String oldDesc, String description) {
    Logger.getLogger(TypeCategoryJDBCTemplate.class.getName()).log(Level.INFO, "old taxonomy code is {0} new description is {1}", new Object[]{oldDesc, description});
    String sql = "update product.typecategory set taxonomydescription = ? where taxonomydescription = ?";
    jdbcTemplateObject.update(sql, new Object[]{description,oldDesc},new TypeCategoryMapper());
}

Exception is:
Exception in thread "AWT-EventQueue-0" org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [update product.typecategory set taxonomydescription = ? where taxonomydescription = ?]; nested exception is com.ibm.db2.jcc.am.SqlSyntaxErrorException: [jcc][1091][10824][4.13.127] Invalid data conversion: Parameter instance [Ljava.lang.Object;@1dc421 is invalid for the requested conversion. ERRORCODE=-4461, SQLSTATE=42815
    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:95)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:818)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:874)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:882)
    at com.ibm.quest.model.typecategory.TypeCategoryJDBCTemplate.updateTaxoActive(TypeCategoryJDBCTemplate.java:59)
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow.updateButtonActionPerformed(ApplicationWindow.java:255)
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow.access$800(ApplicationWindow.java:16)
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow$10.actionPerformed(ApplicationWindow.java:218)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:702)
    at java.awt.EventQueue$4.run(EventQueue.java:700)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: [jcc][1091][10824][4.13.127] Invalid data conversion: Parameter instance [Ljava.lang.Object;@1dc421 is invalid for the requested conversion. ERRORCODE=-4461, SQLSTATE=42815
    at com.ibm.db2.jcc.am.id.a(id.java:677)
    at com.ibm.db2.jcc.am.id.a(id.java:60)
    at com.ibm.db2.jcc.am.id.a(id.java:103)
    at com.ibm.db2.jcc.am.oo.c(oo.java:2584)
    at com.ibm.db2.jcc.am.oo.setObject(oo.java:2363)
    at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:365)
    at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:217)
    at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:145)
    at org.springframework.jdbc.core.ArgPreparedStatementSetter.doSetValue(ArgPreparedStatementSetter.java:65)
    at org.springframework.jdbc.core.ArgPreparedStatementSetter.setValues(ArgPreparedStatementSetter.java:46)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:822)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:818)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:589)
    ... 43 more

A: What are you doing with TypeCategoryMapper ?
Remove ,new TypeCategoryMapper()


text:
Q: Android app with flash: "application descriptor file cannot be parsed" I'm new to app-programming and I'm creating an app with flash CS5.5. While the document is unsaved, I can test the app (on AIR debug launcher). When I try to test it on a mobile, it makes me save it (my version is in spanish, and 'unsaved' contains an accent), and, when I do, it's impossible to test the app, also on debug launcher. ("application descriptor file cannot be parsed"). The description file is create by flash, so it must be right, I guess. It've tried reinstalling java, and it outputs the same message. Thanks in advance.
I think the problem might be on the android SDK, which I can't link to flash on the deployment tab of my "Air settings", because the space for doing that isn't simply there.

A: Try to open your FLA-file from a mapped drive instead of a network drive.
I got the same error when my file path was a network drive (\network\path), but dragging the file into an empty Flash instance from Total Commander made the file-path change to S:\myfolder\ and then the problem disapeared...
When your FLA-file is open, hold the mouse over the tap in the top to see what your file-path is.

A: There is Included files in General tab of AIR for android settings. There are yourproject-app.xml there. It should be found in your project directory. Problem is within it.
Try to create new blank project and compare app.xml's, try publishing blank project into android device.
Make shure AIR sdk version is correct.
If nothing helps post content of yourproject-app.xml here, and ill try to help
EDIT: As i said make shure AIR sdk version is correct. If you trully have 13.0 version of sdk in your flash, then this line:
<application xmlns="http://ns.adobe.com/air/application/13.0">

Should be 4.0 insted of 13.0
<application xmlns="http://ns.adobe.com/air/application/4.0">

try it

A: I've already tried that. Even if the project is blank, it gives me tha same error (once I have saved it). This is my project-app.xml file.
  <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
 <application xmlns="http://ns.adobe.com/air/application/13.0">
  <id>prova6</id>
  <versionNumber>1.0.0</versionNumber>
  <versionLabel />
  <filename>prova6</filename>
  <description />
 <!--  To localize the description, use the following format for the description element.<description><text xml:lang="en">English App description goes here</text><text xml:lang="fr">French App description goes here</text><text xml:lang="ja">Japanese App description goes here</text></description>-->
  <name>prova6</name>
  <!--  To localize the name, use the following format for the name element    <name><text xml:lang="en">English App name goes here</text><text xml:lang="fr">French App name goes here</text><text xml:lang="ja">Japanese App name goes here</text></name>
  -->
  <copyright />
  <initialWindow>
  <content>prova6.swf</content>
  <systemChrome>standard</systemChrome>
  <transparent>false</transparent>
  <visible>true</visible>
  <fullScreen>false</fullScreen>
  <aspectRatio>portrait</aspectRatio>
  <renderMode>cpu</renderMode>
  <autoOrients>false</autoOrients>
  </initialWindow>
  <icon />
  <customUpdateUI>false</customUpdateUI>
  <allowBrowserInvocation>false</allowBrowserInvocation>
  </application>


text:
Q: Explain Behavior of HDBSCAN Clustering I have a dataset of 6 elements. I computed the distance matrix using Gower distance, which resulted in the following matrix:

By just looking at this matrix, I can tell that element #0 is similar to element #4 and #5 the most, so I assumed the output of the HDBSCAN would be to cluster those together, and assume the rest are outliers; however, that wasn't the case.
clusterer = hdbscan.HDBSCAN(min_cluster_size=2, min_samples=3, metric='precomputed',cluster_selection_epsilon=0.1, cluster_selection_method = 'eom').fit(distance_matrix)

Clusters Formed:
Cluster 0: {element #0, element #2}
Cluster 1: {element #4, element #5}
Outliers:  {element #1, element #3}
which is a behavior I don't understand. Also, both parameters cluster_selection_epsilon and cluster_selection_method don't seem to have an effect on my results at all and I don't understand why.
I tried changing the parameters again to min_cluster_size=2, min_samples=1
Clusters Formed:
Cluster 0: {element #0, element #2,element #4, element #5}
Cluster 1: {element #1, element #3}
and any other change in the parameters resulted in all points classified as outliers.
Can someone please help explain this behavior, and explain why cluster_selection_epsilon and cluster_selection_method don't affect the clusters formed. I thought that by setting cluster_selection_epsilon to 0.1, I'd be ensuring that the points inside a cluster would be of distance 0.1 or less apart (so that element #0 and element #2 aren't clustered together for instance)
Below is a visual representation of both clustering trials:

A: As touched upon in the help page, the core of hdbscan is 1) calculating the mutual reachability distance and 2) applying the single linkage algorithm. Since you do not have that many data points and your distance metric is pre-computed, you can see your clustering is decided by the single linkage:
import numpy as np
import hdbscan
import matplotlib.pyplot as plt
import seaborn as sns

x = np.array([[0.0, 0.741, 0.344, 1.0, 0.062, 0.084],
 [0.741, 0.0, 0.648, 0.592, 0.678, 0.657],
 [0.344, 0.648, 0.0, 0.648, 0.282, 0.261],
 [1.0, 0.592, 0.655, 0.0, 0.937, 0.916],
 [0.062, 0.678, 0.282, 0.937, 0.0, 0.107],
 [0.084, 0.65, 0.261, 0.916, 0.107, 0.0]])

clusterer = hdbscan.HDBSCAN(min_cluster_size=2,min_samples=1,
                            metric='precomputed').fit(x)
clusterer.single_linkage_tree_.plot(cmap='viridis', colorbar=True)

The results will be:
clusterer.labels_

[0 1 0 1 0 0]

Because the minimum number of clusters has to be 2. So the only way the achieve this is to have element 0,2,4,5 together.
One quick solution is to simply cut the tree and get the cluster you intended:
clusterer.single_linkage_tree_.get_clusters(0.15, min_cluster_size=2)

[ 0 -1 -1 -1  0  0]

Or you simply use something from sklearn.cluster.AgglomerativeClustering since you are not relying on hdbscan to calculate the distance metrics.


text:
Q: How to get ride of JavaScript errors when using ng-repeat variable as a PHP function parameter? I am have a function qsys::getFullUrl() in PHP which resolves the full URL to images.
Inside the parameter, I need to include an angular variable.
Surprisingly, this actually works, and shows the image:

    <img style="width: 100px" src="<?= qsys::getFullUrl('customImages/{{book.idcode}}.png') ?>"/>

{{book.title}}

{{book.description}}

However, I also get Javascript errors:
NetworkError: 404 Not Found - http://localhost/test/customImages/%7B%7Bbook.idcode%7D%7D.png"

How can I get rid of these JavaScript errors?

A: I don't know much about Angular, but in PHP I would probably do something like this:
<?= url_decode(qsys::getFullUrl('customImages/{{book.idcode}}.png')) ?>

That will then decode the values, but it will decode everything that that function returns, so you might want to only decode that, which you could do this:
$book_file = qsys::getFullUrl('customImages/{{book.idcode}}.png');
echo str_replace("%7B%7Bbook.idcode%7D%7D", "{{book.idcode}}", $book_file) ?>

You could even have your string replace do this to just replace { and }:
$find    = array("%7B","%7D");
$replace = array("{","}");
echo str_replace($find, $replace, qsys::getFullUrl('customImages/{{book.idcode}}.png')) ?>

Using either of these methods should get you a url that finalizes to the browser like this:
 http://localhost/test/customImages/{{book.idcode}}.png"

Angular should then be able to handle it.

A: I solved this with ng-src:

{{book.title}}

{{book.description}}

and by putting the fullUrl in the module:
$scope.absolutePath = '<?= qsys::getFullUrl() ?>';


text:
Q: GPU serializations decomposition According to this, http://www.nvidia.co.uk/content/PDF/isc-2011/Ziegler.pdf, I understand that replays in the GPU literature mean serializations. But what are the factors that contribute to the number of serializations?
To do this, I did some experiments. Profiled a some kernels and find the number of replays (= issued instructions - executed instructions). Sometimes, the number of bank conflicts to be equal to the number of replays. Some other times, the number of bank conflicts is smaller. This implies the number of bank conflicts is always a factor. What about the other?
According to the slides above (from slides 35), there are some others:
. The instruction cache misses
. Constant memory bank conflicts
To my understanding, there can be two others:
. The number of branches divergences. Since both paths are executed, there are replays. But i'm not sure if the number of issued instructions are affected by divergences or not?
. The number of cache misses. I have heard that long latency memory requests will be replayed sometimes. But in my experiments, L1 cache misses are often higher than replays.
Can anyone confirm these factors are those contribute to serializations? What is incorrect and do I miss something else?
Thanks

A: As far as I know branch divergence contributes to instruction replay.
I am not sure about the number of cache misses. That should be handled transparently by the memory controller not affecting the instruction. Worse thing I can think is that the pipeline gets stopped until the memory has been properly fetched.


text:
Q: Perform asynchronous call before calling function I have a function, authenticate() that uses $post() to retrieve a session key from my server. I believe $post is an asynchronous call. Whenever I perform any action in my script, I want to ensure that I have a sessionKey, and if I do not have a sessionKey I want to authenticate(). My problem is how do I run performTask() after I have called authenicate()?
function foo() {
    if (sessionKey) {
        performTask();
    } else {
        authenciate();
        performTask();
    }
}

function authenticate() {
    $.post(url, function(data) {
        sessionKey = data.sessionKey;
    });
}

EDIT: I also do not want to put in authenticate()'s callback function performTask() as authenticate() will be called from several different functions.

A: Pass the callback to authenticate() itself using jQuery's Promise interface (see documentation):
function authenticate(callback) {
    var rq = $.post(url, function(data) {
        sessionKey = data.sessionKey;
    });

    if(callback) {
        rq.success(callback);
    }
}

Now just call authenticate(performTask), for example.

A: You can pass in a callback to the authenticate method.  If authenticate is called from 20 different places, you can pass in 20 different callback methods.
function foo() {
    if (sessionKey) {
        performTask();
    } else {
        authenciate(function() {
           performTask();
        });
    }
}

function authenticate(callback) {
    $.post(url, function(data) {
        sessionKey = data.sessionKey;
        if (callback) callback();
    });
}

A: JQuery's AJAX calls have callback functions (success and error). You can pass in the after-authentication action as the callback to do it after authentication has completed.
Alternately, you can set am option to make the calls synchronous.
Sorry for not linking to the documentation; I'm posting from my phone. Just google "jquery.ajax" to find the documentation.
*EDIT:*As a response to your edit, you could give your authenticate method a parameter to use as a callback function if you want to change what happens after the call (or do nothing) on a case-by- case basis.

A: Check this question: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
It has an example of doing AJAX synchronously. Basically you pass an async:false param, and might require using the ajax() method instead of the post() shortcut to it.
Update:
Another thing you can do is wrap the whole thing in a function like:
function foo() {
    authenciate(function() {
       performTask();
    });
}

function authenticate(callback) {

    if (!callback) { return; }

    if (sessionKey) {
        callback();
    } else {
        $.post(url, function(data) {
            sessionKey = data.sessionKey;
            callback();
        });
    }
}


text:
Q: Bijectivity of a trigonometric function
Let $f : (-1,1)\to (-\pi/2,\pi/2)$ be the function defined by $f(x)= \tan^{-1}\left(\frac{2x}{1-x^2}\right)$ the verify that $f$ is bijective

To check objectivity I assumed 2 variables $x$ and $y$ to be equal and so as to prove $f(x)=f(y)$. But I couldn't do so. I also wish to prove surjectivity.

A: I guess that $f(x)= \arctan(\frac{2x}{1-x^2}).$ I am right ?
Now, if $x,y \in (-1,1)$ and $f(x)=f(y)$, then we have to show that $x=y.$ We get $\frac{2x}{1-x^2}=\frac{2y}{1-y^2}, $ since $\arctan$ is strictly increasing.
This gives $x-y=xy(y-x)$. Now suppose that $x \ne y.$ Then we have $xy=-1$. But this is impossible, since  $x,y \in (-1,1)$, hence $x=y.$

A: Let
$$
f(x)=\arctan\frac{2x}{1-x^2},\qquad g(x)=\frac{2x}{1-x^2}
$$
The derivative is
$$
f'(x)=\frac{1}{1+g(x)^2}g'(x)
$$
Now
$$
1+g(x)^2=1+\frac{4x^2}{(1-x^2)^2}=\frac{(1+x^2)^2}{(1-x^2)^2}
$$
and
$$
g'(x)=2\frac{1-x^2+2x^2}{(1-x^2)^2}
$$
which means that
$$
f'(x)=\frac{(1-x^2)^2}{(1+x^2)^2}\frac{2(1+x^2)}{(1-x^2)^2}=\frac{2}{1+x^2}
$$
which is positive. Since
$$
\lim_{x\to-1^+}f(x)=-\frac{\pi}{2},\qquad\lim_{x\to-1^-}f(x)=\frac{\pi}{2}
$$
you're done.
By the way, this shows that, for $x\ne\pm1$,
$$
f(x)=\begin{cases}
c_++2\arctan x & x>1 \\[4px]
c_0+2\arctan x & -1<x<1 \\[4px]
c_-+2\arctan x & x<-1
\end{cases}
$$
Then $c_0=0$, by evaluating at $0$. Since the limits of $f$ at $\pm\infty$ are $0$, we get that $c_+=-\pi$ and $c_-=\pi$.

A: $$\forall x\in(-1,1):\left(\frac x{1-x^2}\right)'=\frac{1+x^2}{(1-x^2)^2}>1$$
and
$$\forall t:(\arctan(t))'=\frac1{1+t^2}>0.$$
Both functions are monotonous and continous.


text:
Q: Having problems with my WIFI and Android phones Using the WiFi with my phones has been frustrating lately (a problem I don't have with my laptop, maybe because it has a bigger antenna?). My setup is based on a Netgear WNR3500v1 router and 2 Android phones (a Nexus One and a Galaxy Nexus).
The curious thing is the signal strength seems good throughout my house, going from -40dBm to [even] -90dBm at some points (these last ones I consider dark spots). These all led me to believe signal levels could not be the issue so I installed fing on my android phone and ran a ping to my router these are the results FROM less than 6FT away and direct line of sight to router:
Average Ping: 3ms
Packet loss: 35%
Minimum Ping: 1ms
Maximum Ping: 18ms
Std. dev. ping: 0ms
Estimated hops: 0

The router is sitting on a glass table next to my 42" LCD TV, could the LCD be creating interference? (the above test was done with the TV off)
So here are my questions:

*

*Should I be on the market for a new router?

*Could this be an issue with Android? (I don't have other devices to test)

*Does anyone know what 'Std. dev. ping: 0ms' means?

A: Have you scanned other Wifi networks around you? It could be the channel you're broadcasting from is over-saturated. If so, you can change your Router's channel which may help. If you're not sure how to check nearby wireless channels, inSIDDer is a tool that can help.

A: I have a similar problem. But in my case I was able to compare performance with two identical phones. The second phone was one I bought on ebay for peanuts because it had a cracked screen but I figured it would be good for trying out different ROMs and replacement screens are pretty cheap for this model (Lenovo K3 Note).
While my first phone works fine on Wifi all round the flat, the one I got from Ebay gets really poor wifi performance when it is not near the router. So there would seem to be some kind of hardware fault in the second phone.
Also, check which wifi standard your laptop and your phone are using. Maybe one is on 5 GHz while the other is on 2.4 GHz. I think your router does both (as does mine).


text:
Q: Best way to handle pipes and their exit status in a makefile If a command fails in make, such as gcc, it exits...
gcc
gcc: fatal error: no input files
compilation terminated.
make: *** [main.o] Error 4

However, if I have a pipe the exit status of the last command in the pipe is taken. As an example, gcc | cat, will not fail because cat succeeds.
I'm aware the exit codes for the whole pipe are stored in the PIPESTATUS array and I could get the error code 4 with ${PIPESTATUS[0]}. How should I structure my makefile to handle a piped command and exit on failure as normal?

As in the comments, another example is gcc | grep something. Here, I assume the most desired behavior is still for gcc and only gcc to cause failure and not grep if it doesn't find anything.

A: You should be able to tell make to use bash instead of sh and get bash to have set -o pipefail set so it exits with the first failure in the pipeline.
In GNU Make 3.81 (and presumably earlier though I don't know for sure) you should be able to do this with SHELL = /bin/bash -o pipefail.
In GNU Make 3.82 (and newer) you should be able to do this with SHELL = /bin/bash and .SHELLFLAGS = -o pipefail -c (though I don't know if adding -c to the end like that is necessary or if make will add that for you even when you specify .SHELLFLAGS.
From the bash man page:

The return status of a pipeline is the exit status of the last
  command, unless the pipefail option is enabled. If pipefail is
  enabled, the pipeline's return status is the value of the last
  (rightmost) command to exit with a non-zero status, or zero if all
  commands exit successfully. If the reserved word ! precedes a
  pipeline, the exit status of that pipeline is the logical negation of
  the exit status as described above. The shell waits for all commands
  in the pipeline to terminate before returning a value.

A: I would go for pipefail. But if you really don't want (or if you want to only fail on the first process -- not in case of failure from the rest of the pipe):
SHELL=bash

all:
        gcc | cat ; exit "$${PIPESTATUS[0]}"

The only advantage compared to @jozxyqk self answer is that you don't loose the exit status code.

A: Just add in the begin of your makefile the command:
SHELL=/bin/bash -o pipefail

Now you can, for example, generate the errors.err file from objects (1st rule) without being worried it would be overwritten by the executable (2nd rule).
%.o : %.c
    gcc $(CFLAGS) $(CPPFLAGS) $^ -o $@ 2>&1 | tee errors.err

%.x : %.o $(OBJECTS)
    gcc $(LDLIBS) $^ -o $@ 2>&1 | tee errors.err

Without it, make get no errors from rule 1, and run rule 2, overwriting it. You will end up with only a single line in errors.err stating that there are no object file to run gcc
gcc: error: program.o: No such file or directory

A: A reasonable and portable approach is to refactor your build jobs to use files instead of pipes. For example:
foo:
    gcc >$@.log
    grep success $@.log
    cat $@.log
    rm $@.log

Removing the log file after printing it is obviously not necessary; this is just a general template. The beef is the redirection to replace the pipeline. You could even refactor it to multiple recipes:
foo: foo.tmp foo.log
    grep success $@.log
    mv $< $@
%.tmp %.log:
    gcc -o $*.tmp >$*.log

Properly cleaning up the temporary artefacts and generally managing them is an obvious drawback of this approach.


text:
Q: Probability with marbles and no replacements Two marbles are drawn randomly one after the other without replacement from a jar that contains 4 red marbles, 4 white marbles, and 7 yellow marbles. Find the probability of the following events:
(a) A red marble is drawn first followed by a white marble.
(b) A white marble is drawn first followed by a white marble.
(c) A yellow marble is not drawn at all.

I understand how to do this with replacements but don't understand how to adapt the formula to no replacements

A: red marble drawn first is $4/15$, white marble drawn next is $4/14$ so
a) $4/15$ * $4/14$ = $16/210$ = $8/105$
white marble drawn first is $4/15$, white marble drawn next is $3/14$ so
b) $4/15$ * $3/14$ = $12/210$ = $6/105$ = $2/35$
no yellow marble drawn is $8/15$ * $7/14$
c) = $8/15$ * $7/14$ = $56/210$ = $28/105$ = $4/15$


text:
Q: Regular Expression - rename pictures THE PROBLEM:
1000's pictures with --0.jpg at the end (double hyphen)
Example: toni-like-to-play-football--0.jpg
And I want change the --0.jpg to -0.jpg
It would be easy with my tool (Bulk Rename Utility) to replace all with the normal replacement function: replace --0.jpg with -0.jpg
But unfortunately it is a whole picture set that is continuous until -09
Example:
toni-like-to-play-football--0.jpg
toni-like-to-play-football--1.jpg
toni-like-to-play-football--2.jpg
toni-like-to-play-football--3.jpg
toni-like-to-play-football--4.jpg
toni-like-to-play-football--5.jpg
toni-like-to-play-football--6.jpg
toni-like-to-play-football--7.jpg
toni-like-to-play-football--8.jpg
toni-like-to-play-football--9.jpg

Now i looking for a RegEx which rename --0.jpg --1.jpg --2.jpg  ... --9.jpg
to -0.jpg -1.jpg -2.jpg  ... -9.jpg
At the end there should be only - (one hyphen) and the number.
This would be the result:
toni-like-to-play-football-0.jpg
toni-like-to-play-football-1.jpg
toni-like-to-play-football-2.jpg
toni-like-to-play-football-3.jpg
toni-like-to-play-football-4.jpg
toni-like-to-play-football-5.jpg
toni-like-to-play-football-6.jpg
toni-like-to-play-football-7.jpg
toni-like-to-play-football-8.jpg
toni-like-to-play-football-9.jpg

Hope someone have time to call me the RegEx for this.

A: Unless you've got filenames with -- in the middle of them, the easiest way would be:
Search:   --
Replace: -
If you do have filenames like that then use the following regexp:
Search:  \-\-(\d)
Replace: \-\1
If your number goes above 9 then use this instead:
Search:  \-\-(\d+)
Replace: \-\1.


text:
Q: making http request by ajax or c# In my web application I need to get data from Wikidata, for example to show item's details. I thought about using ajax for this, but was't sure from where I should to call it, so I asked this question.
But after some thinking, why should I use ajax? I can make http request from my server side code (C#). I can put it into controller, get information from Wikidata, fill out ViewModel and then call View(ViewModel).
What can be some downsides of this? Will it affect performance?
So, question is: ajax or C#?
UPDATE: Before development starting I was thinking if I should develop client part (HTML, JavaScript) and Web API separately. In this case I would use Ajax of course. But I decided at this stage I'll do one MVC application. Because it has server side code anyway (even in View), so I think that http request from C# looks more naturally than JavaScript request.

A: Usually the overriding reason for making a 3rd party API call server side is that it requires you to have an account, username and password with the 3rd party.
If you make the call client side then you expose this information to the user of your website/app
There are other reasons to consider, perhaps you merge the api data with some other data you only have serverside, perhaps you have more than one provider for the same data and want to switch between them but still provide the same datamodel to your client etc. perhaps javascript just isn't good enough to run your business logic
But, these are more meta-programming concerns about ease of maintainability etc. given the cost of a server side call and the extra step in the network traffic, if you can push it to the client it is usually a good thing to do.


text:
Q: Randomly sample an array with a fixed number of zeros I have optimized code to randomly sample an array containing -1s, 0s and 1s with probabilities 1/4,1/2,1/4. It looks like
#define n (12)
unsigned int x,y=34353,z=57768,w=1564; //PRNG seeds
/* xorshift PRNG
 * Taken from https://en.wikipedia.org/wiki/Xorshift#Example_implementation
 * Used under CC-By-SA */
u_int32_myRand() {
    unsigned int t;
    t = x ^ (x << 11);
    x = y; y = z; z = w;
    return w = w ^ (w >> 19) ^ t ^ (t >> 8);
}

x=(int)time(NULL); //seed PRNG
unsigned int k
int F[n];
for(k=0; k<n; k++) {
      F[k]=(1-(myRand()&3))%2;
    }

How can I modify this so that it only returns arrays that have exactly n/3 zeros in them and still  have it fast?

A: The easiest way to do this would be to fill the first part of the array with n/3 zeros. Then add as many 1's and -1's as you want. Then, do a Fisher-Yates shuffle to randomize the array.
The problem with trying to "randomly distribute n/3 zeros" is that you have difficulty preventing overlap. That is, if you want to put 33 zeros in an array of 99, you can't just pick 33 random indexes because you're likely to get duplicates. So you'll end up with fewer than 33 zeros in the array.
As for performance, this will be nearly as fast as your current example. It just requires an extra pass over the array. The number of random numbers generated is the same.

A: Proceed in two steps:

*

*Distribute exactly n/3 zeros randomly over your array and set the rest to 1.

*Assign a random sign to the remaining ones to get the desired -1/+1.

Example code:
int F[n];
// fill with 1
for(k=0; k<n; k++) {
    F[k] = 1;
}
// distribute n/3 zeros
for(k=0; k<n/3; k++) {
    // find a location which does not have a 0 yet
    int i;
    do {
        i = myRand() % n;
    } while(F[i] == 0);
    F[i] = 0;
}
// change remaining (non zero) to -1 with 50% probability
for(k=0; k<n; k++) {
    if(F[k] && myRand()%2) F[k] = -1;
}

This has a runtime of around 2.4 n, but I do not think you can get much faster than that.
The while loop in the second for loop is in average executed around 1.2 times for the case of n/3 zeros.

Remark:
Trial and error used in the second for loop works quite well if the success probability is high enough. The number of trials you need in average for a probability of p is 1/p.
In our case (n/3 zeroes) the worst probability to find a good location (i.e. for the last zero) is 2/3, thus in average 1.5 iterations. To find places for all n/3 zeros you need in average around 0.2*n iterations.
The average runtime can be computed as -log(1-a), where a is the percentage of zeroes you want to distribute (in your case a = 1/3).
Some more examples: If you would want to distribute 2/3*n zeros, it would take 1.1*n iterations. For 0.99*n zeroes it is already 4.6*n iterations.
All in average. In the worst case it takes forever.

If you need a runtime guarantee you are perhaps better off by implementing real sampling without reselection, i.e. filling a container with all possible indices, sampling a random element as index and removing it from the container. But this probably has a runtime of around O(n*log(n)). Thus it works good for small n or a large percentage of zeroes.

A: Here is a simple algorithm that will do:

*

*Put the required number of zeros (n/3) into your output array

*For the remaining places, put 1 or -1 with probability 1/2

*Shuffle the array
However:

... array containing -1s, 0s and 1s with probabilities 1/4,1/2,1/4

Does it mean that there are exactly n/4 1's in the array? Let's assume it doesn't. Then:

*

*Count the number of 1's (a) and -1's (b) in your array

*Probability for 1 is a/(a+b); use it in the above algorithm instead of 1/2
Note: if there are only zeros, or no zeros at all, in your input array - sampling with exactly n/3 zeros is impossible!


text:
Q: Best Practice for Password Reset in ASP.NET MVC I'm looking to emulate the password reset flow from www.live.com.  That is (skip email option for now):
1) Screen asking/confirming the username
2) Ask reset method (account verification or email reset)
3) Gather account info and verify it
4) Present user with a password reset inputs.
So I was looking for any tips on how to do this a proper way.  I planned on having each 'step' post back to the same action and build up the model as I go (putting properties/fields into hidden inputs or regular inputs based on the step I was on).  Then on step 4, I'd re-verify the account information (just in case someone tried to hack and post directly to step for with username and new password).
This would all be done over SSL and the only drawback I can see is that for step 4, I would be rendering the users 'secret question answer' in an hidden input so it could be submitted/validated again before completing the password reset.
Is this the proper way to implement this screen or are there some security holes I'm not seeing?

A: I'm no expert at this, but I like the idea in this related question. Use a hash to identify the user during step 4 instead of sending their secret answer through a round trip.


text:
Q: How much of this task can/should be done in SQL? I have a database where I would like to construct a result that match my indata.
Explanation of examples:
"Indata" is a row with criteria for the filter in step #1, see below.
"Results after filter #1" is the rows left after step #1
"Results after filter #2" is the rows left after step #2
"Print for indata 1" is the end result, presenting the contect of field OutData after the second filtering, along with the combined content of field "Warn"
Step #1. Filter the Outdata table to only keep records matching Indata. Star * is matching anything. Each row must match the indata row. See examples.
Step #1b. Indata Depl is not matched directly but checked to be in the range OutData
Depl-DeplOffMin>Indata Depl

Step #2. Filter Outdata table again, to only keep unique rows for each Pos, select the row with lowest Mismatch when duplicates exist. See examples.
Step #3. Create all possible combinations of the Outdata Field, with unique Pos. Like LOOP: OutData for first Pos=10 + OutData for first Pos=20 + OutData for first Pos=30 + OutData for first Pos=30, see "Print" lines in the examples.
Step #4. Sort the output combinations ie the "Print" lines, to have lowest mismatch on the top. See examples.
Would you try to do this as one big SQL query, or build temporary tables etc mixing it with PHP doing more of the work?
(The real database is perhaps 1000rows and 30 fields in MySQL.  The Indata is sent to the server via Ajax and the server code in PHP generates the Print data and sends it back.)
"Outdata" table, example:

Pos   OutData     Warn  Mismatch    Producer    Depl        DeplOffMax        DeplOffMin  Axis        Connection
10    S                 0           S           *           *                 *                       *           *
20    24                0           S           24          *                 *           *           *
20    24          +-5   5           S           24          5                 -5          *           *
20    24          +-10  10          S           24          10                -10         *           *
20    48                0           S           48          *                 *           *           *
30    AA                0           S           *           *                 *           A           *
30    AB                0           S           *           *                 *           B           *
30    AC                0           S           *           *                 *           C           *
30    AA          B-AA  5           S           *           *                 *           B
40    C1                0           S           *           *                 *           *           C1
40    C1                1           S           *           *                 *           B           *
40    C1                2           S           24          10                -10         *           *
40    C2                0           S           *           *                 *           *           C2

Example 1:
Indat 1:                           S           24                                        A           C2

Result for indata 1 after filter #1:
10    S                 0           S           *           *                 *                       *           *
20    24                0           S           24          *                 *           *           *
20    24          +-5   5           S           24          5                 -5          *           *
20    24          +-10  10          S           24          10                -10         *           *
30    AA                0           S           *           *                 *           A           *
40    C1                2           S           24          10                -10         *           *
40    C2                0           S           *           *                 *           *           C2

Result for indata 1 after filter #2:
10    S                 0           S           *           *                 *                       *           *
20    24                0           S           24          *                 *           *           *
30    AA                0           S           *           *                 *           A           *
40    C1                2           S           24          10                -10         *           *
40    C2                0           S           *           *                 *           *           C2

Print for indata 1:
Mismatch 0:       S 24 AA C2  Warning -
Mismatch 2:       S 24 AA C1  Warning -

Example 2:
Indata 2:                           S           33                                        B           C2

Result for indata 2 after filter #1:
10    S                 0           S           *           *                 *                       *           *
20    24          +-10  10          S           24          10                -10         *           *
30    AB                0           S           *           *                 *           B           *
30    AA          B-AA  5           S           *           *                 *           B
40    C1                1           S           *           *                 *           B           *
40    C1                2           S           24          10                -10         *           *
40    C2                0           S           *           *                 *           *           C2

Result for indata 2 after filter #2:
10    S                 0           S           *           *                 *                       *           *
20    24          +-10  10          S           24          10                -10         *           *
30    AB                0           S           *           *                 *           B           *
30    AA          B-AA  5           S           *           *                 *           B
40    C1                1           S           *           *                 *           B           *
40    C2                0           S           *           *                 *           *           C2

Print for indata 2:
Mismatch 10:      S 24 AB C2  Warning: +-10
Mismatch 11:      S 24 AB C1  Warning: +-10
Mismatch 15:      S 24 AA C2  Warning: +-10 B-AA
Mismatch 16:      S 24 AA C1  Warning: +-10 B-AA

Example 3:
Indata 3:                           S           28                                        B           C1

Result for indata 3 after filter #1:
10    S                 0           S           *           *                 *                 *           *
20    24          +-5   5           S           24          5                 -5          *           *
20    24          +-10  10          S           24          10                -10         *           *
30    AB                0           S           *           *                 *           B           *
30    AA          B-AA  5           S           *           *                 *           B
40    C1                0           S           *           *                 *           *           C1
40    C1                1           S           *           *                 *           B           *
40    C1                2           S           24          10                -10         *           *

Result for indata 3 after filter #2:
10    S                 0           S           *           *                 *                 *           *
20    24          +-5   5           S           24          5                 -5          *           *
30    AB                0           S           *           *                 *           B           *
30    AA          B-AA  5           S           *           *                 *           B
40    C1                0           S           *           *                 *           *           C1

Print for indata 3:
Mismatch 5:       S 24 AB C1  Warning: +-5
Mismatch 10:      S 24 AA C1  Warning: +-5 B-AA

A: First, the question is too long.
Second, the rules (#1, #1b, #2, #3, and #4) are confusing and need clarification.
However, in spite of that, this is my advice.
If it's not obvious how to do it in SQL, don't.
For something like this, with "rules" for matching ("star is matching anything", "select the row with lowest Mismatch when duplicates exist", etc.) you have two choices.

*

*Simplify the processing steps so that they can be implemented in SQL.  This is generally a good thing.  Your current statement is confused and hard to follow.  Time spent simplifying would be time well spent.

*Use an ordinary programming language.  When you reach things which are hard to do in SQL, don't "force" them.  Get the data from SQL and process it in PHP.
SQL -- generally -- is slow.  It's best used when you have vast volumes of data that won't fit in memory and you have transactional updates going on.  1000 rows and 30 fields is a trivial amount of data that easily fits in memory.  If you're given a batch of data to analyze (with no updates going on) SQL's not helping much.
In a very busy website -- using PHP -- you may have problems with lots of concurrent users.  In which case, get it out of PHP so it's not running under Apache.  Until such time as Apache runs out of memory, just do it in PHP.

A: I have no idea what step 3 means, but all the other steps can be done in SQL, also, they probably should be done in SQL where its a lot more efficient.
I assume from your tags that you're using a MySQL database (it would have been helpful to know).
My initial thots would be somethnig along the lines of:
 SELECT outdata.Pos,
     outdata.OutData,
     outdata.Warn,
     MIN(outdata.Mismatch),
     outdata.Producer,
     outdata.Depl,
     outdata.DeplOffMax,
     outdata.DeplOffMin,
     outdata.Axis
     outdata.Connection
 FROM outdata, indata
 WHERE
   (//some nasty type juggling here
     outdata.depl='*'
     OR outdata.deploffmin='*'
     OR indata.depl='*'
     OR (
        outdata.depl<>'*'
        AND outdata.deploffmin<>'*'
        AND indata.depl<>'*'
        AND outdata.depl-outdata.deploffmin>indata.depl
     )
   )
 AND ( outdata.outdata=indata.outdata
   OR outdata.outdata='*'
   OR indata.outdata='*' )
 AND ( outdata.connection=indata.connection
   OR outdata.connection = '*'
   OR indata.connection='*' )
 AND (outdata.axis=indata.axis
   OR outdata.axis='*'
   OR indata.axis='*' )
 ....repeat for all the fields you want to match
 GROUP BY outdata.Pos,
     outdata.OutData,
     outdata.Warn,
     outdata.Producer,
     outdata.Depl,
     outdata.DeplOffMax,
     outdata.DeplOffMin,
     outdata.Axis
     outdata.Connection
 ORDER BY 4 ASC;

Simples.
C.

A: I don't fully understand the business logic, but for such a tiny amount of data I would not bother going through the pain of trying to implement in SQL. It is likely to be faster just pulling all the data over and using PHP to apply your filters.

A: One thing I've learned. Anything that can be calculated should not be saved in the database


text:
Q: Merge Two Lists LeetCode I've solved the problem on Repl.it website, but when I submitted the code on LeetCode it gave a typeError, that I'm going to paste it here:
Line 29 in solution.js
         throw new TypeError(__serialize__(ret) + " is not valid value for the expected return type
ListNode");
         ^
TypeError: [] is not valid value for the expected return type ListNode
Line 29: Char 20 in solution.js (Object.<anonymous>)
Line 16: Char 8 in runner.js (Object.runner)
Line 13: Char 26 in solution.js (Object.<anonymous>)
Line 1200: Char 30 in loader.js (Module._compile)
Line 1220: Char 10 in loader.js (Object.Module._extensions..js)
Line 1049: Char 32 in loader.js (Module.load)
Line 937: Char 14 in loader.js (Function.Module._load)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
Line 17: Char 47 in run_main_module.js

And here's the code:
var mergeTwoLists = function(l1, l2) {
  let i = 0, j = 0;
  var out = [];
  while(i < l1.length || j < l2.length) {
    if(j == l2.length || i < l1.length && l1[i] < l2[j]) {
      out.push(l1[i++]);
    } else {
      out.push(l2[j++]);
    }
  }
  return out;
};

I really don't know where the problem is... if someone could help I would be grateful

A: This is a Linked List merge question, not a regular array merging. This'd pass through:
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    var dummy = {
      val : -1,
      next : null
    };
    var curr = dummy;
    while (l1 && l2) {
        if (l1.val > l2.val) {
            curr.next = l2;
            l2 = l2.next;
        } else {
            curr.next = l1;
            l1 = l1.next;
        }
        curr = curr.next;
    }

    curr.next = l1 || l2;

    return dummy.next;
};

This is how your list would look like:
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

References

*

*For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.

If you are preparing for interviews:

*

*We'd write bug-free and clean codes based on standards and conventions (e.g., c1, 2, c++1, 2, java1, 2, c#1, 2, python1, javascript1, go1, rust1).


text:
Q: WPF TabItem and TabControl templates combined I'm trying to make template for TabControl
visual design should be following:
TabControl content area should have small shadow over TabItems
but shadow should not be applied to active tab item
problem is that I can only write these templates as separated styles
meaning that if I use grid they'll end up in different grids and I can't change Zindex to make only one TabItem pop out over shadow
I'm using Border to apply shadow
<Border BorderThickness="0" >
  <Border.Effect>
    <DropShadowEffect Direction="90" ShadowDepth="1" Color="#b6b6b6" />
  </Border.Effect>
</Border>

A: You could get something similar by changing the background color to a gradient on the TabItem:
<Style TargetType="TabItem">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="False">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Color="#eeeeee" Offset="0.0"/>
                        <GradientStop Color="#eeeeee" Offset="0.6"/>
                        <GradientStop Color="#b6b6b6" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

A: I came up with this, using the Kaxaml template for a TabControl, it incorporates Adrian's idea of using a LinearGradientBrush to simulate the shadow, I'm using a ControlTemplate:
<TabControl>
            <TabControl.Resources>
                <LinearGradientBrush x:Key="myBrush" StartPoint="0,0" EndPoint="0,1">
                    <GradientStop Color="#ffffff" Offset="0.0"/>
                    <GradientStop Color="#eeeeee" Offset="0.46"/>
                    <GradientStop Color="#787878" Offset="1"/>
                </LinearGradientBrush>

                <Style  TargetType="{x:Type TabControl}">
                    <Setter Property="OverridesDefaultStyle" Value="True" />
                    <Setter Property="SnapsToDevicePixels" Value="True" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabControl}">
                                <Grid KeyboardNavigation.TabNavigation="Local">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="*"/>
                                    </Grid.RowDefinitions>
                                    <TabPanel Name="HeaderPanel" Grid.Row="0" Panel.ZIndex="1" Margin="0,0,0,-1"  IsItemsHost="True"
                                              KeyboardNavigation.TabIndex="1" Background="{StaticResource myBrush}" />
                                    <Border Name="Border" Grid.Row="1" Background="#FFFFFF"  BorderBrush="#888888" BorderThickness="1"
                                            KeyboardNavigation.TabNavigation="Local" KeyboardNavigation.DirectionalNavigation="Contained" KeyboardNavigation.TabIndex="2" >
                                        <ContentPresenter Name="PART_SelectedContentHost" Margin="4" ContentSource="SelectedContent" />
                                    </Border>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter Property="Foreground" Value="#888888" />
                                        <Setter TargetName="Border" Property="BorderBrush" Value="#AAAAAA" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>

                <!-- SimpleStyles: TabItem -->
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Margin="0,0,-4,0" Background="#E0E0E0" BorderBrush="#888888" BorderThickness="1,1,1,1" >
                                        <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                          ContentSource="Header" Margin="12,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="False">
                                        <Setter Property="Panel.ZIndex" Value="100" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                        <Setter TargetName="Border" Property="Background" Value="{StaticResource myBrush}" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#EEEEEE" />
                                        <Setter TargetName="Border" Property="BorderBrush" Value="#AAAAAA" />
                                        <Setter Property="Foreground" Value="#888888" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TabControl.Resources>
            <TabItem Header="Test" />
            <TabItem Header="Test2" />
            <TabItem Header="Test3" />
            <TabItem Header="Test4" />
        </TabControl>

By way of an explanation.
The LinearGradientBrush myBrush will be used in two places, the first is in the TabControl, as the Background:
<TabPanel Name="HeaderPanel" Grid.Row="0" Panel.ZIndex="1" Margin="0,0,0,-1"  IsItemsHost="True"
                                              KeyboardNavigation.TabIndex="1" Background="{StaticResource myBrush}" />

The Second is within the TabItem template as the background for all items that aren't selected *using a trigger); you could add additional selected styles if required:
<Setter TargetName="Border" Property="Background" Value="{StaticResource myBrush}" />

Note: I've changed the background of the TabControl so it's no longer transparent (so it has the shadow. This might fall flat on it's face depending on how you want to use the control (i.e. if you want to show content underneath).
Before this version, I had a different version that used a DropShadow and a clipping grid, which will retain the underlying transparency if you need it. It does rely on you manually matching the gradient brush with the DropShadow. Let me know if you need that other version and I'll post it.
Good luck.


text:
Q: UIButton background image from color for different states I am trying to create a UIButton subclass and have the selected and disabled state background image from color. The UIButton will be with rounded edges self.layer.cornerRadius = self.frame.height/2
class RoundedButton: UIButton {

public var shadowOffset: CGSize = CGSize(width:0, height:0) {
    didSet{
        self.layer.shadowOffset = shadowOffset
    }
}

public var shadowRadius: CGFloat = 0.0 {
    didSet{
        self.layer.shadowRadius = shadowRadius
    }
}

public var shadowOpacity: Float = 1.0 {
    didSet{
        self.layer.shadowOpacity = shadowOpacity
    }
}

public var shadowColor: UIColor = UIColor.black {
    didSet{
        self.layer.shadowColor = shadowColor.cgColor
    }
}

public var selectedBackgroundColor: UIColor = UIColor.black

override func layoutSubviews() {
    super.layoutSubviews()
    self.layer.cornerRadius = self.frame.height/2

    self.setBackgroundImage(getImageWithColor(color: selectedBackgroundColor, size: self.frame.size, cornerRadius: self.frame.height/2), for: .selected)
}

func getImageWithColor(color: UIColor, size: CGSize, cornerRadius: CGFloat?) -> UIImage? {
    let rect = CGRect(x:0, y:0, width:size.width, height:size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()

    if cornerRadius != nil {
        UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius!).addClip()
    }

    UIRectFill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

}

It does not work when I select the button (I do change the state when the button is tapped) the weird think is that the button detect only the first time is being tapped. Another weird behaviour is that If I assign a normal UIImage (not created by core graphics) it works so maybe something wrong with the images generated.
Note that I need to combine shadow, corner radius and being able to have different background button states color from UIColor.

A: You didn't set background image for other states: .normal, .disabled in your case. You also do not need to set the image in layoutSubviews function. Simply override the initializer and set background images for all states there.
Alternative you can observe isSelected, isHighlighted etc. and simply set the backgroundColor property of your button.


text:
Q: ASP.NET MVC 4 Custom View Routing in Sitefinity 7 Our solution hierarchy is as follows:
language/doctor-cv/doctorMcr/doctorFullName
Ex: en\doctor-cv\12345\David
Now I'd like to map the routing so that when the user just types the name of the view in the url, it automatically maps the url to the corresponding controller
I.E: localhost:1234\en\doctor-cv\12345\David
Should map to
View\DoctorCVPage\Index.cshtml
Currently, we're using the default routing
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapHttpRoute(
          name: "DoctorCVPage",
          routeTemplate: "{language}/doctor-cv/{doctorMcr}/{doctorFullName}",
          defaults: new
                        {
                            controller = "DoctorCVPage",
                            action = "Index",
                            doctorMcr = UrlParameter.Optional,
                            doctorFullName = UrlParameter.Optional,
                            language = UrlParameter.Optional
                        });

Here is MyController
public class DoctorCVPageController : BaseController
{
            /// <summary>
            /// Gets or sets the message.
            /// </summary>
            [Category("String Properties")]
            public string Message { get; set; }

            /// <summary>
            /// This is the default Action.
            /// </summary>
            public ActionResult Index(string doctorMcr)
            {
                var id = "";
                ViewBag.PageTitleLink = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
            }
    }

And then in my view I have a  tag.
<a href="/en/doctor-cv/${DoctorMcr}/${DoctorName}"/>

After user click on this  tag, system should to redirect to DoctorCVPage/Index (controller: DoctorCVPage, Action = Index), but it can't do this.
Please helps me know why, thank for all helps.

A: Please follow this way, I think it can help you handle that thing.
 protected override void HandleUnknownAction(string actionName)
    {
        UrlDetail = Request.Url != null ? Request.Url.ToString() : string.Empty;

        Response.StatusCode = (int)HttpStatusCode.OK;
        this.ActionInvoker.InvokeAction(this.ControllerContext, "Index");
        return;
    }

public ActionResult Index()
    {
        return;
    }

Hope this way can help you.

A: It's not working because any URL in Sitefinity will be routed to a page. Your widget is not a page, but on the page. What you have to do is override the HandleUnknownAction method and parse the URL there, then take the appropriate action.
For example
protected override void HandleUnknownAction( string actionName )
{
    if (!RouteHelper.GetUrlParametersResolved())
    {
        this.Response.StatusCode = (int)HttpStatusCode.NotFound;
    }
    else
    {
        this.Response.StatusCode = (int)HttpStatusCode.OK;
        List<string> segments = RouteHelper.SplitUrlToPathSegmentStrings( Request.Url.LocalPath, true )
                                           .Skip(1)
                                           .ToList();
        ViewBag.PageTitleLink = String.IsNullOrEmpty(segments.ElementAt(2)):String.Empty:segments.ElementAt(2);
        var lang = segments.ElementAt(0);
        // etc

        View( "Index", model ).ExecuteResult( this.ControllerContext );
    }
}

This relies on the position of the url segments being consistent, but it works well otherwise. This is the only way I have found to deal with the requirements you have. Also notice that this is a Void method, so you have to execute the view, as shown.


text:
Q: How to solve property error when trying to convert multiple ranges into values? All, I'm new to VBA and am teaching myself... I am getting a property error when trying to change a range's formulas... the range can be found at the bottom of the code. How do you make these cells turn to values without throwing an error?
Sub InvestorModelMacro()

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    DisplayGridlines = False

    Dim r As Range, ws As Worksheet

    For Each r In Worksheets("Asset Dashboard").Range("C6:C9")   'go through each cell in DV list
        If Len(r) > 0 Then                                       'only do something if cell not empty
            Worksheets("Live").Range("D3").Value = r.Value        'transfer value to cell D3 of 'Live' tab
            Application.Calculate
            Set ws = Worksheets.Add                               'add new sheet
            ws.Name = Worksheets("Investor Model").Range("D3")    'renames new sheet after selected asset
            Worksheets("Investor Model").Cells.Copy
            ws.Range("A1").PasteSpecial xlFormulas                'copy values only from Investor Model to new sheet
            ws.Range("A1").PasteSpecial xlFormats                 'copy formats only from Investor Model to new sheet
            ActiveWindow.DisplayGridlines = False                 'turns off gridlines
            ws.Range("F46:G52,G54,G56:G58,G60:G61,G65:G72,G75:G80,G87,G89:G92").Values
            ws.Range("F46:G52,G54,G56:G58,G60:G61,G65:G72,G75:G80,G87,G89:G92").Font.Color = vbBlue

        End If
    Next r

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

A: At most you can use Areas
Dim Area As Range
'...
For Each Area In ws.Range("F46:G52,G54,G56:G58,G60:G61,G65:G72,G75:G80,G87,G89:G92").Areas
    Area.Value = Area.Value
    Area.Font.Color = vbBlue
Next Area