text:
Q: How do I select shapefiles to be converted to GeoJSON in folder with multiple shapefiles? How do I only select .shp's to read and then convert to .geojson. The homefolder has 3 different shapefiles and this code currently converts every single file in the folder to a .json. Just trying to speed up the running process. I have some other issues too with naming conventions that I will deal with next. Among other things, this is a work in progress.
homefolder = "D:/UW/Winter_2016/501/pythonProject/publicLandsData/newShapefiles/"

# read the shapefiles
filenames = os.listdir(homefolder)

for filename in filenames:
  reader = shapefile.Reader(homefolder + os.path.splitext(os.path.basename(filename))[0])
  print filename
  fields = reader.fields[1:]
  field_names = [field[0] for field in fields]
  buffer = []
  print filename + "buffer dictionary done"
  for sr in reader.shapeRecords():
      atr = dict(zip(field_names, sr.record))
      geom = sr.shape.__geo_interface__
      buffer.append(dict(type="Feature", \
      geometry=geom, properties=atr))

# write the GeoJSON file
#currently it saves into the wrong directory..and all one shapefile, might be nice to be in multiple geojson's
#list directory "homefolder" in variable filenames
  filenames = os.listdir(homefolder)

  for filename in filenames:
#for loop to rename local government to loca
    geojson = open(((os.path.splitext(os.path.basename(filename))[0]) + ".json"), "w")
    #os.rename(os.path.join(homefolder, filename), os.path.join(homefolder, (filename.replace('.shp', 'shp'))))
    geojson.write(dumps({"type": "FeatureCollection",\
      " features": buffer}, indent=2) + "\n")
    geojson.close()

I have tried using basename, selecting only ".shp" files with .endwith() etc to no avail. Suggestions?
I found this shp to geojson conversion code at the link below:
https://gist.github.com/frankrowe/6071443

A: Try replacing line 4 with this:
filenames = [ f for f in os.listdir(homefolder) if os.path.isfile(os.path.join(homefolder,f)) and f.endswith(".shp")]

This will create a list containing only files with the extension ".shp"
Expanded for clarity:
# create empty list
filenames = []
# begin iterating over files in homefolder directory
for f in os.listdir(homefolder):
    # if the file is indeed a file and it ends with .shp append the name to the list
    if os.path.isfile(os.path.join(homefolder,f)) and f.endswith(".shp"):
        filenames.append(f)

A: Look at PyShp_geointerface.py with a generator
import shapefile
def records(filename):
   # generator
   reader = shapefile.Reader(filename)
   fields = reader.fields[1:]
   field_names = [field[0] for field in fields]
   for sr in reader.shapeRecords():
      geom = sr.shape.__geo_interface__
      atr = dict(zip(field_names, sr.record))
      yield dict(geometry=geom,properties=atr)
 # for one file
  buffer = [rec for rec in records('shapefile.shp')]
  result = {"type": "FeatureCollection"," features": buffer}

For many files, simply loop through the files
for dir, subdir, files in os.walk(a_folder):
    for fname in files:
        if fname.endswith(".shp"):
           buffer = [rec for rec in records(os.path.join(dir, fname))]
           result = {"type": "FeatureCollection"," features": buffer}
           # write the resulting GeoJSON file
           name = os.path.splitext(fname[0]+'.geojson')
           with open(name, "w") as outfile:
               json.dump(result,outfile)


text:
Q: Legend outside the plot do you know how can I put the Legend outside the plot area?
(Both in code and in xaml)
Thank you for your help!
cis

A: There is no implementation in the current D3 library to move the legend outside the plotter. The most that can be done is to move the legend to a different place in the plotter by editing the Legend.xaml.cs file in the source code. You will have to change the dependency properties in the code-behind to move the legend around the area of your plotter.
If you want to put your legend outside the plotter, you will have to recreate the Legend.xaml to make it independent of the plotter, but still receive the same information it needs to create the legend. If you do manage to do that, please post it here as an answer!

A: Maybe the answer came a little late, but I also ran into this problem.
This is the style of Microsoft.Research.DynamicDataDisplay.Plotter.cs:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Microsoft.Research.DynamicDataDisplay"
                    xmlns:common="clr-namespace:Microsoft.Research.DynamicDataDisplay.Common">
  <Style x:Key="defaultPlotterStyle" TargetType="{x:Type local:Plotter}">
    <Setter Property="Control.Background" Value="White"/>
    <Setter Property="Control.BorderBrush" Value="Black"/>
  </Style>
  <ControlTemplate x:Key="defaultPlotterTemplate" TargetType="{x:Type local:Plotter}">
    <common:NotifyingGrid Name="PART_ContentsGrid" Background="{TemplateBinding Control.Background}">
      <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition/>
        <RowDefinition Height="auto"/>
      </Grid.RowDefinitions>
      <common:NotifyingStackPanel Name="PART_HeaderPanel" Orientation="Vertical" Grid.Row="0"/>
      <common:NotifyingGrid Name="PART_MainGrid" Row="1">
        <Grid.RowDefinitions>
          <RowDefinition Height="auto"/>
          <RowDefinition/>
          <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="auto"/>
          <ColumnDefinition/>
          <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>
        <common:NotifyingGrid Name="PART_CentralGrid" Column="1" Row="1" ClipToBounds="true" Background="Transparent"/>
        <common:NotifyingCanvas Name="PART_MainCanvas" Grid.Column="1" Grid.Row="1" ClipToBounds="true"/>
        <Rectangle Name="PART_ContentBorderRectangle" Grid.Column="1" Grid.Row="1"
                   Stroke="{TemplateBinding Control.BorderBrush}"
                   StrokeThickness="{TemplateBinding Control.BorderThickness}"/>
        <common:NotifyingStackPanel Name="PART_LeftPanel" Grid.Column="0" Grid.Row="1" Orientation="Horizontal"/>
        <common:NotifyingStackPanel Name="PART_RightPanel" Grid.Column="2" Grid.Row="1" Orientation="Horizontal"/>
        <common:NotifyingStackPanel Name="PART_BottomPanel" Grid.Column="1" Grid.Row="2" Orientation="Vertical"/>
        <common:NotifyingStackPanel Name="PART_TopPanel" Grid.Column="1" Grid.Row="0" Orientation="Vertical"/>
      </common:NotifyingGrid>
      <common:NotifyingCanvas Name="PART_ParallelCanvas" Grid.Column="1" Grid.Row="1"/>
      <common:NotifyingStackPanel Name="PART_FooterPanel" Orientation="Vertical" Grid.Row="2"/>
    </common:NotifyingGrid>
  </ControlTemplate>
</ResourceDictionary>

So, the trick is you have to modify the legend's parent and its parent properties, to move the desired elements to the right place in the right size.
PART_CentralGrid element contains the Legend item.
I did the following:
legendGrandparent.Width = plotter.Width - 100;
legendGrandparent.HorizontalAlignment = HorizontalAlignment.Left;
legendParent.ClipToBounds = false;
legend.LegendLeft = plotter.Width - 125;

where legendGrandparent is the PART_MainGrid and legendParent is the PART_CentralGrid.
Before:

After:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt) *which credentials should be provided in kerebros for this exception to resolve when running apache crunch mapreduce pipleline?
No difference after logged in through kinit command. *
Logs are as follows:
WARN [main] org.apache.hadoop.security.UserGroupInformation: PriviledgedActionException as:{user_id} (auth:SIMPLE) cause:javax.security.sasl.SaslException: GSS initiate failed [Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)]
2019-12-09 02:01:45 WARN [main] org.apache.hadoop.hbase.ipc.RpcClientImpl: Exception encountered while connecting to the server : javax.security.sasl.SaslException: GSS initiate failed [Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)]
2019-12-09 02:01:45 FATAL [main] org.apache.hadoop.hbase.ipc.RpcClientImpl: SASL authentication failed. The most likely cause is missing or invalid credentials. Consider 'kinit'.
javax.security.sasl.SaslException: GSS initiate failed [Caused by GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)]

    at com.sun.security.sasl.gsskerb.GssKrb5Client.evaluateChallenge(GssKrb5Client.java:211)
    at org.apache.hadoop.hbase.security.HBaseSaslRpcClient.saslConnect(HBaseSaslRpcClient.java:181)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection.setupSaslConnection(RpcClientImpl.java:618)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection.access$700(RpcClientImpl.java:163)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection$2.run(RpcClientImpl.java:744)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection$2.run(RpcClientImpl.java:741)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1917)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection.setupIOstreams(RpcClientImpl.java:741)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection.writeRequest(RpcClientImpl.java:907)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl$Connection.tracedWriteRequest(RpcClientImpl.java:874)
    at org.apache.hadoop.hbase.ipc.RpcClientImpl.call(RpcClientImpl.java:1246)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.callBlockingMethod(AbstractRpcClient.java:227)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient$BlockingRpcChannelImplementation.callBlockingMethod(AbstractRpcClient.java:336)
    at org.apache.hadoop.hbase.client.ClientScanner.initializeScannerInConstruction(ClientScanner.java:167)
    at org.apache.hadoop.hbase.client.ClientScanner.<init>(ClientScanner.java:162)
    at org.apache.hadoop.hbase.client.HTable.getScanner(HTable.java:862)
    at org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl.restart(TableRecordReaderImpl.java:91)
    at org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl.initialize(TableRecordReaderImpl.java:169)
    at org.apache.hadoop.hbase.mapreduce.TableRecordReader.initialize(TableRecordReader.java:134)
    at org.apache.crunch.io.hbase.inputformat.MultiTableInputFormatBase$1.initialize(MultiTableInputFormatBase.java:135)
    at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.initialize(MapTask.java:554)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:792)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1917)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

Caused by: GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
    at sun.security.jgss.krb5.Krb5InitCredential.getInstance(Krb5InitCredential.java:147)
    at sun.security.jgss.krb5.Krb5MechFactory.getCredentialElement(Krb5MechFactory.java:122)
    at sun.security.jgss.krb5.Krb5MechFactory.getMechanismContext(Krb5MechFactory.java:187)
    at sun.security.jgss.GSSManagerImpl.getMechanismContext(GSSManagerImpl.java:224)
    at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:212)
    at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:179)
    at com.sun.security.sasl.gsskerb.GssKrb5Client.evaluateChallenge(GssKrb5Client.java:192)
    ... 39 more

