Q: Error in datatable select statement in c# I have a SELECT statement I'm running on a data table. The problem is that it gives me the error "the expression contains an invalid string constant". I know it has to do with the single quote at the end of my query but i cannot think of why its not working. Here is the code:
DataRow[] foundRow = dt.Select("Student='" + Student.ID + "' AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'");

A: This looks like a classic SQL injection problem. What if the description contains a single apostrophe i.e. "Wasn't available", this will break your code. In addition, if Student is an integer value (i.e. it is an integer/auto-incrementing ID or equivalent in your DB) it should not be wrapped in quotes, giving you -
DataRow[] foundRow = dt.Select("Student=" + Student.ID + " AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'");


Q: getting syntax error name 'parameters' is not defined? i have written a python script but when i try to run it in arcmap i get a syntax error:

I cant understand where the problem is.
This code is not complete yet. I want to achieve two things from the code

*

*give two inputs and then calculate Fault_loc. If that answer is equal to objectid of input then take corresponding X and Y values from the table and store it in output's attribute table.

*second part which i am working on is to create a POINT layer and show that X and Y Pointon the map.

But first i want to fix the syntax error i am geting
Here is my code:
import arcpy

import os

class Toolbox(object):

    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Pin point1"
        self.alias = "alonglines1"

        # List of tool classes associated with this toolbox

        self.tools = [PinPointFaultLocationpp]

class PinPointFaultLocationpp(object):

    def __init__(self):
        self.label = "PinPointFaultLocationpp"
        self.description = "pin points the fault location."
        self.canRunInBackground = True

    def getParameterInfo(self):
        """Define parameter definitions"""
        in_features = arcpy.Parameter(
            displayName="Input HV Line Feature",
            name="in_HV_Lines",
            datatype="Feature Layer",
            parameterType="Required",
            direction="Input")
        in_features.filter.list = ['Polyline']

        out_point = arcpy.Parameter(
            displayName="Output Point Feature Class",
            name="Fault location",
            datatype="Feature Class",
            parameterType="Required",
            direction="Output")

        Fault_distance = arcpy.Parameter(
            displayName="Fault_distance (units are in units of input)",
            name="Fault_distance",
            datatype="Double",
            parameterType="Required",
            direction="Input")

        distance_between_points = arcpy.Parameter(
            displayName="distance between points (units are in units of input)",
            name="distance_between_points",
            datatype="Double",
            parameterType="Required",
            direction="Input")

        params= [in_features, out_point, Fault_distance, distance_between_points]
        return

    def isLicensed(self):
        return True

    def updateParameters(self, parameters):
        parameters[1].parameterDependencies = [parameters[0].name]
        parameters[1].schema.clone = True
        parameters[1].schema.geometryTypeRule = "AsSpecified"
        parameters[1].schema.geometryType = "Point"
        parameters[1].schema.fieldsRule = "FirstDependencyFIDs"
        parameters[1].schema.fieldsRule = "None"

        id_field = arcpy.Field()
        id_field.name = "Xpoint_output"
        id_field.type = "Double"

        id_field1= arcpy.Field()
        id_field1.name="Ypoint_output"
        id_field1.type="Double"

        parameters[1].schema.additionalFields = [id_field]
        parameters[1].schema.additionalFields = [id_field1]
        return

    def updateMessages(self, parameters):
        """Provide error messages if interval is invalid"""
        """Provide error messages if interval is invalid"""

        err_value = "Distance value cannot be a negative number"

         # percentage
        if parameters[2].value < 0.0:
                parameters[2].setErrorMessage(err_value)

        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
    in_fc = parameters[0].valueAsText
    out_fc = parameters[1].valueAsText
    Fault_distance = parameters[2].value
    distance_between_points  = parameters[3].value
    fault_loc=fault_distance/distance_between_points

    desc = arcpy.Describe(in_fc)
        #http://pro.arcgis.com/en/pro-app/arcpy/get-started/describing-data.htm

        # Create output feature class
    arcpy.CreateFeatureclass_management(
            os.path.dirname(out_fc),
            os.path.basename(out_fc),
            geometry_type="POINT",
            spatial_reference=desc.spatialReference)
            #http://pro.arcgis.com/en/pro-app/tool-reference/data-management/create-feature-class.htm

        # Add a field and transfer X value from input to output
        fid_name="Xpoint_output"
        fid_name1="Ypoint_output"

    arcpy.AddField_management(out_fc, fid_name, "LONG")
    arcpy.AddField_management(out_fc,fid_name1,"Long")

    #input file coloumns
    field_name = 'OBJECTID'
    field_name1= 'X'
    field_name2= 'Y'

    with arcpy.da.SearchCursor(
                in_fc) as search_cursor:
            with arcpy.da.InsertCursor(
                    out_fc) as insert_cursor:
                for row in search_cursor:
                    if row.getValue(field_name)== Fault_loc:
                         x=row.getValue(field_name1)
                         y=row.getValue(field_name2)
                         insert_cursor.insertRow(row)

A: First thing is to be very careful with indentation; the code you have listed looks fine until the def execute.  I hope that is just a paste issue.  If not, make sure to properly indent all the code under that method definition.
My guess as to the issue is for the def getParameterInfo(self): you must return the params array:
params= [in_features, out_point, Fault_distance, distance_between_points]
return params

You have just a return.

A: Fix the indention for your execute function.
 def execute(self, parameters, messages):
        """The source code of the tool."""
        in_fc = parameters[0].valueAsText
        out_fc = parameters[1].valueAsText
        Fault_distance = parameters[2].value
        distance_between_points  = parameters[3].value
        fault_loc=fault_distance/distance_between_points

        desc = arcpy.Describe(in_fc)
            #http://pro.arcgis.com/en/pro-app/arcpy/get-started/describing-data.htm

            # Create output feature class
        arcpy.CreateFeatureclass_management(
                os.path.dirname(out_fc),
                os.path.basename(out_fc),
                geometry_type="POINT",
                spatial_reference=desc.spatialReference)
                #http://pro.arcgis.com/en/pro-app/tool-reference/data-management/create-feature-class.htm

            # Add a field and transfer X value from input to output
            fid_name="Xpoint_output"
            fid_name1="Ypoint_output"

        arcpy.AddField_management(out_fc, fid_name, "LONG")
        arcpy.AddField_management(out_fc,fid_name1,"Long")

        #input file coloumns
        field_name = 'OBJECTID'
        field_name1= 'X'
        field_name2= 'Y'

        with arcpy.da.SearchCursor(
                    in_fc) as search_cursor:
                with arcpy.da.InsertCursor(
                        out_fc) as insert_cursor:
                    for row in search_cursor:
                        if row.getValue(field_name)== Fault_loc:
                             x=row.getValue(field_name1)
                             y=row.getValue(field_name2)
                             insert_cursor.insertRow(row)


Q: JTextArea & JPanel different classes one window...is it possible? So i have two classes:
public class TimeServer extends JPanel implements TimeVariables
{

public TimeServer()
{

    JTextArea serverLog = new JTextArea();
    // Create a scroll pane to hold text area
    JScrollPane scrollPane = new JScrollPane(serverLog);

    JPanel serverWin = new JPanel();

    serverWin.add(scrollPane);

}

and another class that has:
private JPanel mainWin = new JPanel();
private JPanel gridArea = new JPanel(); //hold cells

TimeServer serverWin = new TimeServer();

public class TimClient extends JFrame implements Runnable, TimeVariables
{
    his.add(mainWin, BorderLayout.CENTER);
    mainWin.setLayout(new BorderLayout());
   // mainWin.setLayout(new GridLayout(1,2));

    //Create Grid
    gridArea.setLayout(new GridLayout(10, 10, 2, 2));

    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            gridArea.add(cell[i][j] = new Cell(i, j, this));

    gridArea.setBorder(new LineBorder(Color.black, 1));

    jlblTitle.setHorizontalAlignment(JLabel.CENTER);
    jlblTitle.setFont(new Font("SansSerif", Font.BOLD, 16));
    jlblTitle.setBorder(new LineBorder(Color.black, 1));
    jlblStatus.setBorder(new LineBorder(Color.black, 1));

    mainWin.add(gridArea, BorderLayout.CENTER);
    mainWin.add(serverWin, BorderLayout.PAGE_END);
    // Place the panel and the labels to the frame

    setLayout(new BorderLayout()); // implicit anyway

