text:
Q: Display Template Error: The processing of item fails with error > Object reference not set to an instance of an object I created a very basic display template to show some properties for a content type,
Basically it says, if content type ="Tax Invoice", use this diplay template.
All the managed properties exist and are correctly spelled.
The only thing I can think of is maybe some of them might be empty or null and I need to write javascript logic for that?
If you think that might be the reason, can you please show me an example for my display template below.

<title>Item Tax Invoice</title>

                _#=ctx.RenderBody(ctx)=#_

Jobs:  _#= ctx.CurrentItem.JobCodes= #_

Bill Number:  _#= ctx.CurrentItem.BillNumber =#_

Bill date: _#= billDate.format("dd/MM/yyyy") =#_

Bill To Date:  _#= billToDate.format("dd/MM/yyyy") =#_

Amount:  _#= ctx.CurrentItem.Amount =#_

Due date:  _#= dueDate.format("dd/MM/yyyy") =#_

Component and System=Query1-cbdbeb60-6b87-4f94-8bfa-7ed8baf7a3c1,
  Correlation ID=9d06819c-4647-c05e-bf84-fd27fad8a135, Tenant
  ID=00000000-0000-0000-0000-000000000000 Error code=, Flow
  Name=Microsoft.SharePointSearchProviderFlow, Operator
  Name=ParserExecutor, Message=The processing of item fails with error
  Object reference not set to an instance of an object.