A: try {
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws IOException {
            conn=ConnectionFactory.createConnection(conf);
            return null;
        }
    });
}
catch (InterruptedException e) {
    e.printStackTrace();
}

This worked for me :)


text:
Q: Assigning one variable to another based on (and within) macro I am using RStudio 0.98.1062.
What I am trying to do is within a macro to create a new variable based on another one (that already has a suffix defined by me) in the same dataframe . The name of the data frame, and the index(suffix) are macro variables.
Here is my code:
read_data <- defmacro(fileName, monthIndex, dfName,
                          expr = {
  dfName <- read.table(fileName, head=TRUE,sep = ",")
  #add suffix vor the variables for the corresponding month
  colnames(dfName) <- paste(colnames(dfName),monthIndex, sep = "_")
  #dfName["EasyClientMerge"]<-numeric()

  within(dfName, assign("EasyClientMerge",   paste("dfName$EasyClientNumber",monthIndex,sep="_"))

})

if the macro parameters are (..., monthIndex=6, dfName= m201309) I expect the following variable to be created
m201309$EasyClientMerge<-m201309$EasyClient_6
first of all a new variable is not created within the data frame and second of all it seems that a string is taken "m201309$EasyClient_6" rather than reference to dataframe & variable name
Thanks a lot in advance cause I am kind of stuck!

A: If you really insist on producing hard coded data.frames within a function (in my opinion a bad choice), you can do it like so.
> dfName <- "new.df"
> assign(dfName, value = list(clientMerge = 1:10, clientMerge2 = 1:10))
> as.data.frame(new.df)
   clientMerge clientMerge2
1            1            1
2            2            2
3            3            3
4            4            4
5            5            5
6            6            6
7            7            7
8            8            8
9            9            9
10          10           10


text:
Q: Saving Multiple Select in input I have model for

*

*user(id,name)

*section(id,name)

*section_users(id,user_id,section_id)

The admin adds all the  users and sections separately. Once theses are added I want the admin to  selects the section and add all the users in it in section_users

I have a select input with multiple set to true. How do i save this data the cakephp way along with validation.
<?php echo $this->Form->input("section_id"); ?>
<?php echo $this->Form->input("user_id", array('multiple'=>'checkbox')); ?>

This generates
Array
(
    [section_id] => 1
    [user_id] => Array
        (
            [0] => 3
            [1] => 4
        )

)

I know i can loop and convert to this and use saveAll or saveMany but what is the cakephp way/right way to do it.
Array
(
    [0] => Array
        (
            [section_id] => 1
            [user_id] => 3
        )
    [1] => Array
        (
            [section_id] => 1
            [user_id] => 4
        )

)

A: As already mentioned, this is exaplained in the docs, please read them, and in case you don't understand them (which would be understandable as the HABTM section is a little confusing and requires some trial & error), tell us what exactly you are having problems with.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
Based on the examples shown, the format for saving multiple X to Y should be
Array
    (
        [Section] => Array
            (
                [id] => 1
            )
        [User] => Array
            (
                [User] => Array(3, 4)
            )
    )

The corresponding form could look like this:
<?php echo $this->Form->create('User'); ?>
    <?php echo $this->Form->input('Section.id'); ?>
    <?php echo $this->Form->input('User', array('multiple' => 'checkbox')); ?>
<?php echo $this->Form->end('Add Users'); ?>

And the data would be saved via the Section model, that way its modified column is being updated properly.
public function addUsersToSection($id) {
    // ...
    if($this->request->is('post')) {
        if($this->Section->save($this->request->data)) {
            // ...
        } else {
            // ...
        }
    } else {
        $options = array(
            'conditions' => array(
                'Section.' . $this->Section->primaryKey => $id
            )
        );
        $this->request->data = $this->Section->find('first', $options);
    }

    $users = $this->Section->User->find('list');
    $this->set(compact('users'));
}

Another way would be to restructure the array as shown by Vinay Aggarwal, that works fine, the only difference is that it requires saving through the join model, and consequently it doesn't update the Section models modified column.

A: CakePHP has the saveMany function, as mentioned in the documentation:
Model::saveMany(array $data = null, array $options = array())¶

A: This is HABTM relation, first of all you need have relation setup in SectionUser model. Then you can use saveAll() method to save all records at once.
Array
(
    [0] => Array
    (
        [user_id] => 33
        [section_id] => 9
    )

    [1] => Array
    (
        [user_id] => 33
        [section_id] => 10
    )
)

Make sure your data array is in above given format.
$this->SectionUser->saveAll($data);


text:
Q: How to install tomcat plugin in Eclipse I am using Eclipse as my SDK for web project and I need tomcat integration with Eclipse. I am on my Ubuntu machine. How can I do the integration stuff? How and from where I can download and install tomcat plugin?

A: You can download Eclipse for Java EE

A: *

*Download the Eclipse Tomcat Plugin from Marketplace

*Go to window->Preference.Find Tomcat configuration from the left
panel and configure it.

A: you have to do several things:

*

*download and extract Tomcat

*Install the WTP tools using Eclipse built-in update mechanisms or download the Eclipse Java EE prepackaged build: http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigor

*Configure Tomcat in Eclipse

The following screenshot shows my Eclipse configuration (Ubuntu Natty 11.04, eclipse Helios 3.6, Tomcat 7.0.12):

A: This solution worked for me:

*

*Download zip file of the Tomcat Plugin from https://sourceforge.net/projects/tomcatplugin/

*Install the .zip file from Eclipse. You could use the guide: 1.makesure your .zip file is an valid Eclipse Plugin found in another question.


text:
Q: Item checkout on different orders at the same time for limited stock Having an issue where i have an Item in my inventory which has limited stock of 1. As soon as my mailer goes out people tend to buy at the exact same time.
The problem is when User1 adds  the product to his cart, and User2 adds to his cart then both User1 and User2 checkout at the exact same time it generates an order for both.It should pick-up there was 1 stock so only User1 should be able to checkout.
Just want to know how someone else wil handle this situation seen allot of people running into this bug.
any ideas ?
read some woocommerce solution:
https://github.com/woocommerce/woocommerce/issues/12467


text:
Q: Gridview sorting not working with Linq to SQL I am getting following error while sorting on my gridview. "The data source does not support server-side data paging." I am not using obejctdatasource and linqdatasource. Every example or solution on stack overflow I found is using obejctdatasource. [like: http://www.devtoolshed.com/content/gridview-objectdatasource-linq-paging-and-sorting]
Below is my code. How can I fix sorting error in my code? Can I fix it without using objectdatasource.

public List<SearchLoanViewItem> GetSearchresult(EmpowerEntities empower)
        {
            var searchresult = (from m in dbo.MTGTERMS
                                join p in dbo.PROPINFOes
                                    on m.LNKEY equals p.LNKEY
                                join b in dbo.BORRINFOes
                                    on m.LNKEY equals b.LNKEY
                                join d in dbo.DBLOCKS
                                    on m.LNKEY equals d.LNKEY
                                join u in dbo.UCODES3
                                    on m.LNKEY equals u.LNKEY
                                join c in dbo.CODES
                                    on m.LNKEY equals c.LNKEY
                                where b.WHICHBORR == 1
                                      && (c.APPSTATS == null ? "" : c.APPSTATS) != "DEL"
                                select new SearchLoanViewItem
                                           {
                                               lnkey = m.LNKEY,
                                               prop_addr = p.PROP_ADDR,
                                               networklocked = d.NETWORKLOCKED == "Y" ? "Yes" : "No",
                                               username = (d.USERNAME ?? ""),
                                               mailbox = d.MAILBOX,
                                               borr_name = b.BORR_NAME,
                                               ssn = b.BORR_SSN,
                                               phone = b.BORR_PHONE,
                                               employee_loan = (u.CODE67N ?? -1)
                                           }).Take(5).ToList();
            return searchresult;
        }

        public void ShowSearchResults()
        {
            try
            {
                var empower = new EmpowerEntities();
                var searchresult = GetSearchresult(empower);

                gdvSearchResult.DataSource = searchresult;
                gdvSearchResult.DataBind();
            }
            catch (Exception ex)
            {
                Logger.log("ucSearchLoan", ex.Message, Logger.ERROR);
            }
        }

 protected void Paging_gdvSearchResult(object source, GridViewPageEventArgs e)
        {
            gdvSearchResult.PageIndex = e.NewPageIndex;
            ShowSearchResults();
        }

protected void gdvSearchResult_SortCommand(object source, GridViewSortEventArgs e)
        {
            try
            {
                var empower = new EmpowerEntities();
                var searchresult = GetSearchresult(empower);

                if (SearchSortType == Constants.ASC)
                    SearchSortType = Constants.DESC;
                else
                    SearchSortType = Constants.ASC;

                SeachSortField = e.SortExpression.ToString();

                if (SeachSortField.Equals(Constants.ASC))
                    gdvSearchResult.DataSource = searchresult.AsEnumerable().OrderBy(a => a.GetType().GetProperty(SeachSortField).GetValue(a, null));
                else
                    gdvSearchResult.DataSource = searchresult.AsEnumerable().OrderByDescending(a => a.GetType().GetProperty(SeachSortField).GetValue(a, null));

                gdvSearchResult.DataBind();

            }

and my gridview looks like below.

    <asp:GridView runat="server" ID="gdvSearchResult"
             AutoGenerateColumns="false" OnRowCommand="gdvSearchResult_RowCommand" OnRowCreated="gdvSearchResult_RowCreated" PageSize="2" AllowPaging="true"      AllowSorting="true" OnPageIndexChanging="Paging_gdvSearchResult" OnSorting="gdvSearchResult_SortCommand">

A: Issue was fixed when I added casting [Cast<object>().ToList() part]
 if (SeachSortField.Equals(Constants.ASC))
                    gdvSearchResult.DataSource = searchresult.AsEnumerable().OrderBy(a => a.GetType().GetProperty(SeachSortField).GetValue(a, null)).Cast<object>().ToList();
                else
                    gdvSearchResult.DataSource = searchresult.AsEnumerable().OrderByDescending(a => a.GetType().GetProperty(SeachSortField).GetValue(a, null)).Cast<object>().ToList();


text:
Q: Using AudioFileStreamParseBytes to parse bytes by reading from a file does not call kAudioFileStreamProperty_ReadyToProducePackets I am trying to parse bytes by opening a audio file (M4A), reading 2048 bytes in a loop and passing it to AudioFileStreamParseBytes. This does not call the callback with the property kAudioFileStreamProperty_ReadyToProducePackets. But the property kAudioFileStreamProperty_FileFormat is being successfully called. (So I know the callback mechanism is working.)
Questions :

*

*Can I use AudioFileStreamParseBytes to parse audio data by reading from a local file ? Most examples show how to use AudioFileStreamParseBytes by parsing HTTP stream data, but not reading from a local file.

*Has anyone tried to do the above and has been successful processing audio files ?

NOTE : The reason I am not using AudioFileOpenWithCallbacks to open the m4a file is that the api call is failing to open the following file after downloading it locally ( http://www.arsenal-music.com/podcast/arsenal-podcast-05.m4a ). This m4a file has images embedded in it and AudioFileOpenWithCallbacks is not able to parse the file. At the same time I have used Matt Gallagher AudioStreamer code that opens this file, parses it and plays it fine. So I am leaning towards using AudioFileStreamerParseBytes by reading data from a local file. (As far as I understand there should be no difference whether the data is coming from HTTP stream or a local file. But I could be wrong.)
I do not see any errors in the any API calls (just in case someone asks me this question). I can paste the code if needed, but all I want to know is if the approach of reading from file and passing it to AudioFileStreamParseBytes will work or not ?

A: After some testing I found that one can use AudioFileStreamParseBytes to parse bytes that are read from a local file. Data need not come from a Http stream.


text:
Q: Delphi draw lines in a PlotGrid with canvas I am using a TPlotGrid because I want to try to put some lines in it. Look at this simple code:
procedure TForm1.Button1Click(Sender: TObject);
var a,b: TPointF;
begin
 a.X := 0;
 a.Y := 0;
 b.X := 1;
 b.Y := 5;
 PlotGrid.Canvas.DrawLine(a,b,1);
end;

As you can see here I have the PlotGrid on Tab2 and the button on Tab1. Why isn't this code adding a line to the PlotGrid? A line should appear when I click on the button (going from (0;0) to (1;5)).
I am new with Canvas and in particular with the TPlotGrid but the latter is not very popular on Google and there isn't much on the documentation (only 1 page with a simple example).

A: TPlotGrid provides a canvas with the gridlines but it has no means of storing your drawing elements (lines, rectangles etc.). The first thing you need to do, is arrange for storage of data. In your example move the points a and b to the private section of your form so they are available at any time.
In a real application you would store the elements in some data structure elsewhere.
In your button OnClick event set values to those points and call PlotGrid.Repaint;:
procedure TForm4.Button1Click(Sender: TObject);
begin
  a.X := 0;
  a.Y := 0;
  b.X := 300;
  b.Y := 100;
  PlotGrid1.Repaint;
end;

Create an OnPaint event for the TPlotGrid, here you do the actual drawing:
procedure TForm4.PlotGrid1Paint(Sender: TObject; Canvas: TCanvas;
  const ARect: TRectF);
begin
  Canvas.Stroke.Color := TAlphaColors.Chocolate;
  Canvas.DrawLine(a,b,1);
end;

Sample image with the previous code:


text:
Q: how to get logged in user id in jsf 2.0 how to get logged in user id in jsf 2.0
I am unable to get the user id. I tried the following methods.
xhtml page
<h:outputText value="#{request.remoteUser}"></h:outputText>

<h:outputText value="#{userDetails.userId}"></h:outputText>

Viewscoped bean class.
public String getUserId() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    System.out.println ("User"+ctx.getExternalContext().getRemoteUser());
               userId =ctx.getExternalContext().getRemoteUser();
    return userId;
}

Should i do any initialization in web.xml? or should my bean class extend or implement any other class?


text:
Q: Where and/or when is the term "flight ticket" used? On a forum I frequent some users were complaining about a question using the turn of phrase "flight ticket" as something no English speaker would ever say.
I disagreed because it sounds like something I've heard plenty of times, even though I usually say "plane ticket" myself.
But I'm not sure in which regions of the English speaking world, or in which era or age group it's preferred.
Google Ngrams tells me "flight ticket" is more popular than "aeroplane ticket" but less popular than "airplane ticket", "air ticket", and "plane ticket"... but I couldn't figure out much more about the history or demographics of the phrase.

A: If we take Google Books as a usage indicator, plane  ticket is by far the more common expression in AmE, while plane and air ticket are equally common in BrE.  Flight ticket appears to be less commonly used.


text:
Q: Prevent POST'ing from remote sites I'm just wondering how you go about preventing people trying to fool your script & POST'ing a similar looking form from a remote site.. say for example to try & put in extra values into select fields you don't have in yours or something of that nature.

A: To prevent Cross-Site Request Forgery (CSRF), you should use a so called CSRF token that verifies the authenticity of the request. Additionally, you can check the HTTP Referer and only allow the transaction if it's empty (not existing) or one of your addresses.
See also OWASP's Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet for further information.

A: The best idea would be to create a md5 key generated from the user agent, ip and a time frame.  Then store that in a database and populate it in a hidden text field so on submit you can revalidate the value.
You can also use $_SERVER['HTTP_REFERER'] to get were the request came from and validate it against the url of your site.  Remember this is set by the user web browser so it can be spoofed.  Here is a list of available $_SERVER variables and their descriptions.
http://www.php.net/manual/en/reserved.variables.server.php


text:
Q: Contacts of an Account I have to code a APEX method which receives through parameter an Account object. I don't  (and don't want to) know if this account is already persisted in SFDC database. I just want to iterate on some property to access the contacts which belongs to the Account received as parameter.
Is there someway to do it?
Please let me know if I not clear enough.

A: You can try to use this simple list method that returns all contacts that belongs to the given account:
public List<Contact> getContacts(Account acc){
    return new List<Contact>([Select Id From Contact Where AccountId = :acc.id]);
}

You still have to add a validation to the method (account not null etc).


text:
Q: Angularjs Error in loading external jsonfile from server I am trying to load json file from  server .Here is my services.js file
angular.module('starter.services', [])

/**
 * A simple example service that returns some data.
 */
.factory('Friends', function($http) {

  var friends;
 //here is the code for server access
  $http.get('http://wwww.root5solutions.com/ionictest/get.json').then(function(msg){
      console.log("console output"+msg.data);
      friends=msg.data;
      console.log("from server"+friends.data);
  });

  return {
    all: function() {
      return friends;
    },
    get: function(friendId) {

      return friends[friendId];
    }
  }
});

But its not worked properly.Here is my console message
XMLHttpRequest cannot load http://www.root5solutions.com/ionictest/get.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

A: you have to whitelist that URL
try this
.config(function($sceDelegateProvider) {

    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        // Allow loading from our other assets domain.  Note there is a difference between * and **.
        'http://wwww.root5solutions.com/ionictest/**',
    ]);
})