    add(jlblTitle, BorderLayout.NORTH);
    add(mainWin, BorderLayout.CENTER);
    add(jlblStatus, BorderLayout.SOUTH);
}

public static void main(String[] args) {

    // Create a frame
    TimClient frame = new TimClient("Time Client");
    //frame.getContentPane().add(BorderLayout)

    // Display the frame
    frame.setSize(620, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

all i want to do is keep the server log and grid in the JPanel next to one another, could you explain how?
also how do i add the JPanel in the server class to the one in client?
Here's a sketch of how i'd like it to look:

A: Your problems above appear to stem from a bad Swing code practice, one that seems to be reinforced by Swing code generators (although I'm not sure if you're currently using this tool) and the official Swing tutorials, and that is:

*

*First and foremost, you should avoid having your Swing GUI classes extend JFrame as that unnecessarily paints your GUI code into a corner that requires a bit of effort to get out of.

*Instead gear your Swing GUI code towards making JPanels, panels which now can easily be placed into other JPanels, or into JFrames, JDialogs, JOptionPanes, swapped in CardLayouts,... wherever they are needed.

*Instead, create, fill, and pack your JFrames when they are needed.

So I suggest that you do just this:

*

*change your code above so that the classes do not extend JFrames, and instead create JPanels,

*Create a master JPanel that uses a BorderLayout

*Add your grid to the above, BorderLayout.CENTER

*Add your JTextArea-containing JScrollPane and its JPanel into the master JPanel in the BorderLayout.PAGE_END position.

*Create your JFrame to hold and display the master JPanel.

If you've done a good job of separated your GUI code from your logic code, then it should be easy to re-write the GUI code while keeping your same logic (or "model") code.

Edit 2
Regarding your changed question where now the first class extends JPanel, simply add that JPanel to your JFrame in the BorderLayout.LINE_END end (also known as BorderLayout.EAST) position.


Q: Getting issue with fetching details in mysql Here is my table having tax details:
Image of records in table

I would like to fetch details of a tax record when I have an integer (say, 2500) between the start_range_cost and end_range_cost.
My current SQL using 3000 as an example:
SELECT * FROM `hotel_tax_details`
 WHERE `start_range_cost`>=3000 AND `end_range_cost`<=3000

A: Based solely on the query in your OP and the records in your image nothing would be returned.  It would only return if both start_range_cost AND end_range_cost were exactly 3000 which none of the records match, but this is just because you've got the < and > signs flipped around.  Try using BETWEEN, I feel it's less prone to comparison mistakes if you're upper and lower bounds inclusive in your comparison.
Assuming:

*

*2500 is the number in the range searching for from your example

*You want to be lower and upper bound inclusive (base on your image, it looks like it)

You can use BETWEEN to make this clearer:
SELECT * FROM hotel_tax_details
  WHERE 2500 BETWEEN start_range_cost AND end_range_cost;

You could also fix the original query and correct the comparison:
SELECT * FROM `hotel_tax_details`
 WHERE `start_range_cost`<=2500 AND `end_range_cost`>=2500

A: Hope this helps
SELECT * FROM hotel_tax_details WHERE 2500 BETWEEN start_range_cost AND end_range_cost


Q: CSS not loading in WKWebView I am trying to create a simple WebView app using UITabBarViewController. The CSS does not load when I use Tab Bar. If I use a simple View Controller, the CSS loads. There are no other changes to the code.
let request: NSMutableURLRequest = NSMutableURLRequest(url: myUrl)

    if (webView != nil) {

    } else {
        self.loadView()
        self.webView.navigationDelegate = self
    }
    if (self.finishedUrl != myUrl.absoluteString) {
        webView.load(request as URLRequest)
    }

A: So, I was able to solve the problem and the problem was /. If you put / to the end of url, CSS doesn't load. But, if you don't put / to the end, CSS gets loaded.

A: Replace your if condition, it doesn't make sense to perform actions on a nil webview.
if (webView != nil) {

} else {
    self.loadView()
    self.webView.navigationDelegate = self
}
if (self.finishedUrl != myUrl.absoluteString) {
    webView.load(request as URLRequest)
}

should be:
if (webView != nil) {
    self.loadView()
    self.webView.navigationDelegate = self
}

if (self.finishedUrl != myUrl.absoluteString) {
    webView.load(request as URLRequest) // also make sure this is being executed.
}

A: I had the same problem.  My styles.css file was being referenced in the .HTML files just file, and it worked great loading up directly in a browser.
The problem that I had was that my styles.css wasn't included in any of my Targets.  After I checked the box, it loaded up great.

A: I've got the same problem but nothing here helped me. The solution was to remove the folder path in the link, even if they were inside these folders in my Bundle.
Instead of having this:
<link rel="stylesheet" href="css/style.css" />

Removed the folder part and left this:
<link rel="stylesheet" href="style.css" />

And it worked. The same happened with the .js file

A: I had the same issue and resolved it by adding the resources as "Create folder instance" instead of "Create groups".
Create groups indexes the file but strips it of its path. Calling the file is done by calling the filename (unique filename is important in the group).
Create folder instance maintains the folder structure
Cfr. Create groups vs Create folder reference in Xcode


Q: Difference between string and string? in c# In c#, the string type is inherently nullable, right? This morning I was working with the Environment.GetEnvironmentVariable() method, and noticed it returns type string?. Is the ? added to the return type redundant, and just there to indicate that it returns null when there are no environment variables that match the variable name you asked for? Or is there a more significant difference between string and string? in .net/c#?


Q: NSItemProvider with type identifier "com.apple.pkpass" I am building a share extension for iOS and would like to accept Passbook passes. I have the share extension working in that:
NSItemProvider *itemProvider = inputItem.attachments.firstObject;
[itemProvider hasItemConformingToTypeIdentifier:@"com.apple.pkpass"];

returns true. However, I'm lost at attempting to load this item. I've tried coercing it to NSData using this and other types:
[itemProvider loadItemForTypeIdentifier:@"com.apple.pkpass" options:nil completionHandler:^(NSdata *item, NSError *error) {
    NSLog(@"%@", item);
}];

However, none work. Does anybody know how to use Passbook passes in a share extension? I preferably would like an NSData object.

A: Get the returned data as "id" type first, then create your PKPass object by "initWithData" with your returned data. You don't need to convert it to NSData.
Remember to import Passkit.


Q: How do i solve this problem java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager? I'm currently working on a webservice using Netbeans 11.3 on a local Glassfish-server version 5.1.0
JDK/JRE version 1.8.0_221
When trying to post by using the webservice i receive the following error msg:
java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager
    at sun.security.ssl.Handshaker.init(Handshaker.java:282)
    at sun.security.ssl.Handshaker.<init>(Handshaker.java:242)
    at sun.security.ssl.ClientHandshaker.<init>(ClientHandshaker.java:160)
    at sun.security.ssl.SSLSocketImpl.initHandshaker(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.doneConnect(SSLSocketImpl.java:700)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:679)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:259)

I've tried changing both JDK and JRE using the PCs environment variables and in the IDE but i keep getting the same error msg.
I only found 1 more thread with a similar problem to mine:
java.lang.NoClassDefFoundError: sun/security/ssl/HandshakeStateManager
Where changing JDK to 1.8.0_221 resolved the issue.
Can anyone tell me why this isn't working or do you need any further information?
Thanks

A: I found a fix in this thread: JavaWeb java.lang.NoClassDefFoundError: sun/security/ssl/HelloExtension
"Had basically the same problem, eventually solved it with this solution here.
In your glassfish folder go to glassfish5/glassfish/modules/endorsed/ and open the grizzly-npn-bootstrap.jar file with winrar or your preferred unzipper.
Delete the sun folder and try running your program again."
I've been stuck with this for over a week and finally found this fix. Now using the post-function works!


Q: Why is this pointer incrementing by 0x10 not 0x04? In the code below, when writing to the memory why does this line of code:
temp = ((int*) mem_allocate + i);

not increment the memory locations in consecutive 4 bytes? The memory locations resulted due to this are:
0x20000818
0x20000828
0x20000848
...

and so on.
I wanted to write the data in
0x20000818
0x2000081C
0x20000820
...

and so on.
#include <stdio.h>
#include <stdlib.h>

int main()
{
   int n = 1024;
   int* mem_allocate;
   int loop = 0;
   int i = 0;

   mem_allocate = (int*) malloc(n*sizeof(int));

   for(i=0; i<40; i++)
   {
      int* temp;
      temp = ((int*) mem_allocate + i);
      i=i+3;
      *temp =0xAAAAAAAAu;
      *mem_allocate = *temp;
       mem_allocate = temp;

      if (i == 40)
      {
          loop = 1;
      }
   }

   if (loop == 1)
   {
      free(mem_allocate);
   }
   return 0;
}

A: Your loop control variable i is incremented by one in the for loop:
for(i=0; i<40; i++)

and then by a further 3 by:
i=i+3;

So i is overall incremented by 4 in each iteration.  Pointer arithmetic accounts for the size of the object pointed to.  Here you are pointing to a 32 bit (4 byte) integer, and incrementing by 4 each time, so the address is incremented by 4 x 4 = 16 bytes.
You should have:
   for( i = 0; i < 10; i++ )
   {
      int* temp = mem_allocate + i ;
      // i=i+3; REMOVE THIS!
      ...

Note that the cast was unnecessary; mem_allocate was already an int* as is the type of the expression mem_allocate + i.
Your code is flawed in other ways, unrelated to the question you have asked - specifically the ill-advised modification of mem_allocate - if you modify it, any attempt to free it will be invalid.
Consider:
#include <stdint.h>
#include <stdlib.h>

int main()
{
   const int n = 1024;
   uint32_t* mem_allocate = malloc( n * sizeof(*mem_allocate) ) ;

   for( int i = 0; i < n; i++ )
   {
      mem_allocate[i] = 0xAAAAAAAAu;
   }

   free( mem_allocate ) ;

   return 0 ;
}

As you can see you made a simple thing unnecessarily complicated.


Q: Remove NaN from 2D numpy array For example, if I have the 2D array as follows.
[[1,2,3,NAN],
 [4,5,NAN,NAN],
 [6,NAN,NAN,NAN]
]

The desired result is
[[1,2,3],
 [4,5],
 [6]
]

How should I transform?
I find using
 x = x[~numpy.isnan(x)] can only generate [1,2,3,4,5,6], which has been squeezed into one dimensional array.
Thanks!

A: Just apply that isnan on a row by row basis
In [135]: [row[~np.isnan(row)] for row in arr]
Out[135]: [array([1., 2., 3.]), array([4., 5.]), array([6.])]

Boolean masking as in x[~numpy.isnan(x)] produces a flattened result because, in general, the result will be ragged like this, and can't be formed into a 2d array.

The source array must be float dtype - because np.nan is a float:
In [138]: arr = np.array([[1,2,3,np.nan],[4,5,np.nan,np.nan],[6,np.nan,np.nan,np.nan]])
In [139]: arr
Out[139]:
array([[ 1.,  2.,  3., nan],
       [ 4.,  5., nan, nan],
       [ 6., nan, nan, nan]])

If object dtype, the numbers can be integer, but np.isnan(arr) won't work.
If the original is a list, rather than an array:
In [146]: alist = [[1,2,3,np.nan],[4,5,np.nan,np.nan],[6,np.nan,np.nan,np.nan]]
In [147]: alist
Out[147]: [[1, 2, 3, nan], [4, 5, nan, nan], [6, nan, nan, nan]]
In [148]: [[i for i in row if ~np.isnan(i)] for row in alist]
Out[148]: [[1, 2, 3], [4, 5], [6]]

The flat array could be turned into a list of arrays with split:
In [152]: np.split(arr[~np.isnan(arr)],(3,5))
Out[152]: [array([1., 2., 3.]), array([4., 5.]), array([6.])]

where the (3,5) split parameter could be determined by counting the non-nan in each row, but that's more work and doesn't promise to be faster than than the row iteration.


Q: Floating box css I have a Joomla site with K2 component. And I have a bad look "issue". Please see the image:
Css box foating problem
Here is a part from the css file what I think that it applies to here:
/* --- Item groups --- */
div.itemList {}
div#itemListLeading {}
div#itemListPrimary {}
div#itemListSecondary {}
div#itemListLinks {background:#f7fafe;border:1px solid #ddd;margin:8px 0;padding:8px;}

div.itemContainer {float:left;}
div.itemContainerLast {} /* this class is appended to the last container on each row     of items (useful when you want to set 0 padding/margin to the last container) */

/* --- Item block for each item group --- */
div.catItemView {padding:4px;} /* this is the item container for this view - we add a generic padding so that items don't get stuck with each other */

/* Additional class appended to the element above for further styling per group item */
div.groupLeading {}
div.groupPrimary {}
div.groupSecondary {}
div.groupLinks {padding:0;margin:0;}

div.catItemIsFeatured {background:#ddd;border:1px dotted; padding:3px;margin:1px;} /* Attach a class for each featured item */

So, I like the right side look. Thank you!

A: The reason why CSS failed to achieve the results desired is because CSS only cares about horizontal position, i.e. everything is laid out horizontally first, and then vertically. Therefore, the next float on the subsequent row will only be positioned below the tallest element in the first row float, therefore leaving unfilled vertical spaces when the previous row of floats have containers with shorter heights.
I'd recommend jQuery Masonry :) http://masonry.desandro.com/

A: You can use column-count to achieve the required look. Keep in mind that the order of the items will be different from when you float.
Float:
1 2
3 4
5 6

Columns:
1 4
2 5
3 6

Simply set column-count: 2 on the parent of the items.
Note that it doesn't work in all browsers: http://caniuse.com/#search=column


Q: Could someone tell me if low / less is to be used here? a) My height is low / less
b) I feel my weight is low

A: For a native English speaker, describing your height by saying "my height is less than his" or "my height is low" is not natural or common. We would say "I am shorter than him" or "I am short."
Regarding weight, you can say "My weight is low." Less is used in the context of comparison, so you could say "My weight is less than his" or you could say "My weight is lower than his" but you would not say "My weight is less" unless someone first said their own weight and you were saying that in response. However, this is still a somewhat strange way to phrase things. Most native speakers would say, "I am light" or "I am lighter than him." Saying "my weight is low" is not as strange as saying "my height is low" but it's still a bit strange.


Q: How do I deconcatenate or unconcatenate a string value in a pandas dataframe? im new to python and want to understand how to work with dataframes
I have a dataframe-
 desc13month
Out[45]:
                                            OutputValues  CntOutputValues
0                                  12-99-Annual (AE)                  217
1             21-581-Ineligible  Services(IPS)                        210
2      125-99-Annual (AE),126-22-Jermaine (JE)                        196
3                                  22-99-Annual (AE)                  181
4                                  21-50-Prime (PE)                  169

I want the OutputValues column to be unconcatenated. If you notice, the last string for example "Annual" depends on the second string 99. if its is 22 it changes to Jermaine.Sometimes there could be multiple like we see for row 2. My final output should indicate these columns and an additional column which has that last string
illustration-
desc13month
Out[45]:
                                            OutputValues  CntOutputValues   final
0                                  12-99-Annual (AE)                  217   Annual (AE)
1             21-581-Ineligible  Services(IPS)                        210   Ineligible  Services(IPS)
2      125-99-Annual (AE),126-22-Jermaine (JE)                        196   Annual (AE),Jermaine (JE)
3                                  22-99-Annual (AE)                  181   Annual (AE)
4                                  21-50-Prime (PE)                   169   Prime (PE)

A: IIUC, Let's try Series.str.replace:
df['final'] = df['OutputValues'].str.replace(r'\d+-\d+-', '')

                              OutputValues  CntOutputValues                      final
0                        12-99-Annual (AE)              217                Annual (AE)
1         21-581-Ineligible  Services(IPS)              210  Ineligible  Services(IPS)
2  125-99-Annual (AE),126-22-Jermaine (JE)              196  Annual (AE),Jermaine (JE)
3                        22-99-Annual (AE)              181                Annual (AE)
4                         21-50-Prime (PE)              169                 Prime (PE)

A: There are two parts to your question, one is handling the strings, and the other, applying that to the data frame.
For handling the strings, if the patterns remain the same meaning you are sure that each string will be digits-digits-chars and multiple values are separated by ',' then you can use something like this function:
def deconcat(output_value):
    output_value = output_value.split(',')
    result = ''
    for part in output_value:
        _, _, item = part.split('-')
        result += item + ", "
    return result.rstrip(', ')

The function takes a string, splits it by ',' if there are multiple values, then for each value, splits by '-' and adds the third part to a resulting string.
Now you only have to apply this function to the whole dataframe and create your new column:
df['final'] = df.OutputValues.apply(deconcat)

This will apply the function to each row of the OutputValues in the dataframe, and add the resulting string to a new column called 'final'.


Q: JTS + reading geodata: Number of points must be 0 or >3 I'm trying to read some geodate from file. I'm using the geotools package in java.
I have the geodata available as kml, gml and.shp, those are pretty big files.
Those come from an external bron and are formatted correctly.
When I want to read tools, GeoTools uses JTS. I also tried working with JTS directly but I get the same error message. The error I get is:
java.lang.IllegalArgumentException: Number of points must be 0 or >3
    at com.vividsolutions.jts.geom.LinearRing.validateConstruction(LinearRing.java:98)
    at com.vividsolutions.jts.geom.LinearRing.<init>(LinearRing.java:90)
    at com.vividsolutions.jts.geom.GeometryFactory.createLinearRing(GeometryFactory.java:324)
    at com.vividsolutions.jts.geom.GeometryFactory.createLinearRing(GeometryFactory.java:314)

I get this error halfway through the file. I checked all files manually: all "linearrings" have more than three points. It also doesn't matter which file I'm trying to read.
Code snippet:
File file = new File(bwkFilePath);
Map map = new HashMap();
map.put("url", file.toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);

A part from a KML-file
<MultiGeometry>
<Polygon>
<altitudeMode>
relativeToGround
</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
 5.301275,50.883145,1 5.301244,50.883233,1 5.301302,50.88329999999999,1 5.301146,50.883552,1 5.301037,50.883757,1 5.301124,50.88386299999999,1 5.301524,50.884123,1 5.301924,50.88421500000001,1 5.302014,50.884129,1 5.301751,50.88367,1 5.301275,50.883145,1
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
<Point>
<coordinates>
5.30152,50.883681,0
</coordinates>
</Point>
</MultiGeometry>

A: All linearring must have 3 point at least and also their first point and last point must be same.
in this example its true but may be your file contains wrong one.


Q: Hibernate does not find the hibernate.cfg.xml I made a java project with gradle, so simple, it is a task manager, i have a Person class and a Task class, i want to use hibernate but, hibernate doesn't load the hibernate.cfg.xml, i tried many solutions, but anything has worked.
I have a HibernateUtil.java writen like this:
package org.gradle.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory(
                new StandardServiceRegistryBuilder().build() );
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

This is the layout:
/my-project
  /src
    /main
      /java
        /org
          /gradle
            Main.java
            /controllers
              PersonController.java
              TaskController.java
            /domains
              Person.java
              Task.java
              Person.hbm.xml
              Task.hbm.xml
            /util
              HibernateUtil.java
      /java
        /resources
          hibernate.cfg.xml
          /org
            /gradle
    /test
      /java
        /org
          /gradle
            PersonTest.java
            TaskTest.java

And this is the full trace:
Sep 26, 2014 11:32:11 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Sep 26, 2014 11:32:11 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Sep 26, 2014 11:32:11 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.gradle.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
    at org.gradle.util.HibernateUtil.<clinit>(HibernateUtil.java:9)
    at org.gradle.controllers.PersonController.add(PersonController.java:10)
    at org.gradle.Main.main(Main.java:12)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
    at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2093)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2074)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2054)
    at org.gradle.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
    ... 3 more