Microsoft.Ceres.InteractionEngine.Component.FlowHandleRegistry :
  Exceptions occurred when evaluating the flow.
  Microsoft.Ceres.Evaluation.DataModel.EvaluationException: Evaluation
  failed in operator IndexLookupExecutor of type IndexLookupExecutor
  ---> System.NullReferenceException: Object reference not set to an instance of an object.      at
  Microsoft.Office.Server.Search.Query.Pipeline.Processing.DisplayResults.RetrieveRecords(IList1
  docIds, IList1 fieldsList, IQueryPipelineService
  queryPipelineService, IMarsLookupService lookup, Int64 generationId,
  Int64 timeout, Guid correlationId, Guid tenantId, Guid
  siteCollectionId, String docIdFieldName)      at
  Microsoft.Office.Server.Search.Query.Pipeline.Processing.ResultTypeCalculatorEvaluator.ResultTypeCalculatorRecordSet.RetrieveDisplayFields(Guid
  correlationId, Guid searchApplicationId)      at
  Microsoft.Office.Server.Search.Query.Pipeline.Processing.ResultTypeCalculatorEvaluator.ResultTypeCalculatorRecordSet.DoMoveNext()
  at
  Microsoft.Ceres.Evaluation.Processing.RecordSets.RecordSet.MoveNext()
  at
  Microsoft.Ceres.Evaluation.Processing.RecordSets.RecordSet.d__0.MoveNext()
  at System.Linq.Buffer1..ctor(IEnumerable1 source)      at
  System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)      at
  Microsoft.Office.Server.Search.Query.Pipeline.Executors.IndexLookupExecutor.ExecuteCore(IRecord
  inputRecord)      at
  Microsoft.Office.Server.Search.Query.Pipeline.Executors.QueryPipelineFlowExecutor.Execute(IRecord
  inputRecord)      at
  Microsoft.Office.Server.Search.Query.Pipeline.Processing.ExecutorProducer1.ProcessRecord(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithoutTryCatch(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.PushToOutput()
  at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithoutTryCatch(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.PushToOutput()
  at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithoutTryCatch(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.PushToOutput()
  at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithoutTryCatch(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.PushToOutput()
  at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithoutTryCatch(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.PushToOutput()
  at
  Microsoft.Ceres.Evaluation.Processing.Producers.ProducerRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.Aborting.AbortableRecordSetSink.Put(IRecord
  record)      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithTryCatch(IRecord
  record)     -  -- End of inner exception stack trace ---      at
  Microsoft.Ceres.Evaluation.Engine.ErrorHandling.HandleExceptionRecordSetSink.DoWithTryCatch(IRecord
  record)      at
  Microsoft.Ceres.InteractionEngine.Component.FlowHandleRegistry.SubmitData(FlowExecutionInfo
  handle, InputData inputData, Stopwatch timer, String correlationId,
  Guid tenantId, String query, String flowName, Int32
  queryTimeoutMillis)      at
  Microsoft.Ceres.InteractionEngine.Component.FlowHandleRegistry.ExecuteFlow(String
  flowName, InputData input, Int32 queryTimeoutMillis)

A:
Bill To Date:  _#= billToDate.format("dd/MM/yyyy") =#_

this property (billToDate) is never mentioned before!
You have missed:
var billToDate = new Date($getItemValue(ctx, "BillToDate"));


text:
Q: Can I factor in the sum of a projector? If $P_j$ is a projector of the form $P_j=I_X\otimes \left|j\right>\left<j\right|$ then given $\left|x\right>\in X$ and operator $A_i: X\rightarrow X$ is it true that, for if $\{\left|i\right>\}$ forming an orthonormal basis
$$\sum_{j}P_{j}\sum_{i}A_i\left|x\right>\left|i\right>=\sum_{i}P_iA_i\left|x\right>\left|i\right>$$

I've convinced myself of this with
$$\begin{aligned}
\sum_{j}P_{j}\sum_{i}A_i\left|x\right>\left|i\right>&=\sum_{j,i}P_{j}A_i\left|x\right>\left|i\right>\\
&=\sum_{j,i}\left(I_X\otimes \left|j\right>\left<j\right|\right)A_i\left|x\right>\left|i\right>\\
&=\sum_{j,i}\left(I_XA_i\left|x\right>\right)\otimes \left|j\right>\left<j\right|\left|i\right>\\
&=\sum_{j=i}A_i\left|x\right>\otimes \left<j\vert i\right>\left|j\right>+\sum_{j\neq i}A_i\left|x\right>\otimes \left<j\vert i\right>\left|j\right>\\
&=\sum_{j=i}A_i\left|x\right>\otimes \left<j\vert i\right>\left|j\right>\\
&=\sum_{i}A_i\left|x\right>\otimes \left<i\vert i\right>\left|i\right>\\
&=\sum_{i}\left(I_XA_i\left|x\right>\right)\otimes \left|i\right>\left<i\right|\left|i\right>\\
&=\sum_{i}\left(I_X\otimes \left|i\right>\left<i\right|\right)A_i\left|x\right>\left|i\right>\\
&=\sum_{i}P_{i}A_i\left|x\right>\left|i\right>\,\square\\
 \end{aligned}$$
but I'm not that proficient at matrix operations or summation tricks and fear I may have done violence ot both.

A: Yes, if $x\in X$ and if $|x\rangle\,|i\rangle$ means $|x\rangle  \otimes |i\rangle$, then your computation is correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to access JSON child elements I was trying to iterate following JSON object. when i try to access the content-items  using page.content-items getting error.Is it not possible to access an object which have a key with "-"?.Please give a solution how to access this object.
{
      "page": {
        "title": "Romantic Comedy",
        "total-content-items" : "54",
        "page-num-requested" : "1",
        "page-size-requested" : "20",
        "page-size-returned" : "20",
        "content-items": {
          "content": [
            {
              "name": "The Birds",
              "poster-image": "poster1.jpg"
            },
            {
              "name": "Rear Window",
              "poster-image": "poster2.jpg"
            },
            {
              "name": "Family Pot",
              "poster-image": "poster3.jpg"
            }
          ]
        }
      }
    }

A: It is possible to access the key with the - character, but not using dot notation. You need to use brakcet notation:
page['content-items']

to access the property.

A: Just use string value like in arrays:
page['content-items']

A: Use page['content-items'] because content-item is not a valid JavaScript identifier.


text:
Q: Rounding BigDecimal to *always* have two decimal places I'm trying to round BigDecimal values up, to two decimal places.
I'm using
BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING));
logger.trace("rounded {} to {}", value, rounded);

but it doesn't do what I want consistently:
rounded 0.819 to 0.82
rounded 1.092 to 1.1
rounded 1.365 to 1.4 // should be 1.37
rounded 2.730 to 2.8 // should be 2.74
rounded 0.819 to 0.82

I don't care about significant digits, I just want two decimal places. How do I do this with BigDecimal? Or is there another class/library better suited to this?

A: value = value.setScale(2, RoundingMode.CEILING)


text:
Q: Docker : container by app with LAMP included or LAMP container only? I have server with 20/30 sites to hosts and I would like to use Docker containers for scalability, maintenability and security.
After few searches, I found 2 approaches :

*

*one container per application, (with all included such as LAMP),

*one container per "service", such as Apache, Mysql... And apps.

Regarding my goal (20/30 sites to hosts, duplicate containers for similar apps...) I would have chosen the 1st one. Being totally beginner, I ask for advice : what's the best?
Thanks for your answers !
Nicolas

A: The preferred solution in a greenfield is to have one container per service, so an Apache container and a separate Mysql container. Since Apache will spawn and communicate with the app directly in most LAMP stacks, I wouldn't separate these. Place both of these containers inside a docker-compose.yml definition and start them together in a private network (default with docker-compose). This give each pair of containers the ability to refer to each other by dns on the container name, and makes upgrades easier (you can just swap out the db container without rebuilding the web server).
The app, when loaded with a scripting environment like php, will typically be installed as a volume on the Apache container.


text:
Q: how can i make my code indented like this for better readability and ease Just as the title entails I wanna make my code indented like this for better readability. this is my first coding project so I'm not sure how to do that.

I tried doing what's in the picture and it didn't work.


text:
Q: Why are duplicate ID's an error in HTML5 checkup? I have the following code in HTML:

Text1

click to read

Text2

click to read

This code is used for making an overlayed text transition for images in CSS, but if I want to validate this HTML code, it says I have a duplicate ID (here "first" and "desc") but I honestly wouldn't know how I can simplify this. I need to resize "first" with font-size, and "desc" too.
For example: the paragraph with id "first" has to be 14px, and the paragraph with "desc" has to be 12px.
Only those <"p"> (without the quote) elements can not be a child element in the "span" element.
I wouldn't know how to solve this, do you guys have a solution?
Thanks for the answers, I've already changed the ID's to a class.
Still, I wouldn't know how to resize class "first" and "desc" in two different font sizes, because it's apparently "not done" to put a block element in an inline element
EDIT 3: Solved! Using div's is the best solution, I'm using this for school (kind of a project) for making a gallery. With float: left; I can place those images next to eachother.
Thanks for the tips!

A: You've made several mistakes:

*

*id attribute is of type #ID which by the HTML/SGML standard is defined to be unique, if you want to show duplicates you should use class  attribute (this is part of why there's getElementsByClassName returning a list but getElementById returning only a single item in the JavaScript DOM API)

*span is inline element, while p is a block element, HTML does not allow block element inside inline element. You should replace your span with div. You can use display: inline or display: inline-block if you want it to appear like inline level elements. Example of inline elements include: a, span, etc; example of block elements include: div, p, ul, li, etc.

A: Just change it to:

and

EDIT:
You best remove the spans completely. You don't need them. If you feel you need them to wrap block-level elements, you can do that with divs

A: That is due to the element type.

 tag is block level element

 tag is a inline element

Therefore encapsulating a block level element inside an inline level element is incorrect.

A: Because you can use classes.
Change:
1.
id="first" -- into --> class="first"
id="desc" -- into --> class="desc"

2.
You cannot put another tags into a span tag except , , , and
 ...
With
 you can have 2 lines in your span tag


text:
Q: Flutter: search bar-send request to server after delay I have a search bar which does a rest call after 1 second that the user has typed something. But, in case the user digits more letters, like "asd", actually it will perform 3 requests, one for "a", one for "s" and one for "d". Is there a way to do only one call when the user stops?
The code is:
appBarTitle = new TextField(
    controller: _filterController,
    decoration: new InputDecoration(
        hintText: 'Search...'
    )
);
_filterController.addListener(() {
  if (_filterController.text.isEmpty) {
  } else {
    Future.delayed(Duration(seconds: 1), () {
      userWrites(_filterController.text);
    });
  }
});

userWrites(String filterName){
  try {
//TODO: call
  }catch(_) {
 }

}

A: Don't know if it's still useful, but I solved it using the Timer class.
Timer timer;
appBarTitle = new TextField(
    controller: _filterController,
    decoration: new InputDecoration(
        hintText: 'Search...'
    )
);
_filterController.addListener(() {
  if (_filterController.text.isEmpty) {
  } else {
    if(timer != null){
      timer.cancel();
      timer = null;
    }
    timer = Timer(Duration(seconds: 1), userWrites);
  }
});

userWrites(){
  try {
    print(_filterController.text);
    //TODO: call
  }catch(_) {
 }

}


text:
Q: How to use the Procedure with User Defined Table Type in Entity Framework How to use a procedure with a user-defined table type in Entity Framework?
I have the EF with database-first approach, when I add a procedure with a user-defined table type columns it will not reflected in the EF will update the model.
And how can I pass the user-defined table parameter in EF with procedure?
My procedure :
Sample_Proce_Sp
(
@TableTest @UserDefinedTable Readonly
)
AS
BEgin
Select * from @TableTest
END
In EF I have updated the model, will adding the stored procedure it shows the error like
The model was generated with warnings or errors.
Please see the Error List for more details. These issues must be fixed before running your application.
Loading metadata from the database took 00:00:03.1330217.
Generating the model took 00:00:01.9251464.
Successfully registered the assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the Web.Config file.

A: EntityFrameworkExtras on Github looks promising.
From the Git hub Site:
DbContext context = new DbContext("ConnectionString");

var proc = new AddMemberStoredWithAddressesProcedure()
    {
        FirstName = "Michael",
        LastName = "Bovis",
        Age = 26,
        Addresses = new List<Address>()
        {
            new Address() {Line1 = "16", Line2 = "The Lane", Postcode = "MA24WE"}
        }
    };

context.Database.ExecuteStoredProcedure(proc);

Where "AddMemberStoredWithAddressesProcedure" and "Address" are both defined with special attributes.
I got a chance to try it out..
    CREATE TYPE [dbo].[UdtGuidList] AS TABLE(
        [Guid] [uniqueidentifier] NULL
    )
GO

CREATE PROCEDURE [dbo].[MyUdtSproc]
    -- Add the parameters for the stored procedure here
    (@GuidList  UdtGuidList READONLY)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT *
    from Blog b
    INNER JOIN @GuidList gl ON gl.Guid = b.BlogGuid
    --where b.BlogGuid in (SELECT gl.Guid from @GuidList gl)

END

It created this dynamic SQL with 5 rows of the custom type..
declare @p3 dbo.UdtGuidList
insert into @p3 values(N'333f3916-c823-e311-84f2-0022198ef787')
insert into @p3 values(N'33327a17-c34e-e211-9a8c-0022198ef787')
insert into @p3 values(N'333ebc24-c44e-e211-9a8c-0022198ef787')
insert into @p3 values(N'3338d557-c44e-e211-9a8c-0022198ef787')
insert into @p3 values(N'333d7f92-c44e-e211-9a8c-0022198ef787')

exec sp_executesql N'EXEC [dbo].[MyUdtSproc] @GuidList = @GuidList ',N'@GuidList [UdtGuidList] READONLY',@GuidList=@p3

This might get the work done, but the sql could grow large with many rows in the user defined table. I'm going to compare this to old ADO.
I tried the old DataTable ADO (below) and traced SQL to see what it produced. It was EXACTLY the same!
   var dt = new DataTable();

    dt.Columns.Add("Guid");

    foreach (var r in list)
    {
        var row = dt.NewRow();
        row["Guid"] = r.Guid;
        dt.Rows.Add(row);
    }

    using (var conn = new SqlConnection(@"Server=AComputer\DEVSQL;Database=Booyaa;Trusted_Connection=True"))
    {
        using (var sproc = new SqlCommand("[dbo].[MyUdtSproc]", conn))
        {
            var param = new SqlParameter("@GuidList", SqlDbType.Structured);
            param.TypeName = "[dbo].[UdtGuidList]";
            param.SqlValue = dt;
            sproc.Parameters.Add(param);

            if (conn.State != ConnectionState.Open) conn.Open();
            var reader = sproc.ExecuteReader();
        }
    }

Cool! I say this library is a valid option.
Update:
More information from my blog
A Sample Visual Studio Project


text:
Q: Add subpanel one2many field in suitecrm I'm new into suitecrm, I'd like to add a one2many relationship between Campaigns and Products
In a subpanel form, as far as I know, I should modify
suitecrm/modules/Campaigns/metadata/subpaneldefs.php

File, but I don't understand which of these relations should I take as an example.
Could someone put me in the right direction on this?

A: Hello  I am answering this question according to sugarcrm you have to do it same in suitcrm.
I checked there is only one to one relationship in Campaign Module.
So , try to create custom sub panel withe one to many relation
1. Create a new link class
This should go into custom/modules//YourNewLink.php and this class will act as the custom functionality that will build your link between the two records.
<?php

/**
 * Custom filtered link
 */
class YourNewLink extends Link2
{
    /**
     * DB
     *
     * @var DBManager
     */
    protected $db;

    public function __construct($linkName, $bean, $linkDef = false)
    {
        $this->focus = $bean;
        $this->name = $linkName;
        $this->db = DBManagerFactory::getInstance();
        if (empty($linkDef)) {
            $this->def = $bean->field_defs[$linkName];
        } else {
            $this->def = $linkDef;
        }
    }

    /**
     * Returns false if no relationship was found for this link
     *
     * @return bool
     */
    public function loadedSuccesfully()
    {
        // this link always loads successfully
        return true;
    }

    /**
     * @see Link2::getRelatedModuleName()
     */
    public function getRelatedModuleName()
    {
        return '<Your_Module>';
    }

    /**
     *
     * @see Link2::buildJoinSugarQuery()
     */
    public function buildJoinSugarQuery($sugar_query, $options = array())
    {
        $joinParams = array('joinType' => isset($options['joinType']) ? $options['joinType'] : 'INNER');
        $jta = 'active_other_invites';
        if (!empty($options['joinTableAlias'])) {
            $jta = $joinParams['alias'] = $options['joinTableAlias'];
        }

        $sugar_query->joinRaw($this->getCustomJoin($options), $joinParams);
        return $sugar_query->join[$jta];
    }

    /**
     * Builds main join subpanel
     * @param string $params
     * @return string JOIN clause
     */
    protected function getCustomJoin($params = array())
    {
        $bean_id = $this->db->quoted($this->focus->id);
        $sql = " INNER JOIN(";
        $sql .= "SELECT id FROM accounts WHERE id={$bean_id}"; // This is essentially a select statement that will return a set of ids that you can match with the existing sugar_query
        $sql .= ") accounts_result ON accounts_result.id = sugar_query_table.id";
        return $sql;
    }
}

The argument $sugar_query is a new SugarQuery object, the details of which are documented here. What you essentially need to do is extend this query with whatever join/filters you wish to add. This is done in the inner join I've specified.
Note: The inner join can get really complicated, so if you want a real working example, checkout modules/Emails/ArchivedEmailsLink.php and how the core sugar team use this. I can confirm however that this does work with custom joins.
Here is the getEmailsJoin to help you understand what you can actually produce via this custom join.
 /**
   * Builds main join for archived emails
   * @param string $params
   * @return string JOIN clause
   */
  protected function getEmailsJoin($params = array())
  {
      $bean_id = $this->db->quoted($this->focus->id);
      if (!empty($params['join_table_alias'])) {
          $table_name = $params['join_table_alias'];
      } else {
          $table_name = 'emails';
      }

      return "INNER JOIN (\n".
              // directly assigned emails
          "select eb.email_id, 'direct' source FROM emails_beans eb where eb.bean_module = '{$this->focus->module_dir}'
              AND eb.bean_id = $bean_id AND eb.deleted=0\n" .
" UNION ".
      // Related by directly by email
          "select DISTINCT eear.email_id, 'relate' source  from emails_email_addr_rel eear INNER JOIN email_addr_bean_rel eabr
          ON eabr.bean_id = $bean_id AND eabr.bean_module = '{$this->focus->module_dir}' AND
          eabr.email_address_id = eear.email_address_id and eabr.deleted=0 where eear.deleted=0\n" .
           ") email_ids ON $table_name.id=email_ids.email_id ";
  }

2. Add a new vardef entry for the link field.
For this example, I'm going to create the custom link on the contacts module. So this code goes in custom/Extension/modules/Contacts/Ext/Vardefs/your_field_name.php
<?php
$dictionary["Contact"]["fields"]["your_field_name"] = array(
    'name' => 'active_other_invites',
    'type' => 'link',
    'link_file' => 'custom/modules/<YourModule>/YourNewLink.php',
    'link_class' => 'YourNewLink',
    'source' => 'non-db',
    'vname' => 'LBL_NEW_LINK',
    'module' => '<YourModule>',
    'link_type' => 'many',
    'relationship' => '',
);

3. Add the new link as a subpanel
This goes under custom/Extension/modules/Contacts/Ext/clients/base/layouts/subpanels/your_subpanel_name.php

<?php
$viewdefs['Contacts']['base']['layout']['subpanels']['components'][] = array (
  'layout' => 'subpanel',
  'label' => 'LBL_NEW_LINK',
  'context' =>
  array (
    'link' => 'your_field_name',
  ),
);

4. Add the label
Under custom/Extension/modules/Contacts/Ext/Language/en_us.new_link.php

<?php
$mod_strings['LBL_ACTIVE_OTHER_INVITES'] = 'Your New Link';

5. Quick Repair and Rebuild
That should hopefully get you started. Keep an eye on the sugarlogs while you're debugging your queries. I also found using xdebug and SugarQueries compileSql function invaluable in figuring out what I needed to do to get a working INNER JOIN statement.
This is the refrence Link


text:
Q: Composite Key with Entity Framework 7 and SQLite Thank you in advance for your help!
So I'm working on a WPF application and using SQLite with Entity Framework 7.0.0-Beta8 as my ORM framework. I'm trying to create a composite key in order to  prevent multiple insertions of the same data. Unfortunately when I do something like this modelBuilder.Entity<DeviceConfiguration>().HasKey(d => new {d.property1, d.property2}) with using EF Fluent code I get a System.NotSupportedException

System.NotSupportedException was unhandled   HResult=-2146233067
  Message=SQLite cannot support this migration operation.
  Source=EntityFramework.Sqlite

The code that causes this error is here.
public class Device
{
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public Guid Id { get; set; }
   public string DeviceType { get; set; }
   public UInt32 DeviceIdentifier { get; set; }
   public string PreferredConnection { get; set; }

   public List<DeviceConfiguration> DeviceConfiguration { get; set; }
}

public class DeviceConfiguration
{
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public Guid Id { get; set; }
   public string DeviceType { get; set; }
   public UInt32 DeviceIdentifier { get; set; }
   public string Description { get; set; }
   public string DateTime { get; set; }
   public string Configuration { get; set; }
   public string Reason { get; set; }

   public List<Device> Device { get; set; }
}

public class DeviceContext : DbContext
{
   public DbSet<Device> Devices { get; set; }
   public DbSet<DeviceConfiguration> DeviceConfigurations { get; set; }
   public DbSet<PidTuningSet> PidTuningSets { get; set; }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
       string databaseFilePath =  "RUI.db";
       try
       {
           databaseFilePath = Path.Combine(
               Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
               databaseFilePath);
       }
       catch (InvalidOperationException) { }

       optionsBuilder.UseSqlite($"Data source={databaseFilePath}");
   }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Device>()
           .Property(d => d.DeviceType)
           .IsRequired();
       modelBuilder.Entity<Device>()
           .Property(d => d.DeviceIdentifier)
           .IsRequired();

       modelBuilder
           .Entity<DeviceConfiguration>()
           .HasKey(d => new {d.DeviceIdentifier, d.DeviceType});

       modelBuilder.Entity<DeviceConfiguration>()
           .Property(d => d.Description)
           .IsRequired();
       modelBuilder.Entity<DeviceConfiguration>()
           .Property(d => d.DateTime)
           .IsRequired();
       modelBuilder.Entity<DeviceConfiguration>()
           .Property(d => d.Configuration)
           .IsRequired();
       modelBuilder.Entity<DeviceConfiguration>()
           .Property(d => d.Reason)
           .IsRequired();

       modelBuilder.Entity<PidTuningSet>()
           .Property(d => d.Locked)
           .IsRequired();
       modelBuilder.Entity<PidTuningSet>()
           .Property(d => d.PIDValues)
           .IsRequired();
       modelBuilder.Entity<PidTuningSet>()
           .Property(d => d.Description)
           .IsRequired()
           .HasMaxLength(32);
   }
}

If I comment out the modelBuilder.Entity<DeviceConfiguration>().HasKey(d => new {d.DeviceIdentifier, d.DeviceType}); code and create a new migration it works. But if I leave it uncommented, create a new migration and run it I get the above not supported exception. I'm not sure if this action is even supported yet in EF7 or if there is a better way to go about ensuring that there isn't any repeated data in the database.

A: I've create this key on the model level by just creating an attribute and using the [Key] tag and concatenating the values. I don't like this approach and I'd like to do this through EF if possible though.


text:
Q: Why subset does not work with a vector name identical to a column name? I came across a confusing "feature" of subset function (using column name as a vector name for subsetting does not work):
data(iris)
Species <- unique(iris$Species)
i <- 2
Species[i]
subset(iris, subset = Species == Species[i])

sp <- unique(iris$Species)
sp[i]
subset(iris, subset = Species == sp[i])

Could someone explain me, what happens here and why?

A: subset() will first look inside the dataframe for any object you mention, so in your first example Species[i] returns 'setosa' (the same as iris$Species[i]). Only when the object you specify cannot be found inside the data frame, R looks in the parent frames and will find the correct object there.
So it all does work, you just don't understand how it works. You could have read this in the help files :

Note that subset will be evaluated in the data frame, so columns can
  be referred to (by name) as variables in the expression (see the
  examples).

How does this come about?
The reason is the following lines of code in subset() :
e <- substitute(subset)
r <- eval(e, x, parent.frame())

*

*subset (or e) is in your example Species == Species[i]

*x is in your example iris

*parent.frame() returns in your example the global environment.

The second argument of the call to eval, x is called envir. It is the environment (or list or data frame, ...) where the expression is evaluated. In your case, R evaluates Species == Species[i] inside x, which is your data frame.
The third argument, parent.frame(), is the enclosure. This is the environments that encloses the data frame you specified als environment, and is the place where R will look in case the variables aren't found in the dataframe.
See also ?eval


text:
Q: Onclick update with autosuggestion I have created an autosuggestion to show results from a DB table when typing in an html field and I want to use javascript to post another value from the same row the values from the autosuggestions are in.
http://i.imgur.com/ys8mnbV.png
Both those suggestions have their own numbers, they're not duplicates but on to what I need help with, I want the number in the row of anyone of these suggestions to post in the number's field below.
Here's the html form

                            <form class="contentForm" form method="POST" form action="index.php">

                                    Name:*

                                      <input type="text" name="name" class="span4 autosuggest">

                                    Number:*

                                      <input type="text" class="span4 number" name="number" placeholder="ex: ######">

Here's the Javascript
$(document).ready(function() {

$('.span4.autosuggest').keyup(function() {

    var search_term = $(this).attr('value');
    $.post('ajax/search.php', {search_term:search_term}, function(data){
        $('.result').html(data);

        $('.result li') .click(function() {

            var result_value = $(this).text();
            $('.span4.autosuggest').attr('value', result_value);
            $('.result').html('');
            });

        });

    });
});

Here's the PHP that pulls the info from the database table
<?

include '../connect.php';

 if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {

$search_term = mysql_real_escape_string($_POST['search_term']);

$query = mysql_query("SELECT * FROM *table* WHERE id = '$userid' AND name LIKE '$search_term%' ");

while(($row = mysql_fetch_assoc($query)) !== false){

    echo '
', $row['client_name'], '
';
    }
}

      ?>

A: Emit JSON instead of HTML with your PHP. Then populate the fields with Javscript.
PHP (assuming the row containing the number is called "client_number")
<?

include '../connect.php';

if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
   $search_term = mysql_real_escape_string($_POST['search_term']);
   $query = mysql_query("SELECT * FROM *table* WHERE id = '$userid' AND name LIKE '$search_term%' ");

   $results = array();
   while(($row = mysql_fetch_assoc($query)) !== false) {
     $results[] = array('client_name' => $row['client_name'], 'client_number' => $row['client_number']);
   }

   header("Content-Type: application/json");
   echo json_encode($results);
}

?>

Javascript
$(document).ready(function() {

  $('.span4.autosuggest').keyup(function() {
     var search_term = $(this).attr('value');
     $.post('ajax/search.php', {search_term:search_term}, function(data){
        for(var k in data) {
          $('.result').append("
"+data[k].client_name+"
");
        }

        $('.result li') .click(function() {
           $('.span4.autosuggest').val($(this).text());
           $('.span4.number').val($(this).data("number"));
           $('.result').html('');
        });

      });

   });
});


text:
Q: Hide UINavigationController Top bar in storyBoard view Im trying to hide the navigation controller top bar from my storyboard view, because i'm actually hiding it programmatically and when Iloit's getting reescaled in execution time
Here is an image so you can understand it in a better way:

that top bar it's not appearing in my app and I would like to hide it in the storyboard too.
Any clue?
Thanks in advance!

A: Select the Navigation Controller, and go to the settings in the right bar :

In the "Navigation Controler" section, uncheck "Shows Navigation Bar", and you're good to go !
Here is what you'll get :

A: Or you can turn it off using below Code i hope this will work for you !
[self.navigationController setNavigationBarHidden:YES animated:YES];


text:
Q: Is it OK to use both JPA (for normal CRUDs) and JDBC (for batch update & call stored proc) in the same project I am using JPA/Hibernate to call simple CRUD queries (create, update, findByXAndYAndZ...). However, as I know, JPA doesn't support well on calling stored procedures and batch insert/update, so I consider using old JDBC to do that (like this link: http://www.java2s.com/Code/Java/Database-SQL-JDBC/BatchUpdateInsert.htm).
I just wonder if it causes any problems when I mixing JPA and JDBC. Hope that you may share some real-world experiences on this issue. Thanks.
UPDATE:
I have tried the Spring Batch like suggestion of Behrang Saeedzadeh and it worked well.
@Others: you may look at the example of Spring Batch here: http://mkyong.com/spring/spring-jdbctemplate-batchupdate-example

A: It's OK. However you should ensure that you invalidate relevant JPA caches when you make direct JDBC batch updates.
UPDATE: By the way, you might want to consider having a look at Spring Batch. Using Spring Batch you can make batch updates with JPA or with JDBC if you prefer so.


text:
Q: Combining PHP Rtrim in MySql Query I need to remove trailing dot from my domain name. I have example below. What is the correct way to use it in the query?
$tank5 = "SELECT url FROM `db`.`tank` WHERE url LIKE rtrim('%$string%', '.')"; // this don't work I just test it.

I know I can just do this $string = rtrim($string, '.'); before the query but I was hoping I could run it on 1 line.
Is it actually possible? Thanks in advance.

A: Concatenate your string, instead:
$tank5 = "SELECT url FROM `db`.`tank` WHERE url LIKE '%".rtrim($string, '.')."%'";

A: RTRIM would remove trailing blanks.
You would need to use SUBSTRING.
$tank5 = "SELECT url FROM `db`.`tank` WHERE url LIKE CONCAT('%', SUBSTR($string, 1, LENGTH($string)-1), '%');";

If you would want to execute with SQL functions, but a much better way is to do as Repox said.


text:
Q: Using a number keypad with a decimal point via HTML5/JS/PhoneGap I think a similar question has been asked here, but the solutions accepted were the standard HTML5 input type declarations. Allow me to explain:
I want to use the iPhone number keypad which you can trigger with input type="number" but have an asterix appear on that keypad. Now, I don't think this is possible through PhoneGap, yet it is definitely possible through iOS via UIKeyboardTypeDecimalPad but as I'm building hybrid applications, I don't have access to native code, which is where my problem lies. Is it simply not possible to edit the keypad through Javascript/PhoneGap adapter? I wouldn't be too surprised but I'm looking to get as close to confirmation of that as possible.
I know of one half-house alternative, which is:
<input type="number" name="n" />

This will show the numbers as well as some characters. The only problem with this is that I really like having the numbers really big as it improves the user's experience a considerable amount. Any thoughts on this are welcomed as I've been scratching my head on this for days!
Thanks!

A: Apple has a great document: User Experience Coding How-To's for Safari on iPhone.

To display a numeric keyboard, set the value of the pattern attribute to "[0-9]" or "\d".

This results in this:
<input type="text" name="n" pattern="[0-9]*" />

A: I have been looking at this problem and I have concluded that it's not possible yet, I hope the phonegap team implement it soon. There is this jquery keypad that you could implement but I have not tried it yet because it would look out of place in a mobile app


text:
Q: Kentico 10 Link to existing page feature Is there any way to force Kentico 10 to adopt a certain template when I link to another page with a template of a type I do not want?
An example would be I have a folder of CTA's. I want one of these CTA's to link to a page that uses the template "genericTemplate" but I would like the linked page I just created to be of template type "nonGenericTemplate".
The reason for this is that "genericTemplate" does not have the fields I am looking for and I would prefer to not force people to input field data in two places ("genericTemplate" and "nonGenericTemplate")

A: I maybe misunderstanding what you mean by CTA; to me it's a link that a user can click on.
I don't believe that Kentico puts the field on the Page Template object, but on the Page Type object. The Page Type reflects what can be stored against a page, the Page Template reflects how the page looks.
When you create pages in Kentico you can assign a default Page Template to a Page Type in the administration interface; it's in the New document settings category of the Page Type interface called Default page template
If it's Page Type you meant, you can change the administration interface itself to only display fields when certain criteria are met. You could write a macro too, if the logic is quite complex. You can do this against a field itself or if you've got linked classes you can do it against the whole group. That way, you'd only need one Page Type to cover all eventualities.
John


text:
Q: create a new column with a value from rows I have a data table as below

I want to put "a" to a column like below:

A: Delete row:
df = df.drop(0, axis=0)

Add column :
df.insert(0,"",["a","","",""])

First, you need to learn how to use pandas.

A: df1 = pd.DataFrame({'a':[1,2,3,4],'b':[1,2,3,4],'c':[1,2,3,4]})
print(df1)
df2 = df1.drop([0])
df2 = df2.reset_index(drop=True)
print(df2)
df3 = pd.DataFrame({'': [1,' ', ' ']})
df4 = pd.concat([df3,df2],axis = 1)
print(df4)

  a  b  c
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
   a  b  c
0  2  2  2
1  3  3  3
2  4  4  4
      a  b  c
0  1  2  2  2
1     3  3  3
2     4  4  4


text:
Q: Why people use '@extend' in SCSS? In Sass, I could find I can use '@extend' with '@mixin'.
But from the code, I got curious what's the advantage of using extend.
If we know which 'classes' exactly what do we have to use, we can just use two classes, not extend and make another class.
In my opinion, if we just use two classes, not making multiple extends, code would be shorter and we can save memory. What can I think of the advantage is it's just more easy to see on 'CSS output', but usually people just check SCSS file, not CSS code output.
Isn't it just better to use two separate classes instead of using multiple extends? What is the main advantage of using '@mixin'?

A: It helps you write DRY code quickly. @extend can be very useful when used properly.
It allows a selector to extend the styles of another selector, essentially providing a form of sub-classing. @extend works by combining selectors into a single comma-separated selector.
I.e. -
.A {
    font-size: 1rem;
    color:red;
}

.a{
    @extend .A;
    line-height: normal;
   }

Which outputs:

.A,.a {
   font-size: 1rem;
    color:red;
}

.a{
   line-height: normal;
}

A: There are a couple of important issues with extends to keep in mind:

*

*they change the order of your CSS rules and re-group them often awkwardly which can have unintentional issues down the road

*they are less performant than Mixins when your Sass is minified and gzipped.

Great article detailing these issues by Harry Roberts: "Mixins for Better Performance"


text:
Q: Do I need server-end knowledge (e.g. Django, Rails), if I want to do Javascript, AJAX stuff? I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.)
However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding).
So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff?
Pardon me for my imprecise choice of terminologies.