A: I have also faced the same problem.I am sure it will resolve your problem,

For Windows... create a Chrome shortcut on your desktop > Right-clic > properties > Shortcut > Edit "target" path : > "C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security

NOTE: After setting this exit from chrome and then open

A: All this problem beacuse i tested only using browser.When tesing on device/emulator its working perfect.There is no need of additional coding to overcome this problem.


text:
Q: Write An Annotation to Constrain Class/Method Naming in Java? I'm trying to find a way to use annotation to constrain namings in Java. Might be something looks like this:
@Getter
public String getXxx();

And when the method name does not meet the convention, for example not started with "get", the compiler will throw some error. So that during the coding progress in IDE, such like eclipse, the developer will be able to notice.
I'm getting some ideas from this article, but it's too long and complex for me.
Any simpler examples or directions would be very nice.

A: Check out the custom annotations guide HERE
It also shows you how to use reflection to get info from the annotated elements, you could easily use this to fetch the method name and verify whether it meets your convention and take appropriate actions etc...

A: Didn't get to do it myself but it appears to be possible. You can do some background reading or go directly to the 3rd party tool they link.


text:
Q: Why a React app freezes on mobile devices? I made a small app using react and it works smoothly on my computer. However, when I open it on different mobile devices it crashes after a minute or so of usage. I don't know what causes the problem but weirdly enough I don't have any bugs or warnings on my console and haven't used componentDidUpdate or hooks that might cause infinite loops like useEffect. Please help me if you know what causes a react app to glitch on mobile devices or have encountered the same problem and found a solution for it.
Here's the app
https://summerresort.netlify.app
and the code
https://github.com/Mahmoud-farargy/summerresort/tree/master/Beach-Resort
Thanks!

A: Your app looks all ok except 2 points. I can't test my guess, but I'm almost entirely sure that your problem comes from those 2.
Both parts that seem problematic are located in index.js, here there are:
window.addEventListener("scroll", () => {// gets the current height
    let  scroll = document.body.scrollTop || document.documentElement.scrollTop;
    let arrowUp = document.querySelector(".arrow-up-btn").style;
    scroll >= 1000 ? arrowUp.display="flex" : arrowUp.display = "none";
});

window.addEventListener("resize", ()=> {// gets the current width
    this.setState({
        currentPageWidth: window.innerWidth || document.documentElement.clientWidth
    })
});

The first code block is expensive because:

*

*The scroll event is fired very frequently.

*You don't listen for scroll passively (it'd be a good idea though).

*You set the style much more frequently than needed.

However, I think, that it is the second code block that causes mobiles to glitch.

Check out this answer to see why the resize event is fired on mobiles more frequently than on desktop.

*