I hope you guys could help me, this is breaking my mind.
If you need something more, please let me know.

A: According to this tutorials on Hibernate 4+Gradle:
your resources folder should be under main, not under java:
Edit:
probably, you are missing something in the way you are building the sessionfactory:
Configuration configuration = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(builder.build());

instead of :
return new Configuration().configure().buildSessionFactory(
                new StandardServiceRegistryBuilder().build() );

you have to applysettings to pass properties of your configuration to the builder:


Q: Creating a Simple 1D CNN in PyTorch with Multiple Channels The dimensionality of the PyTorch inputs are not what the model expects, and I am not sure why.
To my understanding...
in_channels is first the number of 1D inputs we would like to pass to the model, and is the previous out_channel for all subsequent layers.
out_channels is the desired number of kernels (filters).
kernel_size is the number of parameters per filter.
Therefore, we would expect, as data passed to forward, a dataset with 7 1D channels (i.e. a 2D input).
However, the following code throws an error that is not consistent with what I expect, where this code:
import numpy
import torch

X = numpy.random.uniform(-10, 10, 70).reshape(-1, 7)
# Y = np.random.randint(0, 9, 10).reshape(-1, 1)

class Simple1DCNN(torch.nn.Module):
    def __init__(self):
        super(Simple1DCNN, self).__init__()
        self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2)
        self.act1 = torch.nn.ReLU()
        self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
    def forward(self, x):
        x = self.layer1(x)
        x = self.act1(x)
        x = self.layer2(x)

        log_probs = torch.nn.functional.log_softmax(x, dim=1)

        return log_probs

model = Simple1DCNN()
print(model(torch.tensor(X)).size)

Throws the following error:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-5-eca5856a2314> in <module>()
     21
     22 model = Simple1DCNN()
---> 23 print(model(torch.tensor(X)).size)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

<ipython-input-5-eca5856a2314> in forward(self, x)
     12         self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
     13     def forward(self, x):
---> 14         x = self.layer1(x)
     15         x = self.act1(x)
     16         x = self.layer2(x)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input)
    185     def forward(self, input):
    186         return F.conv1d(input, self.weight, self.bias, self.stride,
--> 187                         self.padding, self.dilation, self.groups)
    188
    189

RuntimeError: Expected 3-dimensional input for 3-dimensional weight [20, 7, 5], but got 2-dimensional input of size [10, 7] instead

Edit: See below for solution, motivated by Shai.
import numpy
import torch

X = numpy.random.uniform(-10, 10, 70).reshape(1, 7, -1)
# Y = np.random.randint(0, 9, 10).reshape(1, 1, -1)