A: You need to know a bit about the server side. Here's what you need to know.
If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects.
So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it.
If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON.
I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: http://www.trailbehind.com/comment_widget/

A: You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.).
As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.

A: Yes and no.  Typically what people think of AJAX, such as posting a comment on YouTube and seeing the comment appear instantly with a thank you message, for example, requires a server side language handling the requests, looking up data and returning results as html snippets, JSON data, or XML.
However, an AJAX call can be made to static resources as well.  You could have an XML file or html snippet stored statically on your web server and have it loaded.  The uses for this sort of static loading are generally fewer because if you already have the static html or data in file next to your regular page, why not just put that data directly into the page?

A: It helps to set up a local server and write a few lines of code to service your AJAX calls. You can do a lot of JavaScript learning with just a little back-end learning.

A: If you're new in web development you'd rather wait with Ajax and server-side languages until you've learnt the basics with HTML, CSS and JavaScript, especially if you want to mostly work with the user interface and not the funcionality.

A: As you said you can let somebody else do the back-end and focus on front-end (JavaScript, HTML, CSS).
You would need to communicate with the back-end developer when storing or processing data from the server.
As mentioned before back-end development knowledge would be useful but if you have someone doing it, it's not essential for beginning.


text:
Q: maximum recursion depth exceeded - ProfileReport & sqlalchemy I wanted to connect to db; access tables; do data profiling but keep on getting the maximum recursion error. I can upload csv and run the profilers individually. What's my mistake in terms of fetching the data?
Code:
#importing libraries
from sqlalchemy import create_engine
import pandas as pd
import pandas_profiling
import numpy as np
import time