*Now, each time the resize event is triggered, the state of MainApp
is updated.

*Each time MainApp is updated, React recalculates all its children.

*By default, React just re-run render of each child & compares the output.

Considering you have all routes & all components inside the MainApp & you didn't implement any optimizations (React.PureComponent, lazy loading for routes, etc.) React will have to recalculate what the entire site looks like on each resize event.
The easiest fix would be to store currentPageWidth in a ref instead of state.
Another possible problem is that by attaching listeners inside the render method, you're attaching new listeners on each single render without clearing any of previously added listeners.


text:
Q: aws: update lambda environment variables remotely from another app I have an AWS lambda function implemented in Nodejs. FYI, This function is used to process data for a separate web app - which is an asp.net web app which is not hosted in AWS. To process the data, the lambda function requires some information - a set of 6-10 variables - which is set as environment variables for the lambda function. Currently these environment variables are set in aws console and everything works fine. However, setting environment variables manually via console is not scalable when moving to production because the environment variables keep changing throughout the (maybe 4-6 times per day) at random intervals.
Question:
How to update the lambda function environment variables via api from the external asp.net application?


text:
Q: open Android app when internet connection is on otherwise display no internet connection message I just created an android app for fetching data from a website. I want to check if the device has an internet connection or not. If the device has internet connection, run my code and fetch the data and display it, otherwise if the device has no internet, then display the no internet connection message. I have tried this code to check the internet connection. How can I call the code when there is an internet connection?
My Java code:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_primary);
        new FetchWebsiteData().execute();
            }
        });

    }

    private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
        String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
        ProgressDialog progress;
        private Context context;

        //check Internet connection.
        private void checkInternetConnection(){

            ConnectivityManager check = (ConnectivityManager) this.context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            if (check != null)
            {
                NetworkInfo[] info = check.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i <info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        {
                            Toast.makeText(context, "Internet is connected",
                                    Toast.LENGTH_SHORT).show();

                        }

            }
            else{
                Toast.makeText(context, "not conencted to internet",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //some code here
        }

        @Override
        protected String[] doInBackground(Void... params) {
            ArrayList<String> hrefs=new ArrayList<String>();
            try {

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            //get the array list values
            for(String s:hrefs)
            {
                //some code
            }
            //parsing first URL
            String [] resultArray=null;
            try {

            } catch (IOException e) {
                e.printStackTrace();
            }
            //parsing second URL
            String [] resultArray1=null;
            try {

            } catch (IOException e) {
                e.printStackTrace();
            }

            try{

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {

            ListView list=(ListView)findViewById(R.id.listShow);
            ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
            list.setAdapter(arrayAdapter);
            mProgressDialog.dismiss();
        }
    }
}

How can I run the code when the connection is open and how to display message when app has no internet connection?

A: try this
//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null)
    {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if(netInfos != null)
        {
            return netInfos.isConnected();
        }
    }
    return false;
}

once the method return the value you have to check
//detect internet and show the data
    if(isNetworkStatusAvialable (getApplicationContext())) {
        Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
        new FetchWebsiteData().execute();
    } else {
        Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();

    }

A: public static boolean hasInternetAccess(Context context) {

    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(TAG, "No network available!");
    }
    return false;
}

A: Here is class to get information about your internet connection
https://gist.github.com/emil2k/5130324
Just copy and paste in your code and use it's methods

A: Create a class NetworkInformation.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkInformation {

     private static NetworkInfo networkInfo;

     public static boolean isConnected(Context context) {

             ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

             try{
                networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // test for connection for WIFI
            if (networkInfo != null
                    && networkInfo.isAvailable()
                    && networkInfo.isConnected()) {
                return true;
            }

            networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            // test for connection for Mobile
            if (networkInfo != null
                    && networkInfo.isAvailable()
                    && networkInfo.isConnected()) {
                return true;
            }

            return false;
      }

}

Now check whether network is available or not before calling an asynctask like this:
if(NetworkInformation.isConnected(YourClassName.this))
        {
             new FetchWebsiteData().execute();
        }else{

            Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
        }

Dont forget to include the below permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

A: use this method for checking network availability
public static boolean isNetworkAvailable(Context context) {

    try{
    ConnectivityManager connectivityManager
          = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

        return s;
    }
    catch(Exception e){

        System.out.println("exception network"+e);
        return false;
    }
}

if it returns true you can go ahead with network call else Toast a message of network unavailablity.

A: https://stackoverflow.com/a/9570292/4241807 tells you how to check for network connectivity, then just place your message in the "else" part of the code

A: Use below code and make a class like NetworkAvailablity.java
public class NetworkAvailablity {

    public static boolean checkNetworkStatus(Context context) {
        boolean HaveConnectedWifi = false;
        boolean HaveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    HaveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    HaveConnectedMobile = true;
        }

        return HaveConnectedWifi || HaveConnectedMobile;
    }
}

And in the your code use these following lines which check that internet is available or not
        if (NetworkAvailablity.checkNetworkStatus(getActivity())) {
             //code here
        }
        else
        {
        // give message here by Toast or create the alert dilog
             Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show();
        }

A: //Implement this code in MainActivity and check if isConnectingToInternet(), then allow Otherwise show the No Internet Connection message.

public boolean isConnectingToInternet() {
            ConnectivityManager connectivity = (ConnectivityManager) _context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i < info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }

            }
            return false;
        }

A: To check if user connect to the wifi or any access point
it's better to check this method first to see if user has any connection or not
and if it returns true you can check if he has real connection or not with next method
    public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

to check if user has real traffic to send request over network
be aware that you shouldn't call hasTraffic() method in main thread (you can use AsyncTask )
public static boolean hasTraffic(){

    try {

        URL url = new URL("http://www.google.com/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        urlc.setRequestProperty("User-Agent", "test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(2000); // mTimeout is in seconds
        urlc.connect();
        if (urlc.getResponseCode() == 200) {
            Log.d("check Traffic ", "has traffic");
            return true;
        } else {
            return  false;
        }
    } catch (Exception e) {
        Log.i("warning", "Error checking internet connection", e);
        return  false;
    }

}

TO check internet connection
        new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected void onPostExecute(Boolean flag) {

            if(flag == true){
                // do whatever you want
            }else{
                cantAccessToService();
            }
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            if(isOnline(SplashActivity.this) && hasTraffic() ){
                return true ;
            }else{
                return false ;
            }
        }
    }.execute();


text:
Q: LMDB: change label of entry in already made lmdb file I have a large (> 1TB) lmdb file made for caffe. It took a long time to generate. Now I want to change the labels of some of the entries. Is there a way to change the label in place? There is a work around that I could delete them and add them back. But this will lead to all the changed labels (a new class in my case) being at the end of lmdb file, which I think is not good for training.

A: Finally found the solution after some search. I can use replace function, as mentioned in https://lmdb.readthedocs.io/en/release/.
Here is the code snippet for the solution:
map_size = N
env = lmdb.open(lmdb_name, map_size=map_size)
with env.begin(write=True) as txn:
    cursor = txn.cursor()
    for key, value in cursor:
        datum = caffe.proto.caffe_pb2.Datum()
        datum.ParseFromString(value)
        datum_new = caffe.proto.caffe_pb2.Datum()
        datum_new.channels = 3
        datum_new.height = size
        datum_new.width = size
        datum_new.data = datum.data
        datum_new.label = 13
        cursor.replace(key, datum_new.SerializePartialToString())


text:
Q: How to turn on gcc warnings for a forgotten return statement? How do I turn on gcc warnings for a forgotten return statement?
It is supposed to warn me in cases like the following:
int foo() {
  std::cout << "haha";
}

I know -Wall turns that warning on, but it enables too many other warnings.

A: According to gcc's online documentation, -Wall turns on:
      -Waddress
      -Warray-bounds (only with -O2)
      -Wc++0x-compat
      -Wchar-subscripts
      -Wenum-compare (in C/Objc; this is on by default in C++)
      -Wimplicit-int (C and Objective-C only)
      -Wimplicit-function-declaration (C and Objective-C only)
      -Wcomment
      -Wformat
      -Wmain (only for C/ObjC and unless -ffreestanding)
      -Wmissing-braces
      -Wnonnull
      -Wparentheses
      -Wpointer-sign
      -Wreorder
      -Wreturn-type
      -Wsequence-point
      -Wsign-compare (only in C++)
      -Wstrict-aliasing
      -Wstrict-overflow=1
      -Wswitch
      -Wtrigraphs
      -Wuninitialized
      -Wunknown-pragmas
      -Wunused-function
      -Wunused-label
      -Wunused-value
      -Wunused-variable
      -Wvolatile-register-var

Out of those, -Wreturn-type seems like it would do the trick:

Warn whenever a function is defined with a return-type that defaults to int. Also warn about any return statement with no return-value in a function whose return-type is not void (falling off the end of the function body is considered returning without a value), and about a return statement with an expression in a function whose return-type is void.

However, if turning on -Wall makes your code have way too many warnings, I'd recommend fixing up your code!

A: always use:
gcc -g -ansi -pedantic -Wall  -o


text:
Q: Informative stacktraces with karma+browserify, how? I have a problem with assertion traces - they are not enough informative.
For an instance assertion fault:
should navigate inside of layout
       PhantomJS 2.1.1 (Linux 0.0.0)
          1) serialize@http://localhost:9876/base/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:10776:34
             processAssertionError@node_modules/karma-mocha/lib/adapter.js:59:50
             node_modules/karma-mocha/lib/adapter.js:129:49

I've tried karma-sourcemap-loader, but it does not affect the output for me.
My config:
frameworks: ['mocha', 'chai', 'source-map-support', 'browserify'],
files: [
  'tests/**/*.js'
],
browserify: {
  debug: true
},
preprocessors: {
  'tests/**/*.js': ['browserify']
},
reporters: ['progress', 'nyan'],

Any ideas ?

A: It seems like problem related to source-maps support by different browsers, this configuration works just fine with chromium browser, but does not provide readable stack-trace information when i'm testing with phantomjs browser.