class Simple1DCNN(torch.nn.Module):
    def __init__(self):
        super(Simple1DCNN, self).__init__()
        self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2)
        self.act1 = torch.nn.ReLU()
        self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
    def forward(self, x):
        x = self.layer1(x)
        x = self.act1(x)
        x = self.layer2(x)

        log_probs = torch.nn.functional.log_softmax(x, dim=1)

        return log_probs

model = Simple1DCNN().double()
print(model(torch.tensor(X)).shape)

A: You are forgetting the "minibatch dimension", each "1D" sample has indeed two dimensions: the number of channels (7 in your example) and length (10 in your case). However, pytorch expects as input not a single sample, but rather a minibatch of B samples stacked together along the "minibatch dimension".
So a "1D" CNN in pytorch expects a 3D tensor as input: BxCxT. If you only have one signal, you can add a singleton dimension:
 out = model(torch.tensor(X)[None, ...])


Q: How does LSTM/RNN deal with the correlated samples and the samples with different lengths We know that LSTM/RNN has the following advantages compared with the basic machine learning algorithms:

*

*Account the correlation between samples (usually the samples from time series are always correlated)
I agree that the hidden layer of RNN accounts the correlation between states within one sequential sample, however where does RNN reflect the correlation between samples? For example, Gaussian process regression reflects the correlation between sample between their correlation matrix, e.t.c.

*Performs well on the samples with different lengths like time series.
At least, from the following reference, in Keras, LSTM/RNN just simple truncate and pad the raw input sequential samples to obtain the sequence samples with a fixed  length and width. I think this way can be applied to any machine learning algorithms, how is it specific to RNN/LSTM?
https://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/


Q: Investment Formula for Initial and Final Investment and Periodic Contribution. I am able to re-arrange the following formula to calculate Initial Investment, final investment and  Periodic Contribution. But how do I manipulate it to calculate values at the beginning of periodic contribution period (annuity due)?
FV=PV(1+rn)nt+PMT∗(1+rn)nt−1)rn
Periodic contribution can be either in years or months.
Thank you..


Q: Regarding a clean React-Native elements app, getting: 'loose' mode configuration must be the same for Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: /Users/neil/rne/src/index.tsx: 'loose' mode configuration must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled).
at enableFeature (/Users/neil/rne/node_modules/@babel/helper-create-class-features-plugin/lib/features.js:51:13)
at PluginPass.pre (/Users/neil/rne/node_modules/@babel/helper-create-class-features-plugin/lib/index.js:82:35)
at transformFile (/Users/neil/rne/node_modules/@babel/core/lib/transformation/index.js:97:27)
at transformFile.next ()
at run (/Users/neil/rne/node_modules/@babel/core/lib/transformation/index.js:35:12)
at run.next ()
at Function.transform (/Users/neil/rne/node_modules/@babel/core/lib/transform.js:25:41)
at transform.next ()
at step (/Users/neil/rne/node_modules/gensync/index.js:261:32)
at /Users/neil/rne/node_modules/gensync/index.js:273:13


Q: Limitations of parallelizing heterogeneous tasks I was reading Java Concurrency in Practice and a paragraph came across which said something like this:-

Under 6.3.4 Limitations of parallelizing heterogeneous tasks
A further problem with dividing heterogeneous tasks among multiple workers
is that the tasks may have disparate sizes. If you divide tasks A and B between
two workers but A takes ten times as long as B, you’ve only speeded up the total
process by 9%. Finally, dividing a task among multiple workers always involves
some amount of coordination overhead; for the division to be worthwhile, this
overhead must be more than compensated by productivity improvements due to
parallelism.

Now if you go through the bold part, is it correct to say that worker threads' co-ordination overhead must be more than the performance improvement I achieve using parallelism of threads?
Could some one please help me understand it?

A: No, the bolded bit changes the meaning of the sentence quite significantly:

Finally, dividing a task among multiple workers always involves some amount of coordination overhead; for the division to be worthwhile, this overhead must be more than compensated by productivity improvements due to parallelism.

If that was simply "must be more than the productivity improvements..." then you would be right. What the above is saying is that the performance penalty you incur by dividing the tasks among your worker threads (the overhead), must be less than the performance increase you gain by doing it at all.
For instance, if your overhead is 10 seconds and your performance gain is only 5 seconds, then parallelising the operation has actually decreased your overall performance. If your overhead is 10 seconds but the performance gain is 50 seconds, you've ended up with a 40 second reduction in the overall execution time (i.e. an improvement).
Another way of saying it would be "...this overhead must be offset by the productivity improvements due to parallelism.".


Q: Node js url being requested multiple times I am new to Node js. I am trying to import a save a large CSV file into mongoDB using node js. My method name is 'saveCSVintoDB'. I am using csvtojson converter in this method to parse the file. As the file has more than 1 million records, the converter takes around 2 mins to parse the complete file. Meanwhile, My node js method 'saveCSVintoDB' is being requested again and the parsing starts all over again.I don't want this to happen. I don't face this problem with smaller files as they are parsed much faster and the next request takes over from there on.
The problem is only while waiting for about 2 mins while the parsing happens. I don't understand this behavior. I am stuck with this for a long time. Can some body please explain this and suggest some possible alternative?
Thanks,
Naresh

A: You can try adding a timestamp to check when it is being requested the second time:
 console.log("got request @" + new  Date());

Since processing is taking time, the request is getting timed out and hence another request is being fired. You need to increase the timeout interval.
In vanilla JS:
var server = http.createServer(function (req, res) { ... });
server.timeout = 120000;

If you are using Express then you can use Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4

app.use(timeout(120000));

Edit: Handling the multiple request issue:
Most of the answers on SO hint that second request is made for favicon. But I checked on my local machine that this is not the case with the second request made after interval of around 2 minute by printing the req.url which points to the same page which in your case will be /saveCollection.
I can suggest a hack which worked on my local machine:

*

*Send headers: res.writeHead(200, { 'Content-Type': 'application/json' }); upon request. This will buy us 2 minutes time.

*Now setup a interval which will keep feeding browser every 2 minutes with dummy data.

*When the computation is completed remove the interval, send the actual result and close the response.

Here's an example:
    router.post('/saveCollection', function(req, res,next) {
      console.log("col name:"+req.param("collName"));
      var fileStream=fs.createReadStream(req.files.myFile.path);
      var csvConverter=new Converter({constructResult:false});
      csvConverter.on("end_parsed",function() {
        console.log('file completely parsed:');
        clearInterval(si);
        res.write(", 'success':true}");
        res.end();
      });

      i = 0;
      var si = setInterval(function() {
        i++;
        res.write(",'dummy" + i + "' : 'piece'");
      }, 1000 * 60); //this should be kept a little less than two minutes

      console.log('before parsing');
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.write("{'dummy':'piece'");
      fileStream.pipe(csvConverter);
    });

There is no other way to do this that I can think of. Even if you ignore the second request, still the first request will expire and browser will probably show an error.
There is another work around, start computing and send a response back as soon as computing starts and then use sockets to check the status.


Q: Use assemby reference like an Project reference in Visual Studio? I have a C# project with some referenced dll's. To inspect the whole Project it would be nice to replace the referenced dll's against the existing project references temporarily.
The benefits were "the search in the whole solution" and "Go to Definition" makes more sense.
Is there a trick to replace references in the *.csproj file?
Or is there a Visual Studio extension to achieve the benefits?
Thanks

A: I found a solution with ReSharper.
You can open and disassemble the references with the extension ReSharper and set break points.