# Create an engine to the census database
engine = create_engine('postgresql+psycopg2://{dbname}:{password}@{string}/{dbname}')

# Print the table names
lst = engine.table_names()

for x in lst:
    time.sleep(60)#sleep for 60 seconds
    df = pd.read_sql_query('''SELECT * FROM '''+x, engine)
    report = pandas_profiling.ProfileReport(df,correlation_threshold=1)
    report.to_file(x + ".html")

Error I am getting:
<ipython-input-16-5845b8468e3b> in <module>()
      5     time.sleep(60)#sleep for 1 second
      6     df = pd.read_sql_query('''SELECT * FROM '''+x, engine)
----> 7     report = pandas_profiling.ProfileReport(df,correlation_threshold=1)
      8     report.to_file(x + ".html")

C:\Users\katep\Miniconda3\envs\cy_example\lib\site-packages\pandas_profiling\__init__.pyc in __init__(self, df, **kwargs)
     64         sample = kwargs.get('sample', df.head())
     65
---> 66         description_set = describe_df(df, **kwargs)
     67
     68         self.html = to_html(sample,

C:\Users\katep\Miniconda3\envs\cy_example\lib\site-packages\pandas_profiling\describe.pyc in describe(df, bins, check_correlation, correlation_threshold, correlation_overrides, check_recoded, pool_size, **kwargs)
    361         pool = multiprocessing.Pool(pool_size)
    362         local_multiprocess_func = partial(multiprocess_func, **kwargs)
--> 363         ldesc = {col: s for col, s in pool.map(local_multiprocess_func, df.iteritems())}
    364         pool.close()
    365

C:\Users\katep\Miniconda3\envs\cy_example\lib\multiprocessing\pool.pyc in map(self, func, iterable, chunksize)
    251         '''
    252         assert self._state == RUN
--> 253         return self.map_async(func, iterable, chunksize).get()
    254
    255     def imap(self, func, iterable, chunksize=1):

C:\Users\katep\Miniconda3\envs\cy_example\lib\multiprocessing\pool.pyc in get(self, timeout)
    570             return self._value
    571         else:
--> 572             raise self._value
    573
    574     def _set(self, i, obj):

RuntimeError: maximum recursion depth exceeded```


text:
Q: How to initiate class property dynamically I have the following stuff
String[] header1 = {"func", "name", "lrt"};
String[] value11 ={"f1", "n1", "0.1"};
String[] value12 ={"f2", "n2", "0.2"};
......

String[] header2 = {"name", "func", "lrt"};
String[] value21 ={"n3", "f3", "0.1"};
String[] value22 ={"n4", "f4", "0.2"};
......

class unit {
  String func;
  String name;
  double lrt;
}

I have more than 1000 groups of different headers (and their attached values) organized in different order.
how can I initiate the unit class with the property name matching different headers.
Thanks in advance.

A: I suggest to use reflection for that it is actually quite easy:
unit u = new unit();
for(int i=0;i<;header1.lenght;i++) {
  String h = header1[i];
  String v = value11[i];
  Field f = u.getClass().getDeclaredField(h);
  f.set(u, v);
}

Obviously you will need some more infrastructure to iterate your data tuples ... value11, value12, etc.

A: HashMap would be a better approach to your implementation:
Map<String[], ArrayList<Object[]>> unit = new HashMap<String[], ArrayList<Object[]>>();

String[] header1 = {"func", "name", "lrt"};
Object[] value11 ={"f1", "n1", 0.1};
Object[] value12 ={"f2", "n2", 0.2};

String[] header2 = {"name", "func", "lrt"};
Object[] value21 ={"n3", "f3", 0.1};
Object[] value22 ={"n4", "f4", 0.2};

ArrayList<Object[]> values = new ArrayList<>();
values.add(value11);
values.add(value12);
unit.put(header1, values);

values.clear();
values.add(value21);
values.add(value22);
unit.put(header1, values);

Try this and you will have a unit object holding all your values.


text:
Q: stringstream extraction not working I seem to be having a problem with extracting data from a stringstream. The start of my extraction seems to be missing the first two characters.
I have something similar to the following code:
    std::stringstream ss(
    std::stringstream::in |
    std::stringstream::out
    );

    bool bValid;
    double dValue;
    double dTime;

    for( (int i = 0; i < 5; i++ )
    {
        bValid = getValid();
        dValue = getValue();
        dTime = getTime();

        // add data to stream
        ss << bValid;
        ss << dValue;
        ss << dTime;
    }

    int strsize = ss.str().size();
    char* data = new char[strsize];
    std::strcpy(data, ss.str().c_str());

    // then do stuff with data
    // ...... store data in an Xml Node as CDATA

    // read data back
    std::stringstream ssnew( std::stringstream in | std::stringstream out );
    ss.clear();
    ss << getCharData(); // returns a char* and puts it in stream.

    for( int i = 0; i < 5; i++ )
    {
        ssnew >> bValid;  // do something with bValid
        ssnew >> dValue;  // do something with dValue
        ssnew >> dTime;   // do something with dTime
    }

I am having a problem that when I use the extraction operator when reading data from "ssnew" it seems to skip the first two characters. In the debugger, for example, it is showing that the stringstream has "001.111.62.2003... etc". However, after the first "ssnew >> bValid" bValid becomes "true" and dValue becomes "0.111" and dTime becomes "0.62" indicating that the first two zeros in the stream are being ignored. Why isn't it starting at the beginning of the stream?
Cheers,
Seth

A: Try:
    // add data to stream
    ss << bValid << " ";
    ss << dValue << " ";
    ss << dTime << " ";

A: The reason your original code didn't work is that the extraction was greedy, so ssnew >> bValid gobbled up the "001".
Note that strstream is deprecated in favor of stringstream.


text:
Q: youtubeactivity in android I have created a sample code to view youtube activity.
Here's the code,
package com.example.newandroid;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class VideoActivity extends  YouTubeBaseActivity implements
     YouTubePlayer.OnInitializedListener{
String urlVideo;
public void onCreate(Bundle savedInstance){

    super.onCreate(savedInstance);
    setContentView(R.layout.main);

      urlVideo="5lbVNYAeFiQ";

      YouTubePlayerView youTubeView = (YouTubePlayerView)
                              findViewById(R.id.youtube_api_demo);

        youTubeView.initialize("MY_API_KEY", this);
}
   @Override
   public void onInitializationFailure(Provider arg0,
    YouTubeInitializationResult arg1) {
    // TODO Auto-generated method stub
   Toast.makeText(this, "Error ", Toast.LENGTH_LONG).show();
    }

   @Override
    public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1,
    boolean arg2) {
// TODO Auto-generated method stub
Toast.makeText(this, "Success ", Toast.LENGTH_LONG).show();

      }
        }

And i created the main.xml as,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
  android:layout_height="match_parent"
    android:orientation="vertical" >
 <youtube_api_demo
 android:name="com.google.android.youtube.player.YouTubePlayer"
    android:id="@+id/youtube_api_demo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

My manifest.xml is
  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.newandroid"
  android:versionCode="1"
  android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
  <uses-permission android:name="android.permission.INTERNET"/>

 <application  android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

  <activity
    android:label="@string/youtube_api_demo"
    android:name="com.example.newandroid.VideoActivity">
  <intent-filter >
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
  <meta-data android:name="@string/isLaunchableActivity" android:value="false"/>
   </activity>
  </application></manifest>.

What is wrong in this code. I get the following error,
       android.view.InflateException: Binary XML file line #6: Error inflating class

A: It, probably, shall be
<com.google.android.youtube.player.YouTubePlayerView
   android:id="@+id/youtube_api_demo"
.....
/>


text:
Q: window.open terminated the universal application I am creating an application Universial Windows 10 using WinJS. But my application is always crashed once I call the function window.open. Here is the code:
ref = window.open(authorizationUri, '_blank', 'location=yes')
        if (!ref) {
            deferred.reject(new Microsoft.Utility.Exception('The logon dialog was blocked by popup blocker'));
        } else {
            ref.addEventListener('loadstart', onRedirect);
            if (window["tinyHippos"]) {
                window["__rippleFireEvent"] = onRedirect;
            }
        }

Can anyone help me plz? Many many thanks!!!

A: window.open is not supported in UWP. The link below showed that
HTML and DOM API changes list (HTML)


text:
Q: Is there a difference in performance? Would there be any sort of difference using brackets or not using brackets? Is one faster than the other? Or are they both pretty much the same?
No brackets:
if(codehere == codehere)
    return;

Brackets:
if(codehere == codehere) {
    return;
}

I'm not new to Java, but I was just curious is there was any sort of performance difference.
Sorry if this is the wrong place to post this.

A: In this instance, there would be no difference in performance.
However, as pointed out by @MadProgrammer, coding for readability and maintainability should always be your first priority, and optimisations for performance should only be undertaken once the code works and measurements can be taken.
Using the form with braces is good for maintainability, as it reduces the risk of the following:
if(codehere == codehere)
    doSomething();
    doSomethingElse();

When the reader skims this code, they think that both doSomething() and doSomethingElse() are only called when the if statement is true - which in this case is wrong.
If you use braces in the above example:
if(codehere == codehere) {
    doSomething();
    doSomethingElse();
}

... it becomes obvious how the code is supposed to execute.

A: No, this don't change performance.
But take this link, is a good read:
http://java.dzone.com/news/omitting-braces-not-just-a-mat


text:
Q: sum of series $\frac{1}{1\cdot 3}+\frac{1}{4\cdot 5}+\frac{1}{7\cdot 7}+\frac{1}{10\cdot 9}+\cdots $
The sum of series
$$\frac{1}{1\cdot 3}+\frac{1}{4\cdot 5}+\frac{1}{7\cdot 7}+\frac{1}{10\cdot 9}+\cdots $$

My attempt $$\displaystyle \sum^{n}_{k=1}\frac{1}{(3k-2)(2k+1)}=\frac{1}{7}\sum^{n}_{k=1}\bigg[\frac{3}{3k-2}-\frac{2}{2k+1}\bigg]$$
$$=\frac{1}{7}\sum^{n}_{k=1}\int^{1}_{0}\bigg(3x^{3k-3}-2x^{2k}\bigg)dx$$
$$=\frac{1}{7}\int^{1}_{0}\bigg(\sum^{n}_{k=1}3x^{3k-3}-2x^{2k}\bigg)dx$$
$$=\frac{1}{7}\int^{1}_{0}\bigg[\frac{3(1-x^{3n})}{1-x^3}-\frac{2(1-x^{2n+2})}{1-x^2}\bigg]dx$$
How do i solve it Help me please

A: Such integrals can be expressed by the digamma function. One of the formulae for the digamma function is
$$ \psi(z+1) = -\gamma + \int_0^1 \frac{1-t^z}{1-t}dt $$
You have then
$$ \int_0^1 \frac{1-x^{3n}}{1-x^3} dx = \int_0^1 \frac{1-t^{n}}{1-t} \frac13t^{-\frac23}dt = \int_0^1 \frac13 \Big(\frac{1-t^{n-\frac23}}{1-t}-\frac{1-t^{-\frac23}}{1-t}\Big)dt = \frac13\big(\psi(n+\frac13)-\psi(\frac13)\big)$$
$$ \int_0^1 \frac{x^2(1-x^{2n)}}{1-x^2} dx = \int_0^1 \frac{t(1-t^{n})}{1-t} \frac12t^{-\frac12}dt = \int_0^1 \frac12 \Big(2\frac{1-t^{n+\frac12}}{1-t}-2\frac{1-t^{\frac12}}{1-t}\Big)dt = \frac12\big(\psi(n+\frac32)-\psi(\frac32)\big)$$
so
$$ \sum_{k=1}^n \frac{1}{(3k-2)(2k+1)} = \frac17\big(\psi(n+\frac13)-\psi(n+\frac32)-\psi(\frac13)+\psi(\frac32)\big)$$
The same formula can be derived faster, using the fact that $$ \psi(n+z)-\psi(z) = \sum_{k=0}^{n-1}\frac{1}{z+k}$$
so
$$ \sum_{k=1}^{n}\frac{1}{k-\frac23}=\sum_{k=0}^{n-1}\frac{1}{k+\frac13} = \psi(n+\frac13)-\psi(\frac13) $$
$$ \sum_{k=1}^{n}\frac{1}{k+\frac12}=\sum_{k=0}^{n-1}\frac{1}{k+\frac32} = \psi(n+\frac32)-\psi(\frac32) $$
If you want to calculate the infinite sum, you have
\begin{align} \sum_{k=1}^\infty \frac{1}{(3k-2)(2k+1)} &= \frac17 \int_0^1 \Big(\frac{3}{1-x^3} - \frac{2x^2}{1-x^2}\Big) dx =\\ &= \frac17\int_0^1 \Big(\big(\frac{1}{1-x}+\frac{x+2}{x^2+x+1}\big) - \big(-2 + \frac{1}{1-x}+\frac{1}{x+1}\big)\Big) dx =\\ &= \frac17 \int_0^1 \Big(\frac{x+2}{x^2+x+1} +2 - \frac{1}{x+1}\Big) dx \end{align}
and the last integral can be computed with standard methods for the integrals of rational functions:
\begin{align} \int_0^1 \frac{x+2}{x^2+x+1} dx &= \int_0^1 \frac{(x+\frac12)+\frac32}{(x+\frac12)^2+\frac34} dx =^{t=\frac{2}{\sqrt{3}}(x+\frac12)} \\
&= \int_{1/\sqrt{3}}^{\sqrt{3}} \frac{t+\sqrt{3}}{t^2+1} dt = \\
&= \Big(\frac{1}{2}\log(t^2+1) + \sqrt{3}\arctan t\Big)\Big|_{t=1/\sqrt{3}}^{t=\sqrt{3}} = \\
&= \frac{1}{2}\log 3 + \frac{\pi\sqrt{3}}{6}\end{align}
$$ \int_0^1\frac{1}{x+1} dx = \log(x+1)\big|_{x=0}^{x=1}= \log 2 $$
so
$$ \sum_{k=1}^\infty \frac{1}{(3k-2)(2k+1)} =\frac17 (2+ \frac{\pi\sqrt{3}}{6}+\frac{1}{2}\log 3 -\log 2) $$

A: (CONSIDERING INFINITE SUM)
We have $$I_n=\frac 37\int_0^1 \frac {1-x^{3n}}{1-x^3} dx-\frac 27\int_0^1 \left(\frac {1-x^{2n+2}}{1-x^2} +\frac {x^2-1}{1-x^2}\right) dx$$
Let the first integral be denoted by $I_{1,n}$ and the second be denoted by $I_{2,n}$
Hence for the sum we need $$\lim_{n\to\infty} \frac 37 I_{1,n}-\frac 27 I_{2,n}$$
Now note that using the substitution $x^3=t$ in $I_{1,n}$ we get $$I_{1,n}=\frac 13 \int_0^1 \left(\frac {1-t^{n-\frac 23}}{1-t} -\frac {1-t^{-\frac 23}}{1-t}\right)dt$$
Now using the Integral relation if Digamma function I.e. $$\psi(z+1)+\gamma=\int_0^1 \frac {1-x^z}{1-x}dx$$
We get $$I_{1,n}=\frac 13\left(\psi\left(n+\frac 13\right)-\psi\left(\frac 13\right)\right)$$
Similarly using the substitution $x^2=u$ and the same integral relation in $I_{2,n}$ we get $$I_{2,n}= \frac 12\left(\psi\left(n+\frac 32\right)-\left[\psi\left(\frac 12\right)+\frac {1}{1/2}\right]\right)$$
But using that $$\psi(z+1)=\psi(z)+\frac 1z$$ we have $$I_{2,n}= \frac 12\left(\psi\left(n+\frac 32\right)-\psi\left(\frac 32\right)\right)$$
Now taking the limit we see that $$\lim_{n\to\infty} I_n=\frac 17\left[\lim_{n\to\infty} \left(\psi\left(n-\frac 23\right)-\psi\left(n+\frac 32\right)\right)\right]+\frac {\psi\left(\frac 32\right)-\psi\left(\frac 13\right)}{7}$$
Now for large $n$; $\psi(n)\sim \ln n$ . Using this the limit inside square brackets turns $0$
Thus the sum is equal to $$\frac {\psi\left(\frac 32\right)-\psi\left(\frac 13\right)}{7}$$
Which can be simplified using known values of Digamma function.
Edit: You can use from Wikipedia that $$\psi\left(\frac 13\right)=-\frac {\pi}{2\sqrt 3}-\frac {3\ln 3}{2}-\gamma$$
And $$\psi\left(\frac 32\right)=2-2\ln 2-\gamma$$

A: The approximate value of sum of terms in $HP$ is $S_n\approx \frac{1}{d}\ln(\frac{2a+2(n-1)d}{2a-d})$ here $a$=reciprocal of first term  $(a_1=4,a_2=3)$ respectively. $d$=difference between the reciprocal of two terms $(d_1=3,d_2=2)$ respectively
Note that the two HPs  are $3+3(\frac{1}{4}+\frac{1}{7}+....)-2(\frac{1}{3}+\frac{1}{5}+\frac{1}{7}+...)$


text:
Q: How to find overlap of lists in a list I have this get_over_lap function I found on stackoverflow:
def get_over_lap(a,b):
    return max(0, min(a[1],b[1])-max(a[0],b[0]))

This will return the overlap of two lists, for example:
ovl = get_over_lap([30,74],[10,47])
-> Overlap is 17

How do I iterate through a list like this to determine the overlap of all the small lists inside and return a new list of overlap
[[4, 43], [9, 47], [76, 122], [30, 74], [10, 47], [81, 125], [84, 124], [47, 90], [1, 38]]
[30, 74] [10, 47]


text:
Q: How to color code rows in a table dc.datatable? On the DC.js github, Stock Market Selection Strategy by Lon Riesberg is listed as an example of using the dc.js library.
He was able to color code the rows, as shown in the image below, which I'm trying to mimic.

See here for my code: http://codepen.io/chriscruz/pen/myaWvR?editors=101
In particular, how would I change the color of the rows so that all rows with the name 'Red' are red, with the name 'Blue' are Blue, and the name 'White' are white.
Javascript:
items = [
            {Id: "01", Name: "Red", Price: "1.00", Quantity: "1",TimeStamp:111},
            {Id: "02", Name: "White", Price: "10.00", Quantity: "1",TimeStamp:222},
            {Id: "04", Name: "Blue", Price: "9.50", Quantity: "10",TimeStamp:434},
            {Id: "03", Name: "Red", Price: "9.00", Quantity: "2",TimeStamp:545},
            {Id: "06", Name: "White", Price: "100.00", Quantity: "2",TimeStamp:676},
            {Id: "05",Name: "Blue", Price: "1.20", Quantity: "2",TimeStamp:777}
        ];

var ndx = crossfilter(items);

var Dim = ndx.dimension(function (d) {return d.Name;})
dc.dataTable("#Table")
  .width(250).height(800)
  .dimension(Dim)
  .group(function(d) {return ' '})
  .size(100)             // number of rows to return
  .columns([
  function(d) { return d.Id;},
  function(d) { return d.Name;},
  function(d) { return d.Price;},
  function(d) { return d.Quantity;},
  function(d) { return d.TimeStamp;},

])
  .sortBy(function(d){ return d.Price;})
  .order(d3.ascending);
dc.renderAll();

HTML:

      ID
      Name
      Price
      Quantity
      Timestamp

How could this be done considering the only attributes that dc.js has are size, columns, sortBy, and order?

A: You had a syntax error and an unknown symbol in your codepen there. The idea is to use chart.selectAll to grab the rows, and then color them based on the data somehow:
.renderlet(function(chart){
    chart.selectAll('tr.dc-table-row')
         .style('background-color', function(d) {
             return d ? d.Name : null;
         })
});

Here's my fork: http://codepen.io/gordonwoodhull/pen/pvqpVV


text:
Q: Date between said dates in sql server with null I have lets say 4 records in the Pay table. Like this
   UserID   Pay    startdate     enddate

      44      10     2006-12-03   2007-12-31
      44      11     2008-01-01   2008-11-01
      44      12     2008-11-02   2012-02-05
      44      13     2012-02-05    NULL

User 44 is paid 10,11,12,13$ per hour in the years mentioned. My question is if now I give a date lets say 02/27/2010, then it should bring 12$ as his pay. Basically check the date between start and end and give. But now if user gives a date like 02/27/2013 then it should give 13$.

A: You want a where statement:
select pt.pay
from PayTable pt
where '2010-02-27' >= startdate and
      ('2010-02-27' <= enddate or enddate is null);

A: Well, if only the enddate field is nullable, you can do a query like
select UserId, Pay
from Pay
where @date between startdate and isnull(enddate, '9999-12-31')


text:
Q: How do I stop duplication in  tag? I am trying to load data from my JSON file and display in the website with .html() function Here is a screen shot of the problem
The original file has some hard coded data and I am suppose to replace this data with the one I have in my JSON file, I tried that with this code, made some progress but every time I click on the other e mail header the same data gets placed in the  tag of my html file (index). I need to find a way to stop data from duplicating. Can somebody help me?! I am new in AJAX/JSON
$(document).ready(function() {

        $.getJSON("email_list.js",
            {format: "json"}).done(function(data){

            console.log(data);
            for (key in data) {
                emailID = "#" + data[key].id;

                $(".email-header")
                .eq(key).attr("id", data[key].id);

                $(emailID).find('td')
                .eq(0).attr("id", "sender" + data[key].id)
                .html(data[key].sender);

                $(emailID).find('td')
                .eq(1).attr("id", "subject" + data[key].subject)
                .html(data[key].subject);

                $(emailID).find('td')
                .eq(2).attr("id", "datetime" + data[key].datetime)
                .html(data[key].datetime);
            }
        });

    // show/hide emails when click on headers
    $("tr.email-header").click(function(){
        id = "#body " + $(this).attr("id");
        //creates the name for each file
        fileID = $(this).attr("id") + ".js";
            //console.log(id);
            $.ajax({
                url: fileID,
                dataType: "JSON",
                success: function(data) {
                    console.log(data);
                    //I need to replace the contents in the HTML file with
                    //my JASON file contents.
                    fElement = $("tr.email-body").find("p");

                        fElement.eq(0).html(data.recipient);
                        fElement.eq(1).html(data.body);
                        fElement.eq(2).html(data.recipient);
                        fElement.eq(3).html(data.body);
                        fElement.eq(4).html(data.recipient);
                        fElement.eq(5).html(data.body);
                }}).fail(function() {
                        console.log(id + " - HAS AN ERROR!");
                });
        $(this).next().eq(0).toggle();

    });

    // hide email on click
    $("tr.email-body").click(function(){
        $(this).hide();
    });

});

A: Here's an updated snippet that is pulling ajax data from your github repo. Just trace through to see how we are accessing the elements in the js file.
Some additional notes:

*

*Try to use classes for repetitive elements like sender subject and datetime rather than ids. Then it is even easier to access them. I didn't change that.

*You have it set to reload the email every time it's header is clicked. Might want to ensure to only load once.

*You should clear out the existing html right away so the placeholder text isn't shown for a split second before the real content gets loaded.

$(document).ready(function() {

  $.getJSON("https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/email_list.js", {
    format: "JSON"
  }).done(function(data) {

    for (key in data) {
      emailID = "#" + data[key].id;

      $(".email-header")
        .eq(key).attr("id", data[key].id);

      f_el = $(emailID).find('td');

      f_el.eq(0).attr("id", "sender")
        .html(data[key].sender);

      f_el.eq(1).attr("id", "subject")
        .html(data[key].subject);

      f_el.eq(2).attr("id", "datetime")
        .html(data[key].datetime);
    }
  });

  // show/hide emails when click on headers
  $("tr.email-header").click(function() {
    let id = $(this).attr("id"),
      emailBody = $(this).next(".email-body"),
      emailRecipient = emailBody.find('p').first(),
      emailContent = emailBody.find('p').last();

    //make the AJAX call here
    $.ajax({
      url: 'https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/' + id + '.js',
      dataType: "JSON",
      success: function(data) {
        emailRecipient.text('To: ' + data.recipient);
        emailContent.text(data.body);
      }
    }).fail(function() {
      console.log(id + " - HAS AN ERROR!");
    });

    emailBody.toggle();
  });

  // hide email on click
  $("tr.email-body").click(function() {
    $(this).hide();
  });

});
.email-body {
  display: none;
}

  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

  <link rel="stylesheet" href="email.css">

Email Inbox

        Sender
        Subject
        Received

        Bob
        Re: Your brains
        01/03/2014 9:56pm

To: Tom@tom.tom

Heya Tom, it's Bob, from the office down the hall...

        Your only friend
        I've been shockingly nice
        04/07/2011 12:34pm

To: want@you.gone

That's what I'm counting on.

        Mr. Fancy Pants
        Chances are...
        10/21/2005 4:16am

To: dancing@the.parade

You thought you had some fancy pants and now you know it's true.


text:
Q: when i reload the page local storage will be empty so i want to store data after reloading in react const [contacts, setContacts] = useState([]);
//Fetch the Value from Local Storage
  useEffect(() => {
    const retrieveContacts = localStorage.getItem(LOCAL_STORAGE_KEY);
    if (retrieveContacts) {
      setContacts(JSON.parse(retrieveContacts));
    }
  }, []);
  //Storage the Value
  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

i tried to fetch data from local storage but it's not working

A: The use of useEffect hooks is the issue. At the second useffect setting the 'contacts' s not happeing since the first one hasn't yet been set. So the value of setting the localstorage goes null. Instead have the value set at the point of useState hooks. Also, when you are using localStorage, it's important to handle the initial state as well. Try the code below.
import React from 'react'
import { useState, useEffect } from 'react';

const App2 = () => {

const LOCAL_STORAGE_KEY = 'key-1'
const [contacts, setContacts] = useState(
    localStorage.getItem(LOCAL_STORAGE_KEY) ? JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) : {name:'james', count:0}
);

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  const handleButtonClickEvent = () => {
    setContacts({name:'james', count:contacts.count + 1})
  }

  return (
    <>

Name: {contacts.name}

Country: {contacts.count}

        <input type='button' value='button' onClick={(e) => handleButtonClickEvent()}></input>
    </>

  )
}

export default App2

A: Your local storage will be empty after every reload because your default 'contacts' value is an empty array. Your second useEffect then saves this empty array to local storage when the component mounts, overwriting whatever value was previously saved there.
You can resolve this by getting rid of your first useEffect, and loading the default 'contacts' value from local storage:
 const retrieveContacts = () => localStorage.getItem(LOCAL_STORAGE_KEY) || []; // Outside of component

 ...

 const [contacts, setContacts] = useState(() => retrieveContacts()); // Inside of component
 useEffect(() => {
   localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
 }, [contacts]);


text:
Q: Octave with gnuplot adds edges in a mesh When doing surf in octave I get the following results, with different graphics_toolkit.

Run:
surf([1 2 ; 1 2 ],[1 1; 2 2],[6 2 ;4 6],'FaceColor','interp')
To change graphics toolkit you may need to restart octave and run:
graphics_toolkit ftlt|gnuplot

I want gnuplot (B) to display edges as in fltk (A). For some reason I dont understand, gnuplot adds a lot of edges in the middle of the plotted faces (B) which I want to remove.
Using 'EdgeColor','none' (C) I'm able to remove all edges, although I want to keep the edges between datapoints (ie, those shown in A).
An option would be to use fltk, but I prefer the presentation (coulouring and shape) and latex support gnuplot provides.
So: How to make gnuplot show only the edges between datapoints (ie. those in A)??
A) Using default fltk:

B) Using gnuplot:

C) Using gnuplot with 'EdgeColor','none'


text:
Q: Модуль хранения данных для Django Как реализовать модуль, который будет хранить общие данные, например:

*

*номер телефона

*email

*адрес

*и т.д.

т.е. данные которые можно было бы использовать в любом месте шаблона, с возможностью изменения в административной части?
Есть идея создать модель, где одно из полей (особый "ключ") по которому можно было бы вызвать определённую запись.
Вот только вопрос, это вообще как нибудь возможно, в шаблоне достучаться до такой записи?

A: Сделайте модуль назовите его как-то и импортируйте в другие модули. Там сделайте какой-нить объект, ну, например, такой:
class User():
    id_user = 0
    listUser = {}

    def __init__(self, name, phone, address, otherthings):
        self.name = name
        self.phone = phone
        self.address = address
        self.otherthings = otherthings
        self.id = User.new_id()
        User.usertolist(self)

    def __str__(self):
        return f"Name is {self.name}, phone: {self.phone}, adr: {self.address}, other: {self.otherthings}"

    @classmethod
    def new_id(cls):
        cls.id_user += 1
        return cls.id_user

    @classmethod
    def usertolist(cls, usr):
        cls.listUser[usr.id] = usr

где то вызывайте его:
first_user = User('Ivan','+7495356882','Moscow','Other things')
second_user = User('Vladimir','+7343257781','Yekaterinburg','Other things')

Если проверить что там, то вот:
print(first_user)
print(User.listUser.keys())

Name is Ivan, phone: +7495356882, adr: Moscow, other: Other things
dict_keys([1])

В общем у вас хоть один набор данных для какого то пользователя, хоть много пользователей - у вас все данные будут доступны через вот подобный класс. А уж что делать с данными - ваше дело.


text:
Q: Is there a redux for dart middleware for api calls to a service I have a small flutter app using redux for dart.
I am currently using redux_thunk for asynchronous actions and it works very well. Except that my async actions so far only contain dummy code like this:
void action(Store<String> store) async {
  final searchResults = await new Future.delayed(
    new Duration(seconds: 1),
    () => "Search Results",
  );

  store.dispatch(searchResults);
}

Now I would like to call a method in a service (e.g. Firestore) but the thunk actions only take the store as an argument. So how would I pass the service into the actions?
Was wondering since I couldn't find any examples of a good pattern.
I found this: https://github.com/brianegan/flutter_architecture_samples/blob/master/firestore_redux/lib/middleware/store_todos_middleware.dart
But it has all async actions as part of the middleware which I don't particularly like.


text:
Q: Enhancing Paint quality I have this paint project that I did using JPanel and Graphics2D. Everything is good except that the quality of the paint itself is bad and is pixelated. How can I improve it? This is where I setup my brush:
public void setupbrush (){
    strk= new BasicStroke(4, Stroker.CAP_ROUND, BasicStroke.JOIN_ROUND);
    bru1=(Graphics2D)jPanel1.getGraphics();
    bru1.fillRect(0, 0, getSize().width, getSize().height);
    bru1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                bru1.fillRect(10, 10, getSize().width, getSize().height);
                bru1.setPaint(Color.red);
                bru1.setStroke(strk);

                }

A: I have this nice little library method I use a lot...
public static void applyQualityRenderingHints(Graphics2D g2d) {
    g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}

I highly recommend that you have a play around with the values and see what works for you.
The first thing you should never do, is apply this to copy of Graphics you didn't create first.  This is important, as Graphics is shared resource which is used by all the components in your window, so making changes to it could have unexpected results
This means this...
bru1=(Graphics2D)jPanel1.getGraphics();

will be a problem, but not just for this answer.  getGraphics is not how painting works, apart from been able to return null, anything you paint to it can be wiped clean the next time a paint cycle occurs
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting should be done.
Then, once you've correct for that, then your paintComponent method might look something like this...
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    applyQualityRenderingHints(g2d);
    // Do your custom painting here
    g2d.dispose();
}


text:
Q: consulta a dos bases para registro de usuario les comento el tema. Tengo dos tablas en una base, la primera son los datos del matriculado, la segunda es la que contendrá los datos del usuario del sitio.
Primero planteo un formulario donde pido al DNI.
Paso a una segunda página en donde estará el formulario de registro.
Pero antes de mostrarme dicho formulario debe hacer dos comprobaciones.
La primera es si esta en la base de matriculados.
La segunda es si ya esta registrado, consultando a la tabla usuarios.
Alguna orientación como plantearlo. Gracias a Todos


text:
Q: Do some browsers block to create image/xml from svg string using new Blob I have some code for generate SVG image using SVG string.. when i run this code, all goes well, but some people that try my apps told to me that the SVG/image is not show. What i want to know is there are any browser or some settings or proxy or security that block to create SVG image from SVG string using Blob??
this is my code (to generate SVG image)
renderSvg = (svgString) => {
    let blob = new Blob([svgString], { type: "image/svg+xml" });
    let url = URL.createObjectURL(blob);
    return (
      <img
        src={url}
        style={{
          border: "2px solid #aeaeae",
          borderRadius: "5px",
          padding: "5px",
        }}
        alt="svg"
      />
    );
  };


text:
Q: Describe the interval where $f_n(x) = \sum_{k=1}^n \frac{x^k}{x^k + 1}$ uniformly converges
Find the interval $f_n(x) = \sum_{k=1}^n \frac{x^k}{x^k + 1}$ uniformly converges.

Try
First, note that $f_n(x)$ converges pointwise when on $(-1,1)$.
I claim, $\forall \epsilon \in (0, 1)$, $f_n(x)$ uniformly converges on $[-1 + \epsilon, 1 - \epsilon]$.

Note : $\forall x \in [-1 + \epsilon,  1-\epsilon]$, we have $|\frac{x^k}{x^k+1}| \le (-1 + \epsilon)^k$, thus
Since $\lim_{n\to\infty} \left(\sum_{k=1}^n (1-\epsilon)^k\right) < +\infty$, we have $f_n$ : uniformly converges (by M-test).

Is my try on the right way?

A: What you have tried so far is correct.
If you have to find all intervals where $f_n$ uniformly converges you also have to prove that if $|x|\ge 1$ then it doesn't converge.
Finding a function $g_n$ such that $\forall n \in \Bbb N, g_n\le f_n$ and $g_n$ diverges would be the way to go.
Hint:

 Try $g_n(x) = \frac 12$, to show that $f_n$ diverges if $|x| \ge 1$


text:
Q: How do I fix this overflow problem when using hover function I have create this container including movie item list and I tried to use hover function. The problem is when I hovering an img the rest of information is hidden from another container list. How do I get this hovering item overflow another container list. Like for example when I hovering an img. It should display the img and information such as Squid game and icon below but it has been hidden from another container. Here is my code:

.movie-list-container{
    margin-left: 50px;
    margin-top: -16vh;
    height:64vh;
    overflow: hidden;
}

.movie-list-wrapper{
   /* position: relative; */
   display: flex;

}

.movie-list{
    /* position: relative; */
    display: flex;
    align-items: center;
    height: 300px;
    transform: translateX(0);
}

.movie-list-title{
    font-size: 23px;
}

.movie-list-item{
    margin-top: 40px;
    margin-right: 3px;
    /* position: relative; */
    border-radius: 10px;

}

.movie-list-item:hover .movie-list-item-img {
    margin-top: -20px;
    padding-left:58px;
    padding-right: 58px;
    transform: scale(1.5,1.5);
    opacity: 1;
    /* position: relative; */
}

.movie-list-item:hover{
    background-color: black;
    padding: auto;

}

.movie-list-item:hover .movie-list-item-icon{
    opacity: 1;
}

.movie-list-item:hover .movie-title{
    opacity: 1;
}

.movie-list-item:hover .movie-list-desc{
    opacity: 1;
}

.movie-list-item:hover .movie-list-type{
    opacity: 1;
}

.movie-icon{
    padding-left: 37px;
    margin-left: 20px;
    margin-top: 20px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    /* position: relative; */
    transform: scale(1.5,1.5);
}

.movie-title{
    padding-left: 15px;
    margin-top: 50px;
    opacity: 0;
    transition: all 0.5s ease-in-out;
    /* overflow:hidden; */
}

.movie-list-item-icon{
    padding-left: 13px;
    border-radius: 50%;
    width: 50px;
    margin-right: -5px;
    opacity: 0;
    transition: all 0.5s ease-in-out;

}

.movie-list-item-img{
    transition: all 0.5s ease-in-out;
    width: 235px;
    height: 136px;
    object-fit: cover;
    border-radius: 5px;
    cursor: pointer;
}

.movie-list-desc{
    padding-left: 15px;
    margin-top: 20px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    position: relative;
    opacity: 0;
    transition: all 0.5s ease-in-out;
}

.movie-list-type{
    padding-left: 15px;
    margin-top: 20px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    position: relative;
    opacity: 0;
    transition: all 0.5s ease-in-out;
    /* overflow: hidden; */
}

Phim Mới Ra

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

Phim Mới Ra

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

A: Are you meaning the text inside .movie-list-item isn't showing on :hover? Your text is there but it's black text on a black background. I changed the text to white to show that the text is still visible on the page. Of course it depends on what size screen you're viewing the page on, which is a different story (that would be a responsive question). When viewed full-size, the text is legible.

.movie-list-container{
    margin-left: 50px;
    margin-top: -16vh;
    height:64vh;
    overflow: hidden;
}

.movie-list-wrapper{
   /* position: relative; */
   display: flex;

}

.movie-list{
    /* position: relative; */
    display: flex;
    align-items: center;
    height: 300px;
    transform: translateX(0);
}

.movie-list-title{
    font-size: 23px;
}

.movie-list-item{
    margin-top: 40px;
    margin-right: 3px;
    /* position: relative; */
    border-radius: 10px;
    color: #fff;

}

.movie-list-item:hover .movie-list-item-img {
    margin-top: -20px;
    padding-left:58px;
    padding-right: 58px;
    transform: scale(1.5,1.5);
    opacity: 1;
    /* position: relative; */
}

.movie-list-item:hover{
    background-color: black;
    padding: auto;

}

.movie-list-item:hover .movie-list-item-icon{
    opacity: 1;
}

.movie-list-item:hover .movie-title{
    opacity: 1;
}

.movie-list-item:hover .movie-list-desc{
    opacity: 1;
}

.movie-list-item:hover .movie-list-type{
    opacity: 1;
}

.movie-icon{
    padding-left: 37px;
    margin-left: 37px;
    margin-top: 5px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    /* position: relative; */
    transform: scale(1.5,1.5);
}

.movie-title{
    padding-left: 15px;
    margin-top: 40px;
    opacity: 0;
    transition: all 0.5s ease-in-out;
    /* overflow:hidden; */
}

.movie-list-item-icon{
    padding-left: 13px;
    border-radius: 50%;
    width: 50px;
    margin-right: 3px;
    opacity: 0;
    transition: all 0.5s ease-in-out;
    background: pink;

}

.movie-list-item-img{
    transition: all 0.5s ease-in-out;
    width: 235px;
    height: 136px;
    object-fit: cover;
    border-radius: 5px;
    cursor: pointer;
}

.movie-list-desc{
    padding-left: 15px;
    margin-top: 5px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    position: relative;
    opacity: 0;
    transition: all 0.5s ease-in-out;
}

.movie-list-type{
    padding-left: 15px;
    margin-top: 5px;
    cursor:pointer;
    align-items: center;
    justify-content: space-around;
    position: relative;
    opacity: 0;
    transition: all 0.5s ease-in-out;
    /* overflow: hidden; */
}

Phim Mới Ra

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

Phim Mới Ra

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action

SQUID GAME

 13+

 Romantic . Action


text:
Q: How do you hook multiple Triggerzones up to a single Respawn Pad in Rec Room? I have multiple elimination zones in my room that immediately teleport anyone that goes into them back to the start of the map. Things like spike beds, swinging blades, bottomless pits, and so on. Each one has a triggerzone but the Respawn Pad only has one pin.
What are my options for connecting all of these triggerzones up to a single respawn pad?

A: I guess there are at least 2 ways:

*

*Assuming that only one trigger zone will fire at any clock tick, you can just add the output of the red pins of the trigger zones and pass the sum into the respawner.

*To deal with cases where the same player can potentially trigger two triggerzones at the same time: connect the red pin of the first triggerzone to the red and cyan input pin of an unequal comparer chip in advanced mode; set the green input pin of that comparer to 0 and connect the red pin of the second triggerzone to the purple input pin of the comparer. Add the two output pins of the comparer and connect the sum to the respawner. (The idea is that the respawner uses the output of the first triggerzone if that is unequal to 0, otherwise it uses the output of the 2nd triggerzone.) For more than 2 triggerzones, you can build a chain with additional comparerers and add chips.

A: 1. Simple addition, ignoring edge cases
You can just add the trigger zone outputs up, using an addition chip, and wire that directly to the respawn point.
Edge cases: If multiple people enter different trigger zones in the same circuit tick, it will respawn neither. If there happens to be a player with the sum of the player IDs of the entering players in the room, it will respawn that player instead.
Example: Two players with IDs 1 and 2 enter two different trigger zones at the same time, the sum 3 will be forwarded to the respawn. If there happens to be a player with ID 3 in the room, that player will be respawned.
In many cases, that is good enough. For example if you don't have multiple people in the room at the same time, or if it is extremely unlikely that 2 enter different zones at the same time. Also note this solution does not guarantee that a player who touches the zone will always be respawned.
2. Repawn chips, for certain situations
You can connect each trigger zone directly to a respawn chip. The respawn chip will do its magic and select a respawn point according the rules specified in the respawn point and game rule chip configuration. If you can live with a single spawn point, or manage players team, or the spawn point teams, or both, in such a way that only the spawn points you want the player to go to are considered, this is the way to go.
Also note that you can use checkpoints to make the game prefer a specific spawn point.
3. Roles

*

*Create a new role, indicating that you want to queue the player for respawn.

*Assign that role when a player enters a trigger zone, one assign role chip per zone.

*Listen to role changes (role assignment chip in role changed mode). On role change, check if the player has the to-respawn role. If he has, remove the role and respawn the player.

The drawbacks here are that it might be a little slower than 1. The more role changes you have going on during the game, the worse this gets. Many chips have a buffer of 20 events they can output, anything else gets lost. This is probably true for the role changed chip as well (I don't actually know that). The more of these systems you set up, the more roles and role changes you have, so losing events gets more likely. Removing the role again, dying, and being revived are all role changes too, and add to this problem.
4. Buffer Chip

*

*Head over to canny and vote on the Buffer Chip.

*Wait until it is implemented.

*Use it instead of the addition chips in 1.

The only drawback here is having to wait. :)


text:
Q: How do you install a USB CD Rom drive? I recently purchased a USB CD ROM drive, but I don't know how to get it to work with my computer which runs Ubuntu 10.04.
http://www.amazon.com/gp/product/B00303H908/ref=oss_product
When I issue the lsusb command, it shows up as:
Bus 002 Device 016: ID 05e3:0701 Genesys Logic, Inc. USB 2.0 IDE Adapter

The computer doesn't recognize it automatically. How can I get this drive to show up as an actual drive on my computer? If this particular drive can't handle Linux, can you recommended one which can and provide a link to it so I can purchase it? Thanks!
Update: I was asked by Scaine to run a command and report back with the output:
joe@joe-laptop:~$ tail -f /var/log/kern.log
Dec 29 12:51:35 joe-laptop kernel: [103190.551437] sr 7:0:0:0: [sr1] Add. Sense: Illegal mode for this track
Dec 29 12:51:35 joe-laptop kernel: [103190.551446] sr 7:0:0:0: [sr1] CDB: Read(10): 28 00 00 00 00 00 00 00 02 00
Dec 29 12:51:35 joe-laptop kernel: [103190.551463] end_request: I/O error, dev sr1, sector 0
Dec 29 12:51:35 joe-laptop kernel: [103190.877542] sr 7:0:0:0: [sr1] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
Dec 29 12:51:35 joe-laptop kernel: [103190.877551] sr 7:0:0:0: [sr1] Sense Key : Illegal Request [current]
Dec 29 12:51:35 joe-laptop kernel: [103190.877559] Info fld=0x0, ILI
Dec 29 12:51:35 joe-laptop kernel: [103190.877562] sr 7:0:0:0: [sr1] Add. Sense: Illegal mode for this track
Dec 29 12:51:35 joe-laptop kernel: [103190.877572] sr 7:0:0:0: [sr1] CDB: Read(10): 28 00 00 00 00 00 00 00 02 00
Dec 29 12:51:35 joe-laptop kernel: [103190.877588] end_request: I/O error, dev sr1, sector 0
Dec 29 13:08:46 joe-laptop kernel: [104221.558911] usb 2-2.2: USB disconnect, address 16

Then when I plugged the drive back into the computer, I got:
Dec 29 13:10:29 joe-laptop kernel: [104324.668320] usb 2-2.2: new high speed USB device using ehci_hcd and address 17
Dec 29 13:10:29 joe-laptop kernel: [104324.761702] usb 2-2.2: configuration #1 chosen from 1 choice
Dec 29 13:10:29 joe-laptop kernel: [104324.762700] scsi8 : SCSI emulation for USB Mass Storage devices
Dec 29 13:10:29 joe-laptop kernel: [104324.762935] usb-storage: device found at 17
Dec 29 13:10:29 joe-laptop kernel: [104324.762938] usb-storage: waiting for device to settle before scanning
Dec 29 13:10:34 joe-laptop kernel: [104329.760521] usb-storage: device scan complete
Dec 29 13:10:34 joe-laptop kernel: [104329.761344] scsi 8:0:0:0: CD-ROM            TEAC     CD-224E          1.7A PQ: 0 ANSI: 0 CCS
Dec 29 13:10:34 joe-laptop kernel: [104329.767425] sr1: scsi3-mmc drive: 24x/24x cd/rw xa/form2 cdda tray
Dec 29 13:10:34 joe-laptop kernel: [104329.767612] sr 8:0:0:0: Attached scsi CD-ROM sr1
Dec 29 13:10:34 joe-laptop kernel: [104329.767720] sr 8:0:0:0: Attached scsi generic sg2 type 5
Dec 29 13:10:34 joe-laptop kernel: [104330.141060] sr 8:0:0:0: [sr1] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
Dec 29 13:10:34 joe-laptop kernel: [104330.141069] sr 8:0:0:0: [sr1] Sense Key : Illegal Request [current]
Dec 29 13:10:34 joe-laptop kernel: [104330.141077] Info fld=0x0, ILI
Dec 29 13:10:34 joe-laptop kernel: [104330.141081] sr 8:0:0:0: [sr1] Add. Sense: Illegal mode for this track
Dec 29 13:10:34 joe-laptop kernel: [104330.141090] sr 8:0:0:0: [sr1] CDB: Read(10): 28 00 00 00 00 00 00 00 02 00
Dec 29 13:10:34 joe-laptop kernel: [104330.141106] end_request: I/O error, dev sr1, sector 0
Dec 29 13:10:34 joe-laptop kernel: [104330.141113] __ratelimit: 18 callbacks suppressed

There was more output than this (the number of lines started growing after the drive was plugged back in, and kept growing), but this is the first few lines.

A: looks like you're suffering from this bug:
https://bugs.launchpad.net/ubuntu/+source/udev/+bug/646293
This problem is reportedly fixed in Natty, but there have been no suggestions about how to fix it properly for Maverick. I'll update this answer when I know more.

A: Well in 10.10 (Did not test with 10.04 but it is most probably will work the same way). Just connect the USB CDROM Drive. Then start any burning software like Brasero or K3B. They will recognize the burner right away. No need to do anything else. But since there are still several External devices that do not yet work 100% then i will answer the alternative for you.
You have for example this one: http://www.newegg.com/Product/Product.aspx?Item=N82E16827135206
Which works with 10.04 and higher. In the feedback you can see somebody already boot from it and installed ubuntu from it.
You also have this one http://www.amazon.com/Samsung-External-Optical-SE-S084C-RSBN/dp/B002C1BBU8/?tag=klnprk-20 that is known to be compatible with Ubuntu.
Anyway it all boils down to the company making the external unit and how fond they are of linux VS if linux has support for that device.
Here -> https://wiki.ubuntu.com/HardwareSupport is a small list of hardware supported by Ubuntu
Another place where i have uploaded several info is here: http://linuxhcl.com/ where you can look for a specific device. Also here: http://hardware4linux.info/ you can do the same thing but has a much bigger database.
Anyway after all that, check either in the ubuntu forum for a device you want to buy or in the comments of that device in the place you are buying. More than likely somebody already tested this in ubuntu.

A: If it doesn't work as you plug it in, it's likely that its not supported.
http://www.amazon.com/External-Slim-CD-ROM-Drive-Black/dp/B000YQSKPM?tag=dudugo-20 This one apparently works on Ubuntu.


text:
Q: How do I get the "Migrate to JUnit 5" option to appear in Intellij IDEA? According to these release notes Intellij 2017.3 and later should have a feature that enables easy migration from JUnit 4 to JUnit 5 (a.k.a. JUnit Jupiter).

However, that's not appearing for me. How do I get it to show up?

A: If it's not showing up, then the inspection is turned off. You can enable it in the Settings by going to:
Editor → Inspections → Java → JUnit → JUnit 4 test can be JUnit 5

Also, make sure that JUnit Jupiter is on your classpath.


text:
Q: spark.driver.memory relationship with "show()" and "count()", except() function performance in spark, scala? I recently used the count() and show() functions using a large dataframe in spark.
And I got the error below.
Diagnostics: Container [pid=xxx,containerID=container_exxx] is running beyond physical memory limits. Current usage: 4.5 GB of 4.5 GB physical memory used; 7.1 GB of 9.4 GB virtual memory used. Killing container.

I used spark with the specifications below.
spark.executor.instances   = 10
spark.executor.cores       = 2
spark.executor.memory      = 20g
spark.driver.memory        = 4g

Here is a simple sample example.
val df1 = Seq(1,2,3).toDF()
val df2 = Seq(2,3,4,5).toDF()
val df3 = Seq(3,4,5,6,7).toDF()
val df4 = Seq(2,3).toDF()
Seq(df1, df2, df3).foreach{ x =>
   val df = x.except(df4).cache()
   val count = df.count()
   println("count: count")
   df.show()
   df.unpersist()
}

I wonder if the driver keeps saving the calculation results for each df while the for statement is running, so I also used cache() and unpersist(), but nothing changed.
Even with such a simple code, the above error occurs, so I am in doubt.
First, The count() and show() functions are calculated in the executor, and the size sent to the driver is not expected to be large.
But, I don't know why that error occurred.
Second, I set the driver memory to 4g, but in the error above, I don't know why 4.5GB and 7.1 GB of 9.4 GB virtual memory used came out.
Finally, can I solve that problem without increasing the driver memory?
I want to know the root cause for the above problems.
Could anyone please explain the above three in detail?