text:
Q: Empty dictionary for 'chrome_settings_overrides'. Could not load manifest I created an extension with the following values for Settings Overrides in the manifest.json. When I tried to "load unpacked", it "Failed to load extension". The error message was "Empty dictionary for 'chrome_settings_overrides'.". What dictionary does it mean? I cannot decode the error message.
  "chrome_settings_overrides": {
    "search_provider": {
      "name": "....",
      "search_url": "....",
      "suggest_url": "....",
      "keyword": "....",
      "favicon_url": "....",
      "is_default": false
    }
  }

A: You just need to add "encoding": "UTF-8",
"chrome_settings_overrides": {
    "search_provider": {
      "name": "....",
      "search_url": "....",
      "suggest_url": "....",
      "keyword": "....",
      "favicon_url": "....",
      "encoding": "UTF-8",
      "is_default": false
    }
  }


text:
Q: Find a Class object's Item with Maximum character count in a User Defined List I am new to the LINQ, I have got one scenario where I am stuck to do a task in single expression rather than looping.
In a Custom class array and within that array a specific string parameter maximum length?
StringBuilder sb = new StringBuilder();
        CultureInfo[] cinfo = CultureInfo.GetCultures(CultureTypes.AllCultures);
        foreach (CultureInfo ci in cinfo)
        {
            sb.Append(ci.Name + "," + ci.TwoLetterISOLanguageName + "," + ci.ThreeLetterISOLanguageName + "," + ci.ThreeLetterWindowsLanguageName + "," + ci.DisplayName + "," + ci.EnglishName + Environment.NewLine);
        }
        lb.Items.Add(sb.ToString());
        txtData.Text = sb.ToString();

here cinfo is the collection and I want to find out the element in the whole array which has maximum character in Name parameter.

A: You can order by the length of Name then take the first:
var cultureWithLongestName = CultureInfo
    .GetCultures(CultureTypes.AllCultures)
    .OrderByDescending(x => x.Name.Length)
    .FirstOrDefault();

A: The easiest way to go about doing something like that is to order by the length and take the first element. We can do that like so:
var elementWithLongestName = collection.OrderByDescending(e => e.Name.Length).First();

HOWEVER, sorting with OrderByDescending gives you O(nlog(n)) time complexity (it uses Quicksort). We can do better! we can solve this with linear time (O(n)):
Using .NET 5.0 or below
Unfortunately, until .NET 6.0 (currently in preview) there is no built-in LINQ operator that finds a maximum element by one of its properties. There are two ways we can achieve this anyway:
Using vanilla LINQ
We can find the maximum length in the collection, and then find an element with that length:
var longestNameLength = collection.Select(e => e.Name.Length).Max();
var elementWithLongestName = collection.First(e => e.Name.Length == longestNameLength);

One downside of this approach (besides being more verbose) is that we're enumerating the same collection twice. In your case, that's fine because the source collection is a simple in-memory array. If the source collection was a more complicated IEnumerable (like a collection that lazily loads items from a database), it may be a good idea to turn it into an in-memory collection first by using ToList() or ToArray().
Using MoreLinq
You can use the popular package MoreLinq to achieve what you asked for:
var elementWithLongestName = collection.MaxBy(e => e.Name.Length);

Using .NET 6.0 and above
In this version, the MaxBy operator (that does exactly what you need) is included out of the box and there is no need to use a third-party library. You can just write:
var elementWithLongestName = collection.MaxBy(e => e.Name.Length);

NOTE: a stable release of .NET 6.0 is scheduled for November 2021.


text:
Q: .Net core api response is in small case how to change default settings After Migrating .Net Framework MVC API to .Net Core, Json Response was changed. Property Names are in small. How to override default settings for Lowercase

A: We can use below setting in startup.cs
public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
    }

Or we can add as
 services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);


text:
Q: How to assign default value in Dropdownboxlist? Hi I am developing angularjs application. I tried many ways to set default value for dropdown in Angularjs but I am not able to set default value.
 <select ng-change="getModel(b.ID)" ng-model="b.ID"  id="brand" ng-options="b.MakeName for b in list">
                    <option value="1">-- Select a Make --</option>//Not working
                </select>
                <select  ng-change="getStyle(a.ID)" ng-model="a.ID" ng-options="a.ModelName for a in Modellist" id="make" >
                    <option value="1">-- Select a Model --</option>
                </select>//Not working
                <select ng-change="getallDetails(c.ID)" id="type" ng-model="c.ID" ng-options="c.BodyStayleName for c in ModelStyle">
                    <option value="1">-- Select a Type --</option>
                </select>//Not working

May I know am i missing here anything? Any help would be appreciated. Thank you.

A: Use ng-init  or set the default value to the model variable inside the controller,
  $scope.BrandId = "1";

DEMO

<!DOCTYPE html>

      <select ng-init="BrandId=='1'" ng-model="BrandId" ng-options="brand.id as brand.name for brand in brands"></select>


text:
Q: load pathForResource from a text field? Hey so i am trying to give my music player a path from which it will find the music file to play but i have one question. Is it possiable to read the pathForResource from a text field instead?
I have a table view, whena row is clicked a new view pops up where the sound will be played.
Regular:
NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:@"Katy" ofType:@"mp3"];

I Want
NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:myTextField.text ofType:@"mp3"];

Can i give the resouce name via a text field? I tried the above but it will not read it.

A: Are you sure that myTextField.text is actually the string that you entered? Try doing a simple NSLog.
If your "regular" code works, but not your "I Want" code, then it's 99% likely that myTextField.text simply isn't what you think it is.
(As a side question, does your "regular" code work?)


text:
Q: Copy custom headers from incoming pipeline to outgoin pipeline using behaviors I tried to copy a custom headers from the incoming pipeline to de outgoin pipeline with the purpose of spread this headers along all services. This has been implemented using the behaviors pipeline. The problem is in the outgoing context the headers is no present. I resolve it using a cache a get this data from the cache in the outgoingphisical context. Anyone does kown a better way where the cache it not necesary? Thanks.