Q: When building the library matio, the configure script throws the error "C compiler cannot create executables" For building the library matio, I first need to execute a configure script and afterwards run make. The configure script however throws the following error:
    configure: error: in `/home/user/matio-master':
    configure: error: C compiler cannot create executables

More specifically, the error happens while executing core tests. Below you see a section of the config.log. What could be the reason for the fail and how can I fix it?
    ## ----------- ##
    ## Core tests. ##
    ## ----------- ##

    configure:2135: checking for a BSD-compatible install
    configure:2203: result: /usr/bin/install -c
    configure:2214: checking whether build environment is sane
    configure:2274: result: yes
    configure:2415: checking for a thread-safe mkdir -p
    configure:2454: result: /bin/mkdir -p
    configure:2467: checking for gawk
    configure:2483: found /bin/gawk
    configure:2494: result: gawk
    configure:2505: checking whether make sets $(MAKE)
    configure:2527: result: yes
    configure:2622: checking whether to enable maintainer-specific portions of Makefiles
    configure:2631: result: no
    configure:2651: checking build system type
    configure:2669: result: x86_64-pc-linux-gnu
    configure:2691: checking host system type
    configure:2706: result: x86_64-pc-linux-gnu
    configure:2819: checking for pgcc
    configure:2849: result: no
    configure:2819: checking for icc
    configure:2849: result: no
    configure:2819: checking for gcc
    configure:2835: found /home/user/gcc
    configure:2846: result: gcc
    configure:2880: checking for C compiler version
    configure:2888: gcc --version >&5
    gcc (GCC) 6.3.0
    Copyright (C) 2016 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    configure:2892: $? = 0
    configure:2899: gcc -v >&5
    Using built-in specs.
    COLLECT_GCC=/cadappl_sde/ictools/gcc/6.3.0/bin/gcc
    COLLECT_LTO_WRAPPER=/sysmnt/cadappl_sde/ictools/gcc/6.3.0/bin/../libexec/gcc/x86_64-redhat-linux/6.3.0/lto-wrapper
    Target: x86_64-redhat-linux
    Configured with: ../gcc-6.3.0/configure --prefix=/cadappl_sde/ictools/gcc/6.3.0 --with-isl=/cadappl_sde/ictools/gcc/6.3.0 --with-gmp=/cadappl_sde/ictools/gcc/6.3.0 --with-mpfr=/cadappl_sde/ictools/gcc/6.3.0 --with-mpc=/cadappl_sde/ictools/gcc/6.3.0 --enable-static --enable-shared --enable-bootstrap --enable-checking=release --disable-werror --disable-nls --enable-threads=posix --disable-libunwind-exceptions --enable-__cxa_atexit --enable-gnu-unique-object --enable-languages=c,c++,fortran,java,go,objc,obj-c++ --enable-c99 --disable-libada --enable-plugin --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux --enable-libstdcxx-time --enable-long-long --disable-multilib
    Thread model: posix
    gcc version 6.3.0 (GCC)
    configure:2903: $? = 0
    configure:2910: gcc -V >&5
    gcc: error: unrecognized command line option '-V'
    gcc: fatal error: no input files
    compilation terminated.
    configure:2914: $? = 1
    configure:2937: checking for C compiler default output file name
    configure:2959: gcc -L/boost_filesystem -L/boost_system   conftest.c  >&5
    configure:2963: $? = 0
    configure:3001: result:
    configure: failed program was:
    | /* confdefs.h.  */
    | #define PACKAGE_NAME "MATIO"
    | #define PACKAGE_TARNAME "matio"
    | #define PACKAGE_VERSION "1.5.13"
    | #define PACKAGE_STRING "MATIO 1.5.13"
    | #define PACKAGE_BUGREPORT "t-beu@users.sourceforge.net"
    | #define PACKAGE "matio"
    | #define VERSION "1.5.13"
    | #define MATIO_PLATFORM "x86_64-pc-linux-gnu"
    | #define MATIO_MAJOR_VERSION 1
    | #define MATIO_MINOR_VERSION 5
    | #define MATIO_RELEASE_LEVEL 13
    | #define MATIO_VERSION 1513
    | #define MATIO_VERSION_STR "1.5.13"
    | /* end confdefs.h.  */
    |
    | int
    | main ()
    | {
    |
    |   ;
    |   return 0;
    | }
    configure:3007: error: in `/home/user/matio-master':
    configure:3010: error: C compiler cannot create executables
    See `config.log' for more details.


Q: How to reply to specific comment using django recursive relationship and react js Model is
class Comment(models.Model):
    profile = models.ForeignKey(Profile,on_delete=models.CASCADE)
    account = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    content = models.TextField(max_length=160)
    reply = models.ForeignKey('Comment',null=True,related_name="replies",on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)

adding and showing comment using react
class CommentExampleComment extends Component {
state={
  comment:'',
  id:''
}
changeHandler=event=>{
  var vals =event.target.value
  // var jpt = {...this.state.comment}
  // this.props.comments.map(el=>(this.setState({
  //   comment:vals,
  //   id:el.id
  this.setState({comment:vals})
    // file:event.target.files
}
submitHandler=e=>{
  e.preventDefault()
  var formData = new FormData()
  formData.append('content',this.state.comment)
  formData.append('id',this.actionInput.value)
//used to add comment to db
  axios.post('http://127.0.0.1:8000/account/api/comments/1',formData).then(res=>{
    console.log(res.data)
  }).catch(err=>{
    console.log(err)
  })
// used for showing comment
  this.props.onShowComment()
}
return(
      <Aux>

        // THIS IS COMMENT SECTION

            <form method="POST" onSubmit={this.submitHandler}>
      <textarea id="w3mission" onChange = {this.changeHandler} rows="4" cols="50"></textarea>
                <button name ="button">Comment</button>
            </form>
            {this.props.comments.map(el=>(

{ el.content }

                -by

                    -by

 */}

                //THIS IS REPLY SECTION

                  <form method="post" onSubmit={this.submitHandler}>

{el.id}

                     <input type="hidden" name="id" ref={(input) => { this.actionInput = input }} value ={el.id}/>

                <textarea id="w3mission" onChange = {this.changeHandler} rows="4" cols="50"></textarea>

                     <button name ="button">Reply</button>
                  </form>

      ))}

    </Aux>)}}
var mapStateToProps = state=>{
  return{
    comments:state.cmnts.comment
  }
}
var mapDispatchToProps = dispatch=>{
  return{
    onShowComment:()=>dispatch(actions.commentList())
  }
}
export default connect( mapStateToProps, mapDispatchToProps )( CommentExampleComment );
PROBLEM IS :

when i try to submit the reply value passed through hidden field "(input type="hidden" name="id" ref={(input) => { this.actionInput = input }} value ={el.id})"is always the last comment id but i want the value of the comment id to be id corresponding to that particular comment.I want the value to capture the comment id while replying to that comment

A: onChange = {e => this.changeHandler(e, el.id) }
grab el.id on changeHandler and store in state, use this state in your api call.


Q: PIP permission denied on Mac OSX even with --user I've recently come to know the terrors of using pip with sudo to install packages. Instead, it is recommended using the --user flag. The problem is that even with the user flag I can't install ANYTHING with PIP, accusing of permission denied. Anyone ever had this problem before?
Here's a little demo of the error when trying to install the package Cython:
OSError: [Errno 13] Permission denied: '/Users/myusername/Library/Python/2.7'

Thank you in advance for your help.
P.S: I know about the alternative of using a virtualenv, but I really wanna stick to using pip on the clear.
Edit: It turns out I have access to /Library/Python but not to ~/Library/Python. Which seems strange to me, why would I have access to systemwide files but not to my own? Is this normal?

A: Try to use sudo command.
 sudo pip install cython


Q: Render an user interface in memory let's say I have hwnd handle and would like to add some GUI controls in memory. I also receive all user input via events.
So, is it possible to use wxwidgets to add a user interface to an image which will be drawn onto the a Window ( using such hwnd handle ). If so, does wxwidget have some facilities to keep track of state of the GUI?
I'm new to wxwidgets and so please excuse my general questions.
Many thanks,
Christian

A: The only way to add GUI controls to an image, is to draw them yourself. The only way to do that, would be to create an image GUI element, and position the other GUI elements relative to the image element. However, this will not do double-buffering of the UI like you want to do, it doesn't actually draw the UI elements in the image, just places them on top of the image.


Q: How to automatically install self signed certificate in IE Trusted Root Certification Authorities store I created a self signed certificate but the browser tells me "This CA Root Certificate is not trusted. To enable trust, install this certificate in the Trusted Root Certification Authorities store".
I did by going into IE --> Internet Options --> Content --> Certificates --> ect... I actually had to export the self signed certificate and then import it into the Trusted Root Certification.  Only after the certificate was located under the ROOT store in the users machine that IE did not display any WARNINGS.
This will be deployed in a production environment, so having the users manually do the above steps is unacceptable.
How can I automatically do this?  I just want them to accept and not have that "Certificate Error" and have the URL bar turned "RED" in IE.
I'm using Tomcat 5.5. I also followed the same steps as in the Tomcat SSL How To Tutorial http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html
Thanks in advance.

A: Java 6 provides a cryptographic provider named SunMSCAPI to access the windows cryptography libraries API. This provider implements a keystore "Windows-Root" containing all Trust Anchors certificates.
It is possible to insert a certificate in this keystore.
KeyStore root = KeyStore.getInstance("Windows-ROOT");
root.load(null);
/* certificate must be DER-encoded */
FileInputStream in = new FileInputStream("C:/path/to/root/cert/root.der");
X509Certificate cacert = (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(in);
root.setCertificateEntry("CACert Root CA", cacert);

The user will be prompted if for confirmation. If the operation is canceled by the user then a KeyStoreException is thrown.
Some technotes about the provider can be found here: http://download.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunMSCAPI

A: Think about it.  If this were possible, what would stop any fraudulent site from doing the same thing and making it look like their site was trusted?  The whole point is that the user HAS to OK the certificate installation.

A: First of all, possibility to do this would compromise user's security, so it would be a security hole, so no, there's no easy way to do this.
Next, different software has different certificate stores. Microsoft and Chrome browser use CryptoAPI stores, Firefox has it's own store (Chrome can also use firefox's one AFAIK). Adobe's software has it's own store (in addition to CryptoAPI one).


Q: Synchronization in Java - Vector vs ArrayList I am attempting to understand the difference between the Vector and ArrayList classes in terms of thread-safety. Vector is supposedly internally synchronized. Is it synchronized by each element, or as a whole? (I could imagine the case where multiple threads could access the vector at the same time, but multiple threads could not access the same element at the same time). If you look at the code below, getAo() is not equivalent to getV() because the synchronized keyword when used in a method signature synchronizes on the containing class object (an instance of VectorVsArrayList) to my knowledge. HOWEVER, is getAoSync() equivalent to getV()? By equivalent, I mean does the ao instance variable start behaving like a Vector object in terms of synchronization as long as all access to it goes through the getter method?
public class VectorVsArrayList {

        private ArrayList<?> ao = null;
        private Vector<?> v = null;

        public ArrayList<?> getAoSync(){
            synchronized(ao){
                return ao;
            }
        }

        public synchronized ArrayList<?> getAo() {
            return ao;
        }

        public Vector<?> getV() {
            return v;
        }

    }

A: Short answer: No, it's not equivalent.
When you use synchronized around that return ao;, the ArrayList is only synchronized during the return instruction. This means that 2 threads cannot get the object at the exact same time, but once they have got it, they can modify it at the same time.
If 2 threads execute this code, the add() is not thread safe:
ArrayList<?> list = getAo(); // cannot be executed concurrently
list.add(something); // CAN be executed concurrently

Side note: don't use Vectors, take a look at this post to know why.

A: They aren't equivalent. What you're looking for is Collections.synchronizedList which can "wrap around" any list, including ArrayList.

A: to do the equivalent of Vector you should protect any access to any element in the collection, the method getAo simply sychronize the access to the array list.
If two threads call getAo and after each thread call "add" method over this arraylist then you could have a multi thread problem (because "add" is not synch").
I recommend you to check the atomic classes like CopyOnWriteArrayList:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html


Q: Error Failed to execute aapt, when compiling project in React-Native I have this error since Monday, no modifications have been made since last week. And on Monday I started giving problems.

*

*Glade: 2.14.1

*React-Native: 0.49.3

*compileSdkVersion 25

*targetSdkVersion 22

A: This has nothing to do with React Native, one of your resource files references an nonexisting value (dialogCornerRadius). Locate the reference (Android Studio to the rescue) and fix it.


Q: TYPO3 Hook for preview for multiple languages I have a TYPO3 installation with multiple languages.
Now I want to create a function that if i.e. a french editor, with french settings, goes to the View (or preview of a page) that he gets the french version and not the default language.
My first idea was to use the PageLayoutViewDrawItemHookInterface and then change the URL for the right language
in ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['tt_content_drawItem']['tx_editordashboard'] =
    \Vendor\Editordashboard\Hooks\Backend\CheckUserCountry::class;

in my CheckUserCountry.php class
<?php

namespace TRUMPF\Editordashboard\Hooks\Backend;

use \TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface;
use \TYPO3\CMS\Backend\View\PageLayoutView;

class CheckUserCountry implements PageLayoutViewDrawItemHookInterface
{

/**
 * Preprocesses the preview rendering of a content element.
 *
 * @param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling
 parent object
 * @param bool $drawItem Whether to draw the item using the default
functionalities
 * @param string $headerContent Header content
 * @param string $itemContent Item content
 * @param array $row Record row of tt_content
 */
public function preProcess(PageLayoutView &$parentObject, &$drawItem,
&$headerContent, &$itemContent, array &$row) {echo "bam";}
}

But the Hook doesn't work if I click on the "View" Button. Any ideas so solve the problem?


Q: How to make ROC Curves with survey objects I'm trying to build a ROC curve with data from a survey object from surveyr. But the pROC function cannot coerce a survey object back to a data frame for the analyses and it doen't work with the survey object
if (!require("pacman")) install.packages("pacman")

pacman::p_load(tidyverse, haven, survey, sjPlot, pROC, surveydata)

roccurve1 <- roc(apoio_ag ~fitted(Model1), data = psurvey)
roccurve2 <- roc(apoio_ag ~fitted(Model2), data = psurvey)
roccurve3 <- roc(apoio_ag ~fitted(Model3), data = psurvey)

Erro message
Error in as.data.frame.default(data, optional = TRUE) :
cannot coerce class ‘"svyrep.design"’ to a data.frame
Those are the packages and the code that I'm currently using.
Anyone has an idea on how to solve that?

A: The pROC::roc function doesn't accept sampling weights, so it's not just a matter of data formats -- you can extract a data frame from a survey object with model.frame, but roc still won't be doing a weighted analysis.
There's a WeightedROC package that fits weighted ROC curves. You could do something like (not tested because there isn't a reproducible example)
WeightedROC(fitted(Model3), Model3$y, weights(psurvey))


Q: Plotting a Lognormal Distribution I am trying to plot a lognormal distribution so I can compare it with a histogram of my sample data using the code below but my plot does not look right. Is there something with my code that I am not doing correctly?
The C array has a length of 17576
import matplotlib.pyplot as plt
import numpy as np

data=np.loadtxt(F)
C=data[:,3]

x = np.ma.log(C)
avg = np.mean(x)
std = np.std(x)
dist=lognorm(std,loc=avg)
plt.plot(C,dist.pdf(C),'r')
plt.show()

A: It looks like your x data are not in sorted order. Try this
ind = np.argsort(C)
xx = C[ind]
yy = dist.pdf(C)[ind]
plt.plot(xx, yy, 'r')

Plot just connects all the (x,y) pairs with straight lines, so you need to make sure you trace your function from left-right (or right-left). Alternatively, you can skip the lines between the plot:
plt.plot(C, dist.pdf(C), 'ro')


Q: Linux echo byte array to serial port I would like to echo an array of bytes from the linux terminal to serial port. Have already seen this Sending bytes to serial port from UNIX command line? and from that deduced the command will be something like the following:
printf '%b' '\x9c8684a4624000a0b2668a84400003f00301000000048ab0c0' > /dev/ttyUSB0

To debug the ideia I redirected it to a file  with
printf '%b' '\x9c8684a4624000a0b2668a84400003f00301000000048ab0c0' > file.raw

and checked the file with hexedit. But so I've found that ASCII values were been written instead.
In the end I expect the following in the file:
9c 86 84 a4 62 40 00 a0 b2 66 8a 84 40 00 03 f0 03 01 00 00 00 04 8a b0 c0


Q: Как выполнить код, записанный в массиве String Мне нужно чтобы программа выполняла код, записанный в массиве строк. Допустим:
String TEST_STRING = "System.out.println(\"Мама мыла раму\");";
String[] testString = new String[2];
testString[0] = TEST_STRING;
//Здесь каким-то образом выполняется код, записанный в testString[0]

A: разъясните подробнее постановку задачи, может быть вам и не нужно такое вульгарное решение.
От себя советую познакомиться с паттерном "команда". Вот к примеру реализация "пульта управления".
1) У нас есть некоторый набор сущностей с которыми надо взаимодействовать, они могут выполнять действие откатывать его и сообщать свой статус
public class SomeEntity{

private boolean status = false;

public void do() {
    this.status = false;
    //do your code
}

public void undo() {
    this.status = true;
    //undo your code
}

public boolean getStatus() {
    return this.status;
}
}

2)Теперь мы пишем команду для каждого сценария нашего класса
public interface Command {

public void execute();

public void undo();
}

3)За командой прикрепляется сущность с которой она взаимодействует
public class MyCommand implements Command {

private final SomeEntity someEntity;

public MyCommand (SomeEntity someEntity) {
    this.someEntity= someEntity;
}

@Override
public void execute() {
    this.someEntity.do();
}

@Override
public void undo() {
    this.someEntity.undo();
}
}

4)а теперь создадим пульт, который бы знал в лицо объекты с которыми ему взаимодействовать и научим его выполнять макросы
public class Controller {

private final ArrayList<Command> сommands;

public Controller() {
    this.сommands = new ArrayList<Command>();
}

public void addCommand(Command сommand) {
    this.сommands.add(сommand);
}

public void executeCommand(int index) {
    if (index < this.сommands.size()) {
        this.сommands.get(index).execute();
    }else{
        new DoNothingCommand().execute();
        //comand which doing nothing
    }
}

public void undoCommand(int index) {
    if (index < this.undoCommands.size()) {
        this.commands.get(index).undo();
    }else{
        new DoNothingCommand().execute();
    }
}
}

а теперь подумайте сколько всего прикольного можно сделать, вы можете циклом обойти весь список в commands и вызвать их execute() - вот вам и макрос на уровне пульта.
Или ещё круче сделать набор макросов на уровне команд: создать Command в котором лежал бы такой-же ArrayList<Command> и execute() который бы их все выполнял. Тогда пульт даже не знает, что внутри одной из его команд лежит целый сценарий, он выполняет всего один execute() и забывает про это.
5) работа с пультом
public static void main(String[] args) {
    Controller myController = new Controller();
    SomeEntry someEnttity = new SomeEntity ();
    //create as much entities as you want...
    myController.addCommand(new SomeCommand(someEntry));
    //Appoint comands for your entities and add them to controller...
    myController.executeCommand(0);
    //press an button
}

A: Вот еще примитивный пример принта в консоль используя ScriptEngine, но не уверен что это именно то, что вам нужно, думаю в вашем случае скорее Java Compiler API
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine js = scriptEngineManager.getEngineByName("js");
    try {
         js.eval("print(\"someText\")");
    } catch (ScriptException e) {
        e.printStackTrace();
    }


Q: What Does the Electromagnetic Field Around Tapered Fiber Optic Cable Look Like? I am making a graphic that includes a fiber optic cable with a tapered portion. I would like to show in the graphic the EM field within and around the cable. I have a general idea of what the field would look like (for the non-tapered part, it's just within the cable, and at the tapered part, it extends outside the cable, decreasing exponentially with distance), but I can't find any examples of images that show something like this? Note that the way I am generating the graphic (LaTeX's TikZ images) does not actually plot the EM field exactly, I just specify some parameters that create a color gradient that is a good enough visual representation.
If someone could point me in the direction of an example that shows something like I'm talking about I would be very thankful.


Q: How to deal with ASP.NET Core 2.0 Chunked Web Api Call with EF Core I've got an Angular 6 application that makes calls to Web API controllers that use EF Core. By default, EF Core will not load foreign entities (lazy loading maybe?), so following suggestions, I used the following code to include such entities:
var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();

The problem is, when the controller returns members, it sends a header of:

Transfer-Encoding: chunked

Making the result/data unreadable by my Angular application (to be expected I guess, since the response is chunked).
Any suggestions? Is this standard behavior by Web API? What can I do to return a viable JSON?
Thanks

Edit #1, per johnny 5 request:
API Controller:
public async Task<IActionResult> GetDepartmentMembers([FromRoute] int id)
    {
        var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();
        if (members == null) { return NotFound(); }
        return Ok(members);
    }

Angular Service:
getDepartmentMembers(departmentId: number): Observable<Person[]> {
return this.http.get<Person[]>('http://localhost:49659/api/departments/' + departmentId + '/members');
}

Angular Component:
getDepartmentMembers(departmentId: number) {
this.departmentService.getDepartmentMembers(departmentId).subscribe(data => {
  this.departmentMembers = data;
});
}

Response Headers:

A: Just as a guess since you haven't posed the error, you're not returning the correct json, paticularly in the case of the 404, I'm not really familiar with the way your doing this, but usually you would just return a list of Persons
I'm not even sure why you would want to 404 just because the department doesn't have personal, instead of just returning an Empty List.
Id first verify by changing you're code to look something like this:
public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id)
{
    return await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();
}

If that works it's would appear to be how you're handing your NotFound responses,  then you can modify your code to use a global error handler.
Usually I create a custom exception e.g InvalidId to handle my 404's etc
public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id)
{
    var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();
    if (members == null) {
       throw new InvalidId();
    }
    return members;
}

Then you need to create a global error handler to handle your invalid id exception


Q: Application to FTP files from windows server I have an ASP.NET MVC website which clients post files to as part of an order process. These files can be up to 200MB. I have a need to transfer these files to another server via FTP. I don't really want to burden IIS with this. So was thinking of writing c# app to handle the file transfer which ran every x minutes and use windows service to run it.
Would this be an ok solution or is there something that could handle this for me already?
If I wrote the application should I let windows service handle the scheduling i.e. start the app every x minutes or should I just get it start the app on say startup and let the app handle the sleep/wakeup.
I was envisaging something quite rudimentary. Using SQL to track what needs uploading and has been uploaded. Are there any other considerations particular to a window service?
The website runs on iis8 on a windows 2012 vps.

A: One architecture tip -- use a simple executable and a scheduled task rather than write a service. You don't need to worry about memory leakage over months then.
You could probably implement this without writing any code -- you can script ftp.exe pretty effectively. I'd just script it to push all the files, and then, presuming FTP.EXE exited with 0, to clean out the uploads folder and rinse and repeat.


Q: Facebook Graph API, Development of Facebook page post targeting( make visible only specified country/city ) So I have developed APP with FB Graph API. This app writes posts on specified Facebook page. I decided that I need attach target of country and city to posts. So I have written code like this:
if( count( $DataArray ) > 0 ) {

            $MessageData = null;
            $AccessToken = $this->GetAccessToken();

            foreach( $DataArray as $ItemArray ) {
                $CleanTitle  = $this->ValidateTitle( $ItemArray['title'], $NotAcceptableWords );
                $GenerateMessageStr = "{$CleanTitle} - http://someutl/ID/{$Item['id']}/Feed/";

                $MessageData = array (

                    'access_token' => $AccessToken,
                    'message'      => $GenerateMessageStr,
                    'targeting' => "{'cities':'Tbilisi','countries':'Georgia'}"
                );

                try {
                    $this->FacebookObject->api("/{$this->FacebookPageId}/feed", 'POST', $MessageData);
                }
                catch (FacebookApiException $e) {
                    print_r($e);
                }

            }
        }

But after executing, the posts still seems like public and no some targeting is attached.

A: Try feed_targeting instead of targeting!
All parameters which you can target like languages,cities,counties are facebook specific. You can resolve them via autocomplete data :
"{'locales':[1001],'countries':[GE],'cities':[825886]}"
Nice feature for automatic posting with targeting but so bad documented in the Facebook documentation...

A: The right solution is: You generate the key for the city (using the API) and use the country's 2 letter code. $messageData will be:
$messageData = [
    'access_token' => $AccessToken,
    'message'      => $GenerateMessageStr,
    'targeting'    => "{'cities': <generated city key>,'countries':'GE'}"
]

If you're using API v2.8 and the current Facebook PHP SDK (5):
$request = new \Facebook\FacebookRequest(
    $fbApp,
    $accessToken,
   'POST',
   '/<facebook-page-id>/feed',
    [
        'message' => 'With Geolocate Ib',
        'targeting' => "{'geo_locations': {'cities': [{'key':" . <city key> . "}]}}"
    ]
);

The targeting flags makes sure only those in the specified city, region etc sees the post. feeds_targeting might still allow people not in those city/region to see the posts.


Q: Angular Forms: "No value accessor for ..." Using the AngularDart Material package. Could really use some help on this error:

"No value accessor for (username) or you may be missing formDirectives in your directives list."

Minimal setup (formDirectives is specified in directives list):
login.html
<form (ngSubmit)="onSubmit()" #form="ngForm">
        <material-input class="username" ngControl="username" [(ngModel)]="username"
            [required]="true"
            [floatingLabel]="true"
            label="Username">
        </material-input>
</form>

login.dart
import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'login',
  styleUrls: const ['style.css'],
  templateUrl: 'login.html',
  directives: const [formDirectives,MaterialInputComponent,]
)
class LoginComponent {

  String username;
  void onSubmit() {}
}

A: You need the ControlValueAccessor for material-input in your directives list.
Better to use materialInputDirectives instead of MaterialInputComponent directly as it has the other directives you might want to use to interact with the value.


Q: Semigroup epimorphism that is not a quotient by a subsemigroup It is not hard to see that if we have a semigroup epimorphism $\varphi\colon S\to T$, where $S$ is a group, then $T$ must be a group, and it is actually the quotient by the kernel, i.e. the set of $g\in S$ such that $\varphi(g)=\varphi(e)$
The natural argument for this does not seem to work if $S$ is merely a monoid. Namely, $\varphi$ is still constant on the cosets of the "kernel", but there seems to be no obvious reason for this to be an equivalent condition.
Are there some (natural?) examples when this is not true?
In particular, is it possible for a (two-sided?) cancellative $S$? If not, what if $S$ is not a monoid (but merely a semigroup)?

A: Here's a very simple example.  Let $S=\mathbb{N}$ and let $T=\{0,\infty\}$ with addition defined the obvious way.  Then there is a homomorphism $\varphi:S\to T$ which sends $0$ to $0$ and every positive number to $\infty$.  The kernel of $\varphi$ is trivial, but $\varphi$ is doing a lot more than just modding out the trivial submonoid!
For an example where both monoids are cancellative, let $S=\mathbb{N}^2$ and $T=\mathbb{N}$, and let $\varphi:S\to T$ be defined by $\varphi(a,b)=a+b$.  Once again, the kernel of $\varphi$ is trivial but it is not the quotient by the trivial submonoid.


Q: My website Google page rank is always showing zero even after doing SEO Please guide me to get my site in Google ranking as after doing some SEO still Google page rank is zero.

A: SEO is a wide field and PageRank one of possibly thousands of signals in Googles ranking algorithms: PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is... Wikipedia

A: Also what sort of time scale are you talking about? As in if you did all this in the last week it can take a long time for googles bots to re-index your site. Proper SEO can take months before reaping the benefits.


Q: How should I organize my source tree? I am an individual developer working, largely, on web-projects (W/LAMP) and, at times, on C/C++ (non-GUI) projects of about average scale.
I often struggle with structuring my source-code tree. In fact, usually, I don't complete a project without dumping the entire tree and rearranging the pieces three-four times which really takes up a lot of effort and moreover the end result does seem like a compromise.
Sometimes, I end up with over classification of source - very long tree of folders and sub-folders. At other times, I simply end up concentrating all files in a particular folder based on the larger purpose they serve and thereby leading to 'chaotic' folders in the source.
I would want to ask:

*

*Are there any principles/logic/best-practices that can help me better at structuring my source tree?

*Are there any graphical/diagrammatic techniques (for eg.: DFD in case of dataflow) that can help me visualize my source tree beforehand based on the analysis of the project?

*What strategy to adopt to structure multi-media files-tree associated with the project?

About the bounty: I appreciate existing answers with the members sharing their own practices, however, I'd like to encourage more general and instructive answers (or resources) and more responses from the members.

A: Ideally, the organisation has a single repository, the structure of which is intended to increase engagement between engineering & business and promote reuse.
...\products\
...\products\productName\
...\products\productName\doc\

...\systems\
...\systems\systemName\
...\systems\systemName\doc\
...\systems\systemName\res\
...\systems\systemName\build\
...\systems\systemName\test\

...\library\
...\library\libraryName\
...\library\libraryName\doc\
...\library\libraryName\build\
...\library\libraryName\test\

...\devops\

products
One folder per product; helps communicate how the software supports the business.
Ideally, each "product" is little more than a configuration file indicating which systems to invoke and how they are to be configured.
   The doc subfolder could contain the top-level brief\spec & any promotional materiel etc...
By separating products and systems we communicate the potential of reuse to the customer-facing side of the business, and break down per-product silos.
   (This contrasts with the "product line" approach to the same problem)
systems
One folder per system; helps communicate the primary capabilities & opportunity/value of the contents of the repository.

*

*"Configuration management" files specifying build & deployment environments.

*System-level testing configuration (could be significant quantity).

*Top level logic & functionality; most heavy lifting being done by library functions.

library
Reusable components invoked by various systems.
   Most development activities are organised around the production of libraries, rather than systems, so reuse is "baked in" to the development process.
devops
Build, Continuous Integration & other Development Automation functionality.
Conclusion
The source tree is a key piece of documentation, and shapes the approach, structure and psychology of the business' relationship with its proprietary technology.
The drivers for this approach are explained in a bit more depth in my answer to this question: https://softwareengineering.stackexchange.com/questions/43733/who-organizes-your-matlab-code/59637#59637

A: I can't really give you much advice related to webprojects, but here's how I structure my tree in a programming project (mainly from a C/C++ perspective):

*

*/

*

*src — Source files written by myself

*ext — Contains third-party libraries

*

*libname-1.2.8

*

*include — Headers

*lib — Compiled lib files

*Donwload.txt — Contains link to download the version used

*ide — I store project files in here

*

*vc10 — I arrange project files depending on the IDE

*bin — Compiled exe goes here

*build — The compiler's build files

*doc — Documentation of any kind

*README

*INSTALL

*COPYING

A few notes:

*

*If I'm writing a library (and I'm using C/C++) I'm going to organize my source files first in two folders called "include" and "src" and then by module. If it's an application, then I'm going to organize them just by module (headers and sources will go in the same folder).

*Files and directories that I listed above in italics I won't add to the code repository.

A: I dont really know about conventions but all of my main projects are done using Symfony Framework and i have get used to a tree structure like follows:
root/

*

*apps

*app_name

*

*config (app specific config files)

*lib (app specific php files)

*modules ( modular distribution of functionality)

*

*module_name

*

*templates (html)

*actions (php code)

*confing (project config files)

*lib (php code that could be use in hole project)

*model (classes that represent the project information)

*

*base

*form (php files that handle forms, this could be quite difficult to achieve without symfony)

*

*base (base form classes)

*web

*css

*

*images

*file.css

*js

*log (log files that might be generated)

*data (data specific information, like sql patches, or whatever)

*sql

*plugins (libraries used that could be merged with any app of the project)

If you are interested, please read the symfony documentation on the matter for further inquired (MVC and Code Organization on Symfony).

A: What I'm trying to do for each project is similar as :

*

*src - source files, a folder for each namespace/package to easily retrieve files (even header files for C/C++)

*ext - for externals/third-party libraries, it is simple to add externals (such as SVN repositories). Inside, a folder for each libraries (binaries and include files)

*bin - for built binaries, could be quickly exported for release

*

*inc - for C/C++ headers file (copied by IDE/makefile/etc...)

*out - for all temporarily generated files (.class, .obj etc...) and it could be ignored (for example by SVN)

*doc - for any documentation, usually generated with Doxygen

*res - by placing resources here, it's possible to separate text source files and binary resources used by the program. I don't really have specific hierarchy inside.

*

*config - for some configuration files

*drawable - for some pictures or icons

All IDE's files or makefiles are saved directly at the root if you only use one of them.

A: My recommendation is to download a variety of frameworks or engines and see how huge development teams handled their folders layout.
There are so many ways to organize files that it's better to choose one, and try to stick to it at any given project. Stick to a particular convention until completion or revamping to avoid bugs and loosing unnecesary time.
You can download Laravel, Symphony or Codeigniter frameworks for web projects to have an instant folder layout that works.
So I will try to convey a folders layout common to any development:
MVC (Model View Controller) gives a good paradigm of organization.
Root source code could be src (C++) or app (web development)
A file structure that does not have a clear objective for the classes that it groups definitely will cause confusion. It's not only to organize code, instead it can sustain auto-loaders, class factory, wrap local storage, remote storage and namespacing.
This folder structure is derived and simplified from Laravel Framework. My preference on this post is plural naming but I use singular words in my projects.

src/storage (models/file-storage/api/mysql/sql-lite/memcached/redis implementations)
src/repositories (A wrapper of 'storage implementations' with some storage logic, a common interface and return result convention.)
src/services | logic | entities  (App bussiness logic)
src/controllers (Used on web development to route server requests to your services)
src/modules | systems (Modular systems that extend your framework general functionality. Services can use modules but not viceversa)
src/helpers (Helper or wrapper classes like eg. string manipulation. Many times this could be on libs|vendor when third party)
src/types (Named enums)
public | build | output (web or c++)
config (Setup files. YAML is becoming popular for cross-platform config files)
cache
logs
lang (en/es/ru/...)
bootstrap (Starts the framework and app)
docs (Documentation written in markdown format .md)
tests (Unit testing)
database/migrations  (Create database structure from scratch)
database/seeds (Fills your database with dummy data to test)
libs | vendor (all third party software. 'libs' on C++ and 'vendor' usually on php)
assets | resources (images/sounds/scripts/json/any media)

A: The source tree layout should reflect the architecture; as a corollary, a well-structured architecture can lead to a well-structured source tree layout.  I suggest reading up on the POSA1 Layers pattern, attempting to fit your architecture into a layered structure, then naming each of the resulting layers, and using that as a basis for your source hierarchy.  Taking a common three-tier architecture as a baseline:

*

*presentation/webService (present a web-service interface to our business logic)

*logic/* (business logic modules go in here)

*storage/sql (back-end storage APIs here - this uses a SQL interface to store to a database)

*util/* (utility code - usable by all other layers, but that does not refer outside util, goes here)

Note that the layers do not contain code directly, but rather are strictly used to organize modules.
Within a module, I use the following sort of layout:

*

*<module> (path to module directly; defines modular interface)

*<module>/impl/<implName> (a specific implementation of the modular interface)

*<module>/doc (Documentation for using the module)

*<module>/tb (unit-test code for the module)

where the <module> is located in the repository according to the layer to which it belongs.

A: I do something like this. Works well for a cross platform game I'm doing in my spare time. Unfortunately in work, things are much less organized...
Output                      <-- Build outputs
Docs
External
   <libname>
      Include
      Lib
Data
<ProjectName>.xcodeproj
<ProjectName>VS2010
Source
Temp                        <-- Intermediate stuff from builds and other tools
Tools

A: For my teams, we try to enforce a standard structure across projects to make is easy to find things as the team switches context and to avoid having to relearn each time through. Not all projects need all systems so we start with the minimal set.

/Source/Component/Language
/Source/Component/3rd Party/
/Documentation/Requirements
/Documentation/Design
/Tests/Automated/Unit
/Tests/Automated/ToolName
/Tests/Manual

This results in some duplication, particularily under the 3rd Party code and libraries, but at least we never forget the answer to something like "What uses the RogueWave Editor?"

A: I like the ideas presented in this page www.javapractices.com/topic/TopicAction.do?Id=205. Basically, the recommendation is to organize your project into features(or modules, components). In addition to the reasons presented there:

*

*Less cognitive load when you think about the scope of the code you are working on since you have a guarantee that any code in the feature your are working on is "feature-private".

*There is an added sense of security when you are guaranteed that you are only modifying code for given a feature. E.g., you won't break anything other than the feature you are working on. Again this is because of the "feature-private".

*Less cognitive load simple because there is less files you can see for a given package. I am sure everyone has seen a package that contain more than 15 files.

Note this is focused on Java packages (aka namespaces). For big projects, I do recommend, for the same reasons, dividing the project into multiple projects (as in multiple maven projects) that represents a business feature. For maven projects, I recommend this reading.
So far, the projects I was/am involved in does not follow these. There are many reasons, but here's a few:

*

*The misunderstanding of Java default access modifier (most misunderstood access modifier as per this book)

*"Argumentum ad populum": Prevailing culture of package-by-layer (probably caused by Reason #1)

I think there is a missed opportunity to prevent complexity if project source organization is not taken seriously at the start of the project as the architect Alexander said:

"As any designer will tell you, it is the first steps in a design
  process which count for most. The first few strokes, which create the
  form, carry within them the destiny of the rest." - Christopher
  Alexander

Depending on the size & complexity of a project, the missed opportunity to cut costs or ROI can be really big. (I'm interested to see a study to see the exact numbers for this)

A: The Maven Standard Directory Layout is kind of specific to Java, but it may serve as a good basis for other types of projects as well.
Here is the basic structure (you could replace the java directories with php,cpp, etc):
src/main/java       Application/Library sources
src/main/resources  Application/Library resources
src/main/filters    Resource filter files
src/main/assembly   Assembly descriptors
src/main/config     Configuration files
src/main/webapp     Web application sources
src/test/java       Test sources
src/test/resources  Test resources
src/test/filters    Test resource filter files
src/site            Site
LICENSE.txt         Project's license
NOTICE.txt          Notices and attributions required by libraries
README.txt          Project's readme

The structure basically breaks down to src/main and src/test then grouped by type.

A: With object orientated languages, you have the ability to build namespaces. That logical breakdown used to separate parts of the application to avoid coupling is the primary source of logical file location breakdown. Using coupling as a reason for breaking apart namespaces is a good place to start http://en.wikipedia.org/wiki/Software_package_metrics.
Others have spoken about setting up the project in relation to build, but once you get into the source itself, it's about what makes sense - just use how you logically break apart the code anyways.


Q: Fibrant Replacement Functor: its action on morphisms I'm reading the below in Model Categories by Hovey.

And before we go further, here is the definition of model category I am working with:

From reading the answer from Fibrant replacement functor, I know how $Q$ acts on objects, but I'm still not sure how it acts on morphism.
My guess would be the following.
Let's denote $\phi$ as the initial object. I want to know what is $Q(f \colon X \rightarrow Y)$.
Consider the factorization of $i_1 \colon \phi \rightarrow Y$ by $i_1 = \beta(g) \alpha(g)$ and the factorization of $i_2 \colon \phi \rightarrow X$ by $i_2 = \beta(h) \alpha(h)$, where $\alpha(g) \colon \phi \rightarrow QY$ and $\alpha(h) \colon \phi \rightarrow QX$.
We may consider the following commutative square.

$\alpha(h)$ is a cofibration, and $\beta(g)$ is trivial fibration, so there is a lift $k \colon QX \rightarrow QY$.
Now, I want to say $Qf = k$, but this lift may not be unique, so this poses a problem.
Any help would be appreciated, thanks!

A: You wrote "fibrant replacement functor", but used the notation $Q$, which is the notation for the cofibrant replacement functor. I went with the the fibrant one, but of course, for $Q$, the story is entirely dual.
Well if $f: X\to Y$, you have a morphism of morphisms:
$\require{AMScd}\begin{CD} X @>>> Y \\
@VpVV @VqVV \\
*@>>> *\end{CD}$
and since $(\gamma,\delta)$ is by assumption a functorial factorization, you get a map $\gamma(p)\to \gamma(q)$, that is, a commutative square:
$\begin{CD}X @>>> Y \\
@V\gamma(p)VV @V\gamma(q)VV \\
R(X) @>>> R(Y)\end{CD}$
with $R(X) \to R(Y)$ being given as part of the data of $\gamma((f,id_*))$ (note that in $\gamma(p)$, we see $p$ as an object of the arrow category, while in $\gamma((f,id_*))$, $(f,id_*)$ is an arrow in the arrow category)
The fact that this map $R(f): R(X)\to R(Y)$ makes $R$ into a functor follows from the fact that $\gamma$ is a functor and that $(g,id_*)\circ (f,id_*)= (g\circ f,id_*)$


Q: Python Regex to Check Long List of Strings Match a Pattern I would like to test a string:
BASE[A-Z] + SINGLE CHAR {F,G,H,J,K,M,N,Q,U,V,X,Z} + SINGLE NUMERIC [0-9]
The 'BASE' is at least one character long.
eg. 'ESZ6' -> True, 'ESSP6' -> False
I appreciate I can do:
import re
prog = re.compile('[A-Z]+[FGHJKMNQUVXZ]{1}[\d]{1}')

...

if prog.search(string):
    print('This matched...')

I then wanted to use:
matches = [i for i in items if prog.search(item)]

Is this the optimal way of implementing this?

A: This depends on what you mean by, 'test a string'.  Do you want to check if the entire string matches your pattern, or if the pattern just happens to occur in your string, e.g. 'ESZ6' vs. "I've got an ESZ6 burning a hole in my pocket'.  Can other characters abut your target, eg. '123ESZ6ARE'?
Assuming we're just testing individual tokens like 'ESZ6' and 'ESSP6', then here are some code ideas:
import re

items = ('ESZ6', 'ESSP6')

prog = re.compile(r"[A-Z]+[FGHJKMNQUVXZ]\d$")

matches = [item for item in items if prog.match(item)]

Use .match() instead of .search() unless you want an unanchored search.  Drop the final '$' if you want the end unanchored.  (If using Python 3.4 or later, and want an anchored search, you can probably drop the '$' and use .fullmatch instead of .match)
Pattern match operators only match one character sans repetition operators so you don't need the {1} indications.  Use raw strings, r"\d", when dealing with patterns to keep Python from messing with your back slashes.
Your description and your examples don't match exactly so I'm making some assumptions here.


Q: Create an excel output file from Biztalk as resulting of a query from SQL I have a query in SQL Server that returns me 5 columns with some data.
I want to create a BizTalk application that saves me the result of my query in an Excel file.
I will create a SP for polling, using wcf adapter to do the communication between BT and SQL.
I don't know how to generate a file.xls. Is it possible?
Thanks

A: Any .xls file can be saved as a XML Workbook ( File-Save As from Excel), which is an XML document. You can see that this an XML doc you open it in notepad.
Now, the trick is to get hands on the schema used for generating this, which is perhaps proprietary for microsoft and may not be given out. So, the workaround is, if your excel file is failrly simple, you can save it as the Workbook and see the XML and generate an XSD based on it.
Now, map your incoming XML to this Workbook XSD and the resultant XML will open directly in Excel, when you double-click on it.
Hope this helps.

A: in that case you need to developed a custom pipeline
biztalk-custom-excel-pipeline-component