A: Using extension bag (Extensions property on the behaviour's context object) is a good option. You can set the value in the incoming pipeline behavior and reference it later in the outgoing pipeline behavior.
The Audit Filter Pipeline Extension sample on the documentation site demonstrates how to extend the NServiceBus message-processing pipeline with custom behaviors to add filters which prevent certain message types from being forwarded to the audit queue. In your case, you'd be storing the incoming message header and using it in the outgoing behavior(s)


text:
Q: change coordinates of L.Marker in L.layerGroup I cannot find way how to change coordinates of layer(L.Marker) placed in layerGroup.
I created global variable var markerGroup = new L.layerGroup();
Then I have a function where  I'm creating layers like:
var newMarker = L.marker([decimal_lat, decimal_lon]);
markerGroup.addLayer( newMarker );

And I have a modal dialog window where I'm changing coordinates of Markers ( depends on id what Marker from my layer I change ):
(markerGroup.getLayer(id)).setLatLngs( L.latLng(parseFloat(lat_p), parseFloat(lon_p)) );

But this solution makes error like:

Cannot read property 'setLatLngs' of undefined

Is there any way how to change coordinates of L.Marker on specific position in L.layerGroup?

A: Marker layers don't have setlatLngs method, they do have setLatLng. Most probably you've made a typo error.
Here is the fiddle where I've correctly reproduced your issue. At first I've added a marker with arbitrary coordinates, then I've moved it to the centre of the map, exactly where map view is set.
var markerGroup = new L.layerGroup();
var newMarker =  L.marker([1000, 1000]);
markerGroup.addLayer( newMarker );
markerGroup.addTo(map);
markerGroup.getLayer(24).setLatLng(new L.LatLng(0,0));


text:
Q: Running Neo4j query in nodejs returns "undefined" I am trying to run a query against neo4j database from nodejs. here is the code inside my app.get in nodejs:
var query = 'match (t {name:"Tom Hanks"}) return t';
    var params={limit: 10};
    cypher(query,params,cb);

And here is the cypher function definition for executing the query:
function cypher(query,params,cb) {
      request.post({uri:txUrl,
        json:{statements:[{statement:query,parameters:params}]}},
        function(err,res) { cb(err,res.body);});
    }

Finally, this is the cb function definition:
var cb = function(err,data) {
  console.log(JSON.stringify(data));
};

And I set the database path as follows:
var txUrl = 'http://localhost:7474/db/data';

After running the code in node js. I just get the error "undefined" in the console. It is hard to debug with this clue. Before this I got similar errors of form "variable x is undefined". But now, I am stuck. Does anyone have any idea to find the source of problem?

A: You should output the err parameter, then you should also see the error message.
Try to get up to speed with javascript/node and it's conventions first, that will save you such misunderstandings.
Your URL is wrong, it has to be:
var txUrl = 'http://localhost:7474/db/data/transaction/commit';

Also your params are not used any where.
And you should use a Label in your match, like :Person or :Actor
I think you would be better off using a driver for Javascript, see http://neo4j.com/developer/javascript


text:
Q: No appropriate default constructor available with template implementation in Cpp I am trying to implement Stack by hand in C++. I want to use this implementation for many datatypes so that I've tried to implement it by using template in C++. Then I come to an error with my constructor of my Stack class.
Here is my code
#include<iostream>
#include<string>
using namespace std;

template <class T>
class Node
{
public:
    T data;
    Node* next;

    Node(T value)
    {
        data = value;
        next = NULL;
    }
};

template <class T>
class Stack :public Node<T>
{
public:
    Node<T>* head;
    Stack()
    {
        head = NULL;
    }

    ~Stack()
    {
        Node<T>* current = head;
        Node<T>* next;
        while (current != NULL) {
            next = current->next;
            delete current;
            current = next;
        }

        head = NULL;
    }

    T top()
    {
        return head->data;
    }

    void push(Node<T>* newNode)
    {
        newNode->next = head;
        head = newNode;
    }
    void pop()
    {
        Node<T>* temp = head;
        head = head->next;
        delete temp;
    }
    bool isEmpty()
    {
        return head == NULL;
    }
};

And the error is: 'Node': no appropriate default constructor available
Can you guys explain what is happening and give me some advices!!!

A: The Stack class should not inherit Node class, it should compose it, you should delete the inheritance relation from stack class, it should look like this:
template <class T>
class Stack

A: When an object is created that derives from a base class then also the base class subobject is created. This:
Stack()
{
    head = NULL;
}

is the same as writing:
Stack() : Node<T> () {
    head = NULL;
}

That is: When you do not explicitly call the base class constructor then its default constructor is called. Your Node has no default constructor (a default constructor is one that can be called without parameters).
Actually it looks like Stack should not inherit from Node in the first place.
As a side note, you should initialize members instead of assignment in the constructors body. One way to initialize them is the the member initialization list. And better use nullptr rather than NULL:
Stack() : Node<T>(), head(nullptr)
{}

PS You'd get the same error if there were no templates involved. I suggest to write the same code for one specific type and then turn it into a template. In this way you can do one thing at a time.


text:
Q: How to reference a property in microsoft bot framework I'm using Composer.
The text prompt is - What is your name? And I want to store the user input in a $name property.
In the User Input section - under property - the placeholder gives examples saying you can use $birthday or dialog.${user.name}.
When I use $name as the property I am unable to then get access to the property during the reply eg the reply is "Welcome ......"  - and the name is blank.
I have tried Welcome {$name} and Welcome ${name} without success.
But when I use user.name in the property field then I am able to access the property and replying "Welcome Jack" works.
Could I please get clarification on whether $name or $birthday can be used to store values.
Thx
Thanks

A: Bot state handling is stateless, You have to specify the property with the state(memory) ex: user.Name, here the user is Bot user state(memory)
once you specify the state, your property and value get stored otherwise it's lost.
ex : user.name or user.birthday you get the values otherwise it's lost.
bot has different memory states user state, Conversation state, dialog state, etc.  For more information refer Bot state management


text:
Q: Retrieve firebaseUID from user_pseudo_id I have an analytics table that contains recorded events. These events are recorded by Firebase and exported to BigQuery. I need to connect this table of events that identify users through their user_pseudo_ID with another table that just contains userUID and firebaseUID.
I was not able to find a documentation or a topic describing how to connect this user_pseudo_id with userUID or firebaseUID.
Do you know how to do that?
Thank you very much!

A: Firebase does not automatically set a identifiable user ID for analytics events. Instead it sets an internal ID that merely identifies what events come from the same user, not who they are. If you want to tie the events to a user of your app, you'll have to set the user ID in the application code. See https://firebase.google.com/docs/analytics/userid
This will add your User ID to the analytics events, and you can then use that in the BigQuery export to tie the events to users in your own tables.


text:
Q: Правильный способ выровнять иконки по центру Нужно выровнять иконки по центру-вертикально и горизонтально:

Svg иконки разных размеров, а их контейнер, белый круг всегда одного размера: 100х100. Выравниваю через flexbox, но мне кажется это кривой и громоздкий способ
.icon-container {
    display: flex;
    align-items: center;
    justify-content: space-around;
}

A: Flexbox конечно короче но и старые варианты которые везде работают забывать не надо
смотрите

* {
  margin: 0;
  padding: 0;
}

.table {
  display: table;
  width: 100%;
  border-bottom: 1px solid red;
}

.table-row {
  display: table-row;
}

.table-cell {
  display: table-cell;
  height: 150px;
  text-align: center;
  vertical-align: middle;
}

.table-cell span {
  background: #ccc;
  color: #fff;
  border-radius: 50%;
  padding: 10px;
}

ico1

ico2

ico3

A: Flexbox это самый удобный и красивый способ на данный момент.
Скажем так, все остальные способы выглядят более громоздкими.


text:
Q: SSIS Relative File Path for referencing .dtsx files on a execute package task Hi I have an SSIS package in which i have a main package that references child packages, is there a way I can make the location path external using a Relative path or just the file name. I cant use the full C: drive path as this is subject to change.

A: yes, but you have to find a way of changing the current working directory of the execution of the package. I worked at one place where we ran bat files to execute the packages and the first line used cd to set the working directory to the folder location of the parent package. I think I've also seen people use a script task inside the parent package to set the working directory based on the runtime location of the parent package.
http://www.artisconsulting.com/blogs/greggalloway/2008/7/13/relative-paths-in-ssis

A: from what i found it is best to use the project reference system instead of file reference and you can reference any project file if you deploy to the SSISDB instead of the MSDB, it works much better than the MSDB as well as being able to work with package params easier


text:
Q: Ignore dependency with buildout Here is my buildout.cfg:
[buildout]
extends = versions.cfg
eggs = package1
       package2
parts = installeggs

[installeggs]
recipe = zc.recipe.egg
eggs = ${buildout:eggs}

And my versions.cfg:
[versions]
package1 = 1.0
package2 = 2.0

Unfortunately, package2's version requires another version of package1.
Error: The requirement ('package1>=2.0') is not allowed by your [versions] constraint (1.0)

Is there an option I'm not aware of to install this version of package1 anyway? Something like the --no-deps option of pip for instance.

A: I use a workaround consisting in running pip install --no-deps, but it forced me to declare another part.
[buildout]
extends = versions.cfg
eggs = package1
#      package2
parts = installeggs
        forceinstall

[installeggs]
recipe = zc.recipe.egg
eggs = ${buildout:eggs}

[forceinstall]
recipe = collective.recipe.cmd
on_install = true
cmds = ${buildout:directory}/bin/pip install --no-deps package2==2.0


text:
Q: Como transformar um arquivo python em executável? Se eu criar um aplicativo em python e quiser que outras pessoas possam usá-lo, as outras pessoas vão ter que instalar o python pra poder rodar ele ou existe uma forma de tornar  ele executável? E pra criar um instalador pra esse aplicativo preciso aprender outra linguagem?

A: Você pode usar o cython também. Existe algum ganho de perfomace.
cython main_script.py --embed

Porém acho que a solução mais simples é utilizar o PyInstaller, funciona no Windows, Linux e MacOS. Ele cria um pacote com tudo incluso(python, libs, e o executavel).
pyinstaller main_script.py


text:
Q: Define a problem using chernoff bounds We are preparing this for an exam.
Given the division of a plane into a number of regions of different sizes. We would like to find, or guess, which is the biggest region, by doing the following.
We will shoot a number of random points at the plane, and then conclude that the region containing the most points, is also the biggest.
The question is: how do use Chernoff bounds to say how many random points we need to shoot, to know that we have found the biggest region with, say, 75% probability?


text:
Q: How to call the "full page screenshot" function in chrome extension? I am writing a chrome extension and need to screenshot the full page using javascript. I find that chrome has already offered powerful screenshot function in its development tool:
Just open the develop tool, use command+shift+p to run "capture full size screenshot" command.(my reputation is not enough for posting images here, sorry for that)
How to call this function from extension code?


text:
Q: Perl regex, insert value between commas I have a CSV file, and some of the fields are empty.
Sample Data
ItemA,5,4,3,2,1
ItemB,7,,,2,4
ItemC,,,,2,
ItemD,,3,,,

I'd like to pass a perl one liner over the file, that would insert a string, say NULL in between each comma, or after the final comma if no value exists after it.
so after regex, data should look like:
ItemA,5,4,3,2,1
ItemB,7,NULL,NULL,2,4
ItemC,NULL,NULL,NULL,2,NULL
ItemD,NULL,3,NULL,NULL,NULL

I don't know how to create this regex, assistance is appreciated.  Thank you.

A: Simple, use positive lookbehind and lookahead assertions like below.
$ perl -pe 's/(?<=,)(?=,|$)/NULL/g' file
ItemA,5,4,3,2,1
ItemB,7,NULL,NULL,2,4
ItemC,NULL,NULL,NULL,2,NULL
ItemD,NULL,3,NULL,NULL,NULL

*

*(?<=,) Just lookafter to all the commas. That is, it asserts that the match must be preceded by a comma.

*(?=,|$) And the match was immediately followed by a comma or end of the line anchor. So it matches all the boundaries which exists inbetween all the commas and the one which are next to the comma which are at the last.

*Replacing the matched boundary with NULL string will give you the desired output.

A: I wouldn't use regex. Use a core module Text::ParseWords:
perl -MText::ParseWords -lne'
    @w = parse_line (",", 1, $_);
    print join ",", map { (length) ? $_ : "NULL" } @w
' file
ItemA,5,4,3,2,1
ItemB,7,NULL,NULL,2,4
ItemC,NULL,NULL,NULL,2,NULL
ItemD,NULL,3,NULL,NULL,NULL

or alternatively use the optional third param for split.
perl -lne'
    @F = split ",", $_, -1;
    print join ",", map { (length) ? $_ : "NULL" } @F
' file
ItemA,5,4,3,2,1
ItemB,7,NULL,NULL,2,4
ItemC,NULL,NULL,NULL,2,NULL
ItemD,NULL,3,NULL,NULL,NULL

A: Here's one solution with a regex:
$ perl -pe 's/,(?=,)|,$/,NULL/g' file.csv

ItemA,5,4,3,2,1
ItemB,7,NULL,NULL,2,4
ItemC,NULL,NULL,NULL,2,NULL
ItemD,NULL,3,NULL,NULL,NULL

I.e. match a comma immediately followed by a comma (,(?=,)) OR a comma at the end of the line (,$), and replace the matched comma with ,NULL.

EDIT: As pointed out by Casimir et Hippolyte, s/,(?=,|$)/,NULL/g is simpler.
(Match a comma immediately followed by another comma or by the line's end).

A: You can use this:
#!/usr/bin/perl

use strict;
use warnings;

my $fpath = "./data.txt";

open(my $fh, '<', $fpath) or die "*** Cannot open $fpath:\n$!\n";

while ( <$fh> ) {
    while(1) { last if ( $_ !~ s/,\s*,/,NULL,/g ) }
    $_ =~ s/,\s*$/,NULL/g;
    print $_ . "\n";
}


text:
Q: Imported dependency requires another dependency to be first available in scope I'm trying to import a library that extends another one, here's my first approach:
import * as PIXI from 'pixi.js';
import 'pixi-layers'; // extends PIXI classes

I get an Uncaught ReferenceError: PIXI is not defined on runtime when pixi-layers tries to Object.assign on a PIXI class.
I suppose this is related to how webpack's hoisting, I've tried to use:

*

*imports-loader

*script-loader

*I've also tried to provide PIXI through webpack:

module.exports = {
    // ...
    plugins: [
        new webpack.ProvidePlugin({
            PIXI: 'pixi.js',
        }),
    ],
};

PIXI remains unavailable to pixi-layers, how can I bundle pixi-layers and make sure it can actually work with the PIXI object?

A: Turns out providing PIXI as a plugin through the webpack config file was the solution, I just has this same config file compile in the wrong location (paths are hard).


text:
Q: Error using Animation package R Tried to run the following code in R:
ani.options(
   convert = shQuote("C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe")
)
 saveGIF(
{
  for (i in 1:10) plot(runif(10), ylim = 0:1)
},
 movie.name = "test.gif",
interval = 0.2,
ani.width = 300,
ani.height = 300,
outdir = getwd()
)

Getting the error message:
Executing:
"\"C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe\"" -loop 0 -delay 20     Rplot1.png Rplot2.png Rplot3.png
Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png Rplot9.png Rplot10.png "test.gif"
The filename, directory name, or volume label syntax is incorrect.
an error occurred in the conversion... see Notes in ?im.convert
[1] FALSE
Warning messages:
1: running command 'C:\Windows\system32\cmd.exe /c "\"C:/Program     Files/ImageMagick-6.9.0-Q16/convert.exe\"" --version' had status 1
2: running command 'C:\Windows\system32\cmd.exe /c "\"C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe\"" -loop 0  -delay 20 Rplot1.png Rplot2.png Rplot3.png Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png Rplot9.png Rplot10.png "test.gif"' had status 1
3: In cmd.fun(convert) :
  '"\"C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe\"" -loop 0  -delay 20 Rplot1.png Rplot2.png Rplot3.png Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png Rplot9.png Rplot10.png "test.gif"' execution failed with error code 1
4: running command '"\"C:/Program Files/ImageMagick-6.9.0-Q16/convert.exe\"" -loop 0  -delay 20 Rplot1.png Rplot2.png Rplot3.png Rplot4.png Rplot5.png     Rplot6.png Rplot7.png Rplot8.png Rplot9.png Rplot10.png "test.gif"' had status 127

Could someone please point on my mistake.

A: I had the same issue, and it seems it is due to the path to convert.
If I type:

ani.options(convert = shQuote('C:/Program Files/ImageMagick-6.8.7-Q16/convert.exe'))

And then check the path

ani.options("convert")
  [1] "\"C:/Program Files/ImageMagick-6.8.7-Q16/convert.exe\""

However, if I do:

ani.options(convert = 'C:/Program Files/ImageMagick-6.8.7-Q16/convert.exe')
  ani.options("convert")
  [1] "C:/Program Files/ImageMagick-6.8.7-Q16/convert.exe"

It is the correct path and saveGIF works.... weird things...


text:
Q: Google maps API divide destinations to groups and find shortest paths I'm about to write a project in C# MVC and AngularJS. In this project I have a list of about 100-200 locations that I need to divide into groups, each group 3-4 destinations max. The groups are divided in a way that the destinations in them are minimal. Then have to build routes from a single origin into each group (seperate route for each group).
I'm kinda new to the google maps api and got lost in it, is there a service that gets multiple destinations and retrieves the minimum distance between them all?
Or I must find it in my algorithm by looping on all destinations?
All that I've found was distance matrix between origin and single destination.

A: Distance matrix API has different limitations on number of destinations and number of origins but however the total element limit (element is considered as combination of one origin and one destination) is 625 (you can have any number of origins and any number of destinations but their product shouldn't go over 625) per call.
That being said you can implement your call as single origin and 625 destinations per call. There is also another limit for google distance matrix which limits you to request only 1000 elements per second.
The response can be either XML or JSON based upon your specification and can take either lat/Long values or an address.
Google Distance matrix


text:
Q: Simple typescript error that cannot pass props to a functional component I'm trying to pass a prop to a functional component (uses typescript) and I'm getting a rendering error but don't know why.
Here is the file that imports the component:
<ActiveCheckbox active={true} />

And here's the component file:
import React from "react";
import { Checkbox } from "@chakra-ui/core";

export const ActiveCheckbox: React.FC = (active: boolean) => {
  return <Checkbox variantColor="teal" mr={2} isChecked={active}></Checkbox>;
};

And the error:
TypeScript error in /src/components/active-checkbox.tsx(4,14):
Type '(active: boolean) => JSX.Element' is not assignable to type 'FC<{}>'.
  Types of parameters 'active' and 'props' are incompatible.
    Type '{ children?: ReactNode; }' is not assignable to type 'boolean'.  TS2322

Can someone explain what I'm doing wrong here? I've also tried appending <any> after React.FC but to no avail.
Thanks for any advice


text:
Q: Fit Text box in excel cell? I am trying to fit a text box in a ASP.NET gridView in row data bound. here it is not properly adjusting in the cell.to to fit it properly.
In row data bound I am using
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
            e.Row.Cells[2].Width = new Unit("700px");
            TextBox txtAddress = new TextBox();
            txtAddress.ReadOnly = false;
            e.Row.Cells[2].Controls.Add(txtAddress);
            e.Row.Cells[2].Style.Add("text-align", "center");
            txtAddress.Text = e.Row.Cells[2].Text;
            GridView1.Attributes.Add("style", "table-layout:fixed");
        }
    }

How to fit it properly in grid cell.

A: I am trying this and its working fine ..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onclick", "this.style.backgroundColor='orange'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
                e.Row.Cells[2].Width = new Unit("700px");
                TextBox txtAddress = new TextBox();
                txtAddress.ReadOnly = false;
                //txtAddress.Style = "width:100%;";
                txtAddress.Style.Add("width", "99%");
                e.Row.Cells[2].Controls.Add(txtAddress);
                e.Row.Cells[2].Style.Add("text-align", "center");
                txtAddress.Text = e.Row.Cells[2].Text;
                GridView1.Attributes.Add("style", "table-layout:fixed");
            }
        }

100% is mathematically accurate but 99 did the trick for me :)


text:
Q: General system exception happened - The custom_range value wasn't found in the algorithms When importing a csv spreadsheet I am getting the following error:

A: In vendor/magento/module-import-export/Model/Export/AbstractEntity.php
You will find
/**
 * Limit of errors after which pre-processing will exit
 *
 * @var int
 */
protected $_errorsLimit = 100;

It's probably the limit that makes you getting that message.
That being said if you want to know what is wrong you probably have more details in var/log/system.log and var/log/exception.log


text:
Q: what is the concept of evaluation of expression z = (y = 30) + (y = 10) + (y = 20); What is the output of the following code please help ... I'm not getting any compiler error
How does the compiler evaluate such expression?
    #include <stdio.h>
    int main()
    {
        int y = 3;

        int z =  (y = 30) + (y = 10) + (y = 20);
        // `print z`
        printf("%d\n", z);
        // `print y`
        printf("%d\n",y);
    }

A: Strictly speaking, the behavior is undefined:

6.5 Expressions
...
2    If a side effect on a scalar object is unsequenced relative to either a different side effect
on the same scalar object or a value computation using the value of the same scalar
object, the behavior is undefined. If there are multiple allowable orderings of the
subexpressions of an expression, the behavior is undefined if such an unsequenced side
effect occurs in any of the orderings.84)

84) This paragraph renders undefined statement expressions such as
   i = ++i + 1;
    a[i++] = i;

while allowing
   i = i + 1;
    a[i] = i;

C 2011 Online Draft
Similar language exists for C++.
C does not force left-to-right evaluation of arithmetic expressions - each of the y=30, y=10, and y=20 subexpressions may be evaluated in any order (a parallel architecture may evaluate them all simultaneously).  Each of these expressions has a side effect - they change the value of y:

6.5.16 Assignment operators
...
3    An assignment operator stores a value in the object designated by the left operand. An
assignment expression has the value of the left operand after the assignment,111) but is not
an lvalue. The type of an assignment expression is the type the left operand would have
after lvalue conversion. The side effect of updating the stored value of the left operand is
sequenced after the value computations of the left and right operands. The evaluations of
the operands are unsequenced.

111) The implementation is permitted to read the object to determine the value but is not required to, even
when the object has volatile-qualified type.

ibid.
Note that emphasized portion only specifies that the side effect is sequenced after evaluating the two operands - it doesn't say that it occurs immediately after.  y may be updated immediately after each assignment, or it might not.
"But", I hear you say, "the result of y = 10 is 10 regardless of whether y is updated or not, so shouldn't the value stored in z be 60 irrespective of all that other stuff?"
That's the problem with undefined behavior - once any part of your program is undefined, the whole program is undefined.  There are no guarantees of anything.  z may get the value 60.  It may get something else.
There's no way of predicting what the value of y should be at the end of this, either.


text:
Q: DllImport Not Working I'm trying to write a WPF application which uses a function defined in C++. The C++ application is compiled as a DLL.
What I'm doing is using the DllImport attribute to import the function and use it. This works fine on my machine but when I attempt to run my WPF application on another machine it gives a "cannot find the DLL" error.
An excerpt of my C# (WPF) code:
[DllImport("Dll.dll")]
public static extern int MyFunc();

public MainWindow()
{
  InitializeComponent();
  MessageBox.Show("Starting");
  try
  {
    MessageBox.Show(MyFunc().ToString());
  }
  catch (Exception exc)
  {
    while (exc != null)
    {
      MessageBox.Show(exc.Message);
      exc = exc.InnerException;
    }
}

My C++ code:
extern "C" __declspec(dllexport) int MyFunc() {
  return 3;
}

Can anyone see where my error might be?
Thanks in advance for your help!
EDIT: It would appear that the issue is that the dependency "MSVCR100D" isn't present. My understanding is that this is a file in the VC++ Redistributable package which I have installed by to no avail.

A: Your DLL might depend on other DLLs that are not installed on the other machine. You can check the dependencies with Dependency Walker.
Typical missing dependencies are the Visual Studio C/C++ Runtime libraries. If they are missing, just google for it. Microsoft offers redistributable packages for them.

A: Is the dll registered on the other machine too ? Try setting the Build ACtion to Content and Copy to Output folder to always for the dll file


text:
Q: Getting weird error message from Highstock / Highcharts I'm currently working with Highstock / Highcharts and I wan't to load data through a json file, that I have. When I'm trying to get the data it gives me this error message in the console that I haven't seen before:
highstock.js:456 Uncaught TypeError: f.data.slice is not a function

And I'm trying to get the json data through this function. I'm only getting this error message when im entering the url for my data.json:
$.each(names, function (i, name) {

        var dataUrl = 'http://local.priceservice.dev/js/data.json';

        $.getJSON(dataUrl,    function (data) {

            seriesOptions[i] = {
                name: name,
                data: data
            };

            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter += 1;

            if (seriesCounter === names.length) {
                createChart();
            }
            console.log(data)
        });
    });

I have never seen that message before and I've tried to search around, but I can't find someone that had the same issue as me.
Json:
{
    "priceSeries": {
        "2016-10-19T12:51:51.000Z": [[1451606400000, 18.0], [1454284800000, 19.0], [1456790400000, 17.0], [1456790400000, 15.0], [1459468800000, 15.0], [1462060800000, 15.0], [1464739200000, 15.0], [1467331200000, 15.0], [1470009600000, 15.0], [1472688000000, 15.0], [1475280000000, 15.0], [1477958400000, 15.0], [1480550400000, 15.0], [1483228800000, 15.0], [1485907200000, 15.0], [1488326400000, 15.0]],
        "2016-11-19T12:51:51.000Z": [[1451606400000, 19.0], [1454284800000, 20.0], [1456790400000, 18.0], [1456790400000, 16.0], [1459468800000, 16.0], [1462060800000, 16.0], [1464739200000, 16.0], [1467331200000, 16.0], [1470009600000, 16.0], [1472688000000, 16.0], [1475280000000, 16.0], [1477958400000, 16.0], [1480550400000, 16.0], [1483228800000, 16.0], [1485907200000, 16.0], [1488326400000, 16.0]]
    }
}

Highstock / Highcharts code:
$(function () {
    var seriesOptions = [],
        seriesCounter = 0,
        names = ['MSFT', 'AAPL', 'GOOG'];
    /**
     * Create the chart when all data is loaded
     * @returns {undefined}
     */
    function createChart() {

        $('#container').highcharts('StockChart', {

            chart: {
                zoomType: 'x'
            },
            legend: {
                enabled: true
            },

            rangeSelector: {
                buttons: [{
                    type: 'hour',
                    count: 1,
                    text: '1h'
            }, {
                    type: 'day',
                    count: 1,
                    text: '1d'
            }, {
                    type: 'week',
                    count: 1,
                    text: '1w'
            }, {
                    type: 'month',
                    count: 1,
                    text: '1m'
            }, {
                    type: 'year',
                    count: 1,
                    text: '1y'
            }, {
                    type: 'all',
                    text: 'All'
            }],
                inputEnabled: false, // it supports only days
                selected: 4 // all
            },
            yAxis: {
                labels: {
                    formatter: function () {
                        return (this.value > 0 ? ' + ' : '') + this.value + '%';
                    }
                },

                plotLines: [{
                    value: 0,
                    width: 2,
                    color: 'silver'
                }]
            },

            plotOptions: {
                series: {
                    compare: 'percent',
                    showInNavigator: true
                }
            },

            tooltip: {
                pointFormat: '{series.name}: {point.y} ({point.change}%)
',
                valueDecimals: 2,
                split: true
            },

            series: seriesOptions
        });
    }

    $.each(names, function (i, name) {

        var dataUrl = 'http://local.priceservice.dev/js/data.json';

        $.getJSON(dataUrl,    function (data) {

            seriesOptions[i] = {
                name: name,
                data: data
            };

            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter += 1;

            if (seriesCounter === names.length) {
                createChart();
            }
            console.log(data)
        });
    });
});

Thank you in advance! :)

A: Data in series has to be an array. The series requires at least one object with data in the format like this:
series: [{
   data: [...] // <- has to be an array
}]

Your series looks like this:
series: [{
   name: ...,
   data: { // <- you put an object instead of an array with points
      "priceSeries": ...
   }
}]

The code above causes that slice is call on object, like this
var someObj = {};
someObj.slice(); // Uncaught TypeError: someObj.slice is not a function(…)

You should go in this way: http://jsfiddle.net/r3xfxymm/1/


text:
Q: На каком этапе защищаться от xss: Api или Front? Есть сайт, на котором начали добавлять модули front (на angular) и api (php).
Встал вопрос, а на каком уровне лучше защищаться от xss? Разработчики бэка и фронта переводят друг на друга.
Доводы в этом вопросе (B = back, api, F = front):

*

*B: api должна передовать то что ей передали и не искажать данные.
Защищаться должна только от прямого нарушения работоспособности api.

*B: с api могут работать не только web технологии, которым может
быть безраличны теги, но чувствительна к другим уязвимостям, которые
могут исказить работу web. Т.е. api не должна подстраиваться под
всех клиентов, с которыми она работает.

*F: front должен работать
с данными которые пришл

*F: по api должны передаваться чистые
данные без html тегов

A: Приложение на фронте выполняется под управление пользовательского компьютера и теоретически этот пользователь может делать с ним всё, что захочет. В том числе вообще минуя фронт отправлять запросы напрямую к API, только куки подставить. Взять какой-нибудь Telerik Fiddler и вперед. Поэтому защита встраивается на бек, а не отдается на откуп того, что пользователь не в состоянии сломать фронт. Так же работает валидация, её встраивают на беке, даже если на фронте она есть и дублируется.
Так же по последнему комментарию, никто не запрещает передавать через API всякие HTML теги, типичный пример в WYSIWYG редакторах. Просто их надо фильтровать, вырезая всякие XSS-подозрительные теги на типа <script> или <iframe> во время записи.


text:
Q: Bad gateway on 2 sites after Certbot changed the Nginx site-conf file of one of them I experience bad gateway on 2 sites after Certbot changed the Nginx site-conf file of one of them.
No errors all in nginx -t.
Only this comes up in tail /var/log/nginx/error.log:

2017/10/24 15:40:47 [error] 27439#27439: *125 connect() failed (111:
  Connection refused) while connecting to upstream, client:
  66.249.69.71, server: domain.tld1, request: "GET /category/%D7%9B%D7%9C%D7%9C%D7%99/ HTTP/1.1", upstream:
  "fastcgi://127.0.0.1:9000", host: "contfix.co.il" root@benqzq:~#

Only this comes up in tail /var/log/nginx/access.log:

185.188.204.5 - - [24/Oct/2017:15:44:13 +0000] "POST /xmlrpc.php HTTP/1.0" 499 0 "-" "Mozilla/4.0 (compatible: MSIE 7.0; Windows NT
  6.0)"

*

*No error in nginx reset.

This is the site-conf of the site I changed with Certbot:
server {
    root /var/www/html/contfix.co.il;
    server_name contfix.co.il www.contfix.co.il;

    location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass 127.0.0.1:9000;
    }

    location ~ /\.ht {
        deny all;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
        expires 365d;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/contfix.co.il/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/contfix.co.il/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    # Redirect non-https traffic to https
    # if ($scheme != "https") {
    #     return 301 https://$host$request_uri;
    # } # managed by Certbot
}

The site-conf file of the second site that I didn't choose to finish with Certbot, stayed the same.
Both sites worked perfectly before installing and working with Certbot.
I went to nginx/conf.d/ssl but the files there contain keys and not something to work with to debug this.
How should I further debug this?
Update
When using Certbot on my domain, I got the error:
Could not open file: /etc/nginx/sites-enabled/default

When I did certbot renew --dry-run I also got it, but I didn't get it just when doing "certbot renew".

A: The main problem was that the CGI directives regarding my site (responsible for PHP-dependent data processing), as appears in my site-conf file, weren't as they should be after implementing SSL.
This is the new setting that works:
location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

Regarding the error I had with the detault, just go to sites-enabled and delete the symlink inode called default. Thus, even if you have a default template in sites-available, it won't be utilized.


text:
Q: Question about Paramters vs. Variables for Azure CDN I'm using the Azure python SDK to create CDN origins. There is one parameter I haven't been able to set using the examples given for the SDK. I'm looking at the endpoint class. I'm able to set variables, like 'name' and 'host_name' but not able to set parameters.
I've tried adding the parameters to the api call, but it hasn't worked.
The example code is this:
endpoint_poller = cdn_client.endpoints.create('my-resource-group',
                                          'cdn-name',
                                          'unique-endpoint-name',
                                          {
                                              "location": "any_region",
                                              "origins": [
                                                  {
                                                      "name": "origin_name",
                                                      "host_name": "url"
                                                  }]
                                          })

I have tried adding:
                                               "origins": [
                                                  {
                                                      "name": "origin_name",
                                                      "host_name": "url",
                                                      "origin_host_header": origin_host
                                                  }]

but that did not set the origin_host_header correctly. I'm assuming that since "name" and "host_name" are variables, and "origin_host_header" is a parameter, that simply adding "origin_host_header" to that dict isn't the right place. But I can't find any examples online as to how to properly set parameters.
Without the origin_host_header set, the CDN distribution doesn't work. Once I go in and manually add that to an origin I've added via the API, the CDN starts working properly.

A: The origin_host_header is a property of the EndpointCreateParameters. Perhaps move it to the same level as the location parameter.
EndpointCreateParameters:
    location,
    origins,
    tags=None,
    origin_host_header=None,
    origin_path=None,
    content_types_to_compress=None,
    is_compression_enabled=None,
    is_http_allowed=None,
    is_https_allowed=None,
    query_string_caching_behavior=None