text:
Q: How to convert arrow Function to ES5 function in react I have this arrow function in react:
const Welcome = ({subject, description}) => (

  <Person title={`Welcome ${subject}`}></Person>
  <Profile description={description}></Profile>

)

and I would like to convert to an es5 function but I am not able to get it to work:
var Welcome = function(subject,description) {
   return(
     <Person title="Welcome ".concat(subject)/>
     <Profile description=(description)/>
   );
};

How should I go about it? Thanks

A: You need to do following steps:

*

*wrap the 2 adjacent JSX elements with a common parent element.

*wrap { } around 'Welcome'.concat(subject) and description.

*destructure the function parameter.

var Welcome = function({subject, description}) {
   return(

        <Person title={ 'Welcome'.concat(subject) }/>
        <Profile description={description}/>

   );
};

A: var Welcome = function(subject,description) {
   return(

        <Person title={"Welcome ".concat(subject)}/>
        <Profile description={description}/>

   );
};

try this bro

A: You forgot the destructuring in the params and also fogot to wrap the the html content under one parent tag
var Welcome = function({subject,description}) {
   return(

        <Person title="Welcome ".concat(subject)/>
        <Profile description=(description)/>

   );
};


text:
Q: AWS Amplify DataStore time to sync new item to backend so it is accessible in a Lambda function? my problem:
I am busy developing a Vue web app using Amplify DataStore.
In the web app, when I save a new Item to the DataStore I am unable to immediately access that item using a Lambda function and AWS.DynamoDB.DocumentClient() to query the dynamoDb table using await docClient.query(params).promise(). The result is empty.
If I wait a minute or two after saving the item, I am able to access the item in my lambda function.
I assume that there is a delay in syncing the locally saved item to the backend.
The lambda function is called by a third party via an API immediately after the new item is saved in the web app.
How can I ensure that the item is available to access in my lambda function?

A: You should wait for a 200 response when saving the item, and then issue a strongly consistent read from DynamoDB which will ensure it returns the latest result:
ConsistentRead: true
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property
DynamoDB works on a leader/follower architecture, all writes are persisted by the leader and later replicated to the followers (in milliseconds). It's possible that you are reading from a follower and thus getting an empty response and DynamoDB has not yet replicated that write. Setting ConsistentRead to true will force the read to happen on the leader, which will return the item, so long as your save API had already returned a 200.

A: found a solution, I use DataStore.observe to observe changes in the item (model) that I have saved - msg.opType === 'INSERT' is triggered on first saving (in local storage) and msg.opType === 'UPDATE' when the item is written in the backend dynamoDb table.
Also, these attributes and values are returned in update
              "createdAt": "2022-12-23T13:23:57.978Z",
              "updatedAt": "2022-12-23T13:23:57.978Z",
              "owner": "test",
              "_version": 1,
              "_lastChangedAt": 1671801837996,
              "_deleted": null

and not in first save. So by using a conditional statement I can ensure that the observed item matches mine and then I can trigger my code knowing that the data is available in the dynamoDb table.
Hope this helps anyone coming across a similar issue as mine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating Values of a table from same table without using a select query My Requirement
 Updating Values of a table from same table without using a select query
    this query won't effect any rows.
    My aim : Update val2 of #table where slno=1 with the value of val2 of slno=2
      Is there any other way without doing this method
 Declare @val2 nvarchar(50)
  select @val2=val2  from #table where slno=2
  update #table set val2=@val2 where slno=1

    create table #table
    (
     slno int identity(1,1),
     val nvarchar(50),
     val2 nvarchar(50)
    )

    insert into #table(val,val2)values('1',newID())
    insert into #table(val,val2)values('1',newID())
    insert into #table(val,val2)values('1',newID())

    select * from #table

    update #table set val2=T.val2
      from #table T where slno=1 and T.slno=2

      drop table #table

I have lot of records in the table.
So If i am selecting and update it may effect the performance.

A: Please, provide more info.
Do you have only 2 rows in your table?
Why do you need this kind of update?
I suppose, that your db structure is wrong, but I can't tell exactly, until you explain why do you need this.
Anyway I can suggest a poor way to do this without using select. You can self join the table. It would be better to have addition column, but if you don't have it, how's you should do
    UPDATE T1
    SET T1.val2 = T2.val2
    FROM #table T1 INNER JOIN #table T2
       ON T1.slno = 1 AND T2.slno = 2


text:
Q: I get ''execution fail: cat << EOT | /var/tmp/one/vmm/kvm/deploy '/var/lib/one//datastores/101/103/deployment.0' " Permission denied I'm creating a new VM and get this error. What should I do?

Mon Jan 21 13:06:41 2019 [Z0][ReM][D]: Req:2080 UID:0 one.vmpool.info
  invoked , -2, 0, -200, -1 Mon Jan 21 13:06:41 2019 [Z0][ReM][D]:
  Req:2080 UID:0 one.vmpool.info result SUCCESS,
  "69<..." Mon Jan 21 13:06:41 2019 [Z0][ReM][D]:
  Req:8720 UID:0 one.user.info invoked , 0 Mon Jan 21 13:06:41 2019
  [Z0][ReM][D]: Req:8720 UID:0 one.user.info result SUCCESS,
  "0

  Mon Jan 21 13:06:43 2019 [Z0][VMM][D]: Message received: LOG I 103
  Successfully execute network driver operation: pre.
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG I 103
  Command execution fail: cat << EOT | /var/tmp/one/vmm/kvm/deploy
  '/var/lib/one//datastores/101/103/deployment.0'
  'fast.sense.dcc.ufmg.br' 103 fast.sense.dcc.ufmg.br
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG I 103
  error: Failed to create domain from
  /var/lib/one//datastores/101/103/deployment.0
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG I 103
  error: internal error: process exited while connecting to monitor:
  2019-01-21T15:06:44.029263Z qemu-system-x86_64: -drive
  file=/var/lib/one//datastores/101/103/disk.1,format=qcow2,if=none,id=drive-virtio-disk0,cache=none:
  Could not open '/var/lib/one//datastores/101/103/disk.1': Permission
  denied
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG E 103
  Could not create domain from
  /var/lib/one//datastores/101/103/deployment.0
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG I 103
  ExitCode: 255
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: LOG I 103
  Failed to execute virtualization driver operation: deploy.
Mon Jan 21 13:06:44 2019 [Z0][VMM][D]: Message received: DEPLOY
  FAILURE 103 Could not create domain from
  /var/lib/one//datastores/101/103/deployment.0

A: Resolved!
I added oneadmin to sudo group:
sudo adduser oneadmin sudo

And, added:
user = "root"
group = "root"
dynamic_ownership = 0

to /etc/libvirt/qemu.conf

A: Installing the opennebula-node-kvm package on the VM host server would take care of all of this i.e

*

*creating oneadmin user,

*defining required sudo privileges to oneadmin user

*creating the /etc/libvirt/qemu.conf with the required configuration
user = "root"
group = "root"
dynamic_ownership = 0


text:
Q: Aggregate multiple lookups return no data I have documents like this in DB. And I need to grab the data of each item based on the itemType from their own collection.
      { listId: 2, itemType: 'book', itemId: 5364 },
      { listId: 2, itemType: 'car', itemId: 354 },
      { listId: 2, itemType: 'laptop', itemId: 228 }

Based on MongoDB docs and some search, I figured out that I need to use let and $expr in lookup, to make some condition.
ListItemsModel.aggregate([
    { $match: { listId: 2 } },
    { $lookup:
       {
         from: 'books',
         localField: 'itemId',
         foreignField: '_id',
         let: { "itemType": "$itemType" },
         pipeline: [
            { $project: { _id: 1, title: 1 }},
            { $match: { $expr: { $eq: ["$$itemType", "book"] } }}
         ],
         as: 'data'
       }
     },
     { $lookup:
        {
          from: 'cars',
          localField: 'itemId',
          foreignField: '_id',
          let: { "itemType": "$itemType" },
          pipeline: [
             { $project: { _id: 1, title: 1 }},
             { $match: { $expr: { $eq: ["$$itemType", "car"] } }}
          ],
          as: 'data'
        }
      },
      { $lookup:
       {
         from: 'laptops',
         localField: 'itemId',
         foreignField: '_id',
         let: { "itemType": "$itemType" },
         pipeline: [
            { $project: { _id: 1, title: 1 }},
            { $match: { $expr: { $eq: ["$$itemType", "laptop"] } }}
         ],
         as: 'data'
       }
     }
    ]);

The problem is, in the result all data fields are empty as data: [].
The syntax seems correct to me. What's wrong?

A: Any subsequent reassignment of field values will eliminate any previous value.
So, for your aggregation pipeline, you need to assign different values to each "$lookup" "as" field.
For example:
     // ...
     { $lookup:
       {
         from: 'books',
         // ...
         as: 'booksData'
       }
     },
     { $lookup:
       {
         from: 'cars',
         // ...
         as: 'carsData'
       }
     },
     { $lookup:
       {
         from: 'laptops',
         // ...
         as: 'laptopsData'
       }
     },
     // ...


text:
Q: Freeness of the Canonical $SU(n)$ Action I have another question about $SU(n)$, again I hope it's not too basic. For $n=2$, the action of $SU(2)$ on $C^2$ is free since it's equal to the group of rotations. In general, the group of rotations is properly contained in $SU(n)$, does this mean that its action on $C^n$ is no longer free.

A: Perhaps the generalization you want of the case $n=2$ is that $SU(n)$ acts freely and transitively on itself, and thus also on orthonormal $(n-1)$-tuples of vectors since the last column of an element of $SU(n)$ is determined by the first $n-1$. You can relax the condition to independence if you only want a free action.

A: $SU(n)$ acts freely on $\Bbb C^n\setminus 0$ (not on $\Bbb C^n$) for $n=1,2$, but not for higher $n$ (the stabilizer of a point is $SU(n-1)$). If this is what you are asking about, the answer is "yes". (This IS a basic question, though.)


text:
Q: Swift protocol conformance with associated type using same-type constraint I'm trying to define a protocol B which extends protocol A (the latter containing the associated type C), while using a where clause with same-type constraint as the compiler suggests. However, when doing this the code won't compile anymore. Is this a Swift bug (Swift 4 in this case)?
To be more concrete, the code below does not compile with error:
type 'E' does not conform to protocol 'A'
class D {

}

protocol A: class {
    associatedtype C: AnyObject
}

protocol B: A where C == D {

}

class E: B {

}

Changing the definition of protocol B as specified below will compile but will show this warning instead:
Typealias overriding associated type 'C' from protocol 'A' is better expressed as same-type constraint on the protocol
protocol B: A {
    typealias C = D
}

The only way to make it compile without warnings is to specify the typealias in class E and using the where clause in protocol B, but this seems to duplicate the typealias unnecessary:
protocol B: A where C == D {

}

class E: B {
    typealias C = D
}

A: I guess same type constraint on protocol declaration is not getting read by classes when it conforms to that protocol.
To avoid reduplication of typealias, you can remove same type constraint from protocol B and use extension to give typealias on protocol B.
class D {

}

protocol A: class {
    associatedtype C
}

protocol B: A  {
}

extension B {
    typealias C = D
}

class E: B  {
}


text:
Q: cannot compile matrix to pdf I have a problem knitting my rmd to pdf. I have tried copying the code that works for others from this forum but it is not working for me. I keep receiving:
!LaTeX Error: Can be used only in preamble.
Can anyone please help?
title: "Untitled" output: pdf_document: latex_engine: xelatex
library("tinytex")

`
\documentclass{article}
\usepackage{mathtools}
\usepackage{amsmath}
\begin{document}

\[
\begin{bmatrix}
    x_{11}       & x_{12} & x_{13} & \dots & x_{1n} \\
    x_{21}       & x_{22} & x_{23} & \dots & x_{2n} \\
    \hdotsfor{5} \\
    x_{d1}       & x_{d2} & x_{d3} & \dots & x_{dn}
\end{bmatrix}
=
\begin{bmatrix}
    x_{11} & x_{12} & x_{13} & \dots  & x_{1n} \\
    x_{21} & x_{22} & x_{23} & \dots  & x_{2n} \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    x_{d1} & x_{d2} & x_{d3} & \dots  & x_{dn}
\end{bmatrix}
\]
\end{document}

Thanks for replying to my issue. However, I still can't sort out the problem myself. Hence I have attached the log file for your perusal.
Unt.log


text:
Q: windows batch file errors out on variable name in if statement @IF [%PORT%] == [] (
@echo Error : Com port not specified
goto end
) ELSE (
    IF  x%PORT:COM=%==x%PORT% (
        @echo ERROR: Com port name invalid
        goto end
    )
)

I get the error saying

=PORT was unexpected at this time.

When the outer if statement is successful

A: The problem in your code is that line IF  x%PORT:COM=%==x%PORT% is parsed even when PORT is empty, and since sub-string substitution is used, which is actually aborted with empty variables, the expanded line is invalid syntax.
To fix that, do not use else, but write it as a separate if statement, so it is not parsed if PORT is undefined:
if not defined PORT (
    echo ERROR: COM port not specified
    goto end
)
if "%PORT:COM=%"=="%PORT%" (
    echo ERROR: COM port name invalid
    goto end
)

Additionally, I put quotation marks around the comparison expressions, which is recommended to avoid problems with special characters. Furthermore, to check whether the variable is empty, I used if defined instead of a comparison.


text:
Q: Button values in single textarea In my code
<script>
$(document).ready(function(){
    $("#btn").on('click', function() {
        var caretPos = document.getElementById("txt").selectionStart;
        var textAreaTxt = $("#txt").val();
        var txtToAdd = $("#btn").val();
        $("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
    })
});
</script>

HTML
<textarea id="txt" rows="15" cols="70"></textarea>
<input type="button" id="btn" value="OK" />
<input type="button" id="btn" value="Bye" />
<input type="button" id="btn" value="TC" />

I want to give these values in textarea. But it is only giving value of Ok button. How I can give each button values in textarea

A: You have the same id on elements. ID's must be unique. You can use class and end to this:

$(".btn").on('click', function() {
  $("#txt").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txt" rows="5" cols="10"></textarea>
<input type="button" class="btn" value="OK" />
<input type="button" class="btn" value="Bye" />
<input type="button" class="btn" value="TC" />

A: try this
html
<textarea id="txt" rows="15" cols="70"></textarea>
<input type="button" id="btn" value="OK" />
   <input type="button" id="btn" value="Bye" />
   <input type="button" id="btn" value="TC" />

javascript
 $('input#btn').click(function()
    {
       $('#txt').val($('#txt').val()+this.value); // append the value of each button
    })

Demo here

A: <textarea name="insert" rows="5" cols="30" id="insert" onblur="myFunction()"></textarea>
<button class="myvalue" id="myvalue">Ok</button>
    <button class="myvalue" id="myvalue">Bye</button>
    <button class="myvalue" id="myvalue">Tc</button>
<script>
function insertAt (myField, myValue, startSel, endSel)
 {
if (startSel || startSel == '0') {
    var startPos = startSel;

    var endPos = endSel;

    myField.val(myField.val().substring(0, startPos)+ myValue+ myField.val().substring(endPos, myField.val().length));

  }`  else {
  myField.val() += myValue;
  }`}var targetBox = $('textarea#insert'),
startSel,
endSel;`targetBox.bind('focusout', function() {
startSel = this.selectionStart;
endSel = this.selectionEnd;
});

$(".myvalue").click(function() {
    var myValue = $(this).text();
    insertAt(targetBox, myValue, startSel, endSel);

});
</script>

Finally It Works

A:
My suggestion to you change button id to class because id is unique for each element so you have to use class instead of id.

$("input.btn").on('click', function() {
    $("#txt").val($("#txt").val()+$(this).val());
})

Demo

A: All your buttons have the same 'id', and 'OK' is the first one, so that's the one that's being returned...
To get the value of the button that's clicked you'd need to give each one a unique id (which should be the case anyway).
I would put your buttons in a separate container, probably a div, and apply the click handler to that. In the handler function, see if the event target has a value attribute, and if it has, send it to your textbox.
Or you could give each button a handler, it depends on your circumstances...
Danny


text:
Q: Doubt about instantiating child class of an abstract class I'm on a ASP.Net MVC project with LinqToSQL and multilayer. Users cand upload files, basically Excel and Access file and my service layer will do all of its validation and other stuff.
I was thinking about implement an abstract class named "UploadManager" and 2 child classes: "UploadExcel" and "UploadAccess". Some methods will be common to both classes, such as "SaveFile" and "DeleteFile". But, some other methods will be restricted to an especific child class, such as "ValidateWorksheet" that will belong to "UploadExcel" class only.
I was designing something like this:
    public abstract class UploadManager
    {
        protected void SaveFile(string fileName)
        {
             //Implement
        }

        protected void DeleteFile(string fileName)
        {
             //Implement
        }
    }

   public class UploadExcel : UploadManager
   {
      private bool ValidateWorksheet()
      {
         //Implement
      }
   }

   public class UploadAccess : UploadManager
   {
      private bool ValidateSomethingAboutAccess()
      {
         //Implement
      }
   }

I was thinking about using Interfaces too. But, my main doubt is how can I know which child class I have to instantiate? If uploaded file is an Excel file, it will be "new UploadExcel()" and if it is an Access file, it will be "new UploadAccess()".
Is there a way to accomplish this? Is there a better way? I'm some kinda lost with this...
Thanks in advance!!

A: Could do something like this, a pseudocode:
First:
public abstract class UploadManager
{
   public void SaveFile(string fileName){ //uploading file }
   public abstract bool CanAccept(string sFileName); //abstract

    protected void DeleteFile(string fileName)
    {
       //Implement
    }
}

Second concrete implementation:
 public class UploadExcel : UploadManager
   {
      public override bool CanAccept(string sFileName) {

           //if Excel file return true, else false
      }

      private bool ValidateWorksheet()
      {
         //Implement
      }
   }

   public class UploadAccess : UploadManager
   {
       public override bool CanAccept(string sFileName) {

           //if Access file return true, else false
      }
      private bool ValidateSomethingAboutAccess()
      {
         //Implement
      }
   }

Somewhere in the code you have a collection:
List<UploadManager> managers = new List<UploadManager>{ new UploadExcel(), new UploadAccess()};

//at the time decide to send a file (sFileName):
UploadManager myUploadManager = managers.Find(manager=>{return manager.CanAccept(sFileName);});
myUploadManager.SaveFile(sFileName); //call concrete implementaiton for that specific file

The code works only with UploadManager type, so you create definit abstraction layer over any concrete implementation for any file type uploader you want.
Regards.
Done.

A: The basic idea would be to inplement the validate method as abstract in the base class.
You then only have to worry about the child class when instantiating, for the rest you only deal with the base class methods:
string fileName = ...;  // from your request somehow

UploadManager manager = null;  // note the type of manager, no var

if (System.IO.Path.GetExtension(filename).LowerCase().StartsWith("xls"))
   manager = new UploadExcel ();
else
   ...

manager.Validate();  // calls the Excel or the Access override

And your classes would look more like
public abstract class UploadManager
{
    // SaveFile, DeleteFile

    public abstract bool Validate();
}

public class UploadExcel : UploadManager
{
      public override bool Validate()
      {
          // ...
          return ValidateWorksheet();
      }

      private bool ValidateWorksheet()
      {
         //Implement
      }
}

A: I believe what you're looking for is the Abstract factory design pattern

A: Based on my understanding of your question, you could have a cache of upload managers so that when the user selects to upload the file, you can get the manager relevant to the file extension. i.e.
// Cache of upload managers keyed by their associated file extension
private Dictionary<string, UploadManager> mManagers;

    // ... Add managers to cache in constructor ...

public void Upload(string filename)
{
    string extension = System.IO.Path.GetExtension(filename);

    // See if we have a manager for this extension
    UploadManager manager;
    if(mManagers.TryGetValue(extension, out manager))
    {
        // Validate the file
        // Note: This will call an abstract method in the UploadManager base
        //   class that will be defined in the child classes.
        manager.Validate(filename);
    }
}

A: You can define an interface
public interface IUserDataManager
{
    void SaveFile();
    void DeleteFile();
    void Validate();
}

Then abstract class and two children
public abstract class UserDataManager : IUserDataManager
{
    private readonly string filename;

    protected UserDataManager(string filename)
    {
        this.filename = filename;
    }

    public void SaveFile()
    {
        Console.WriteLine("File saved as: " + filename);
    }

    public void DeleteFile()
    {
        Console.WriteLine("File deleted: " + filename);
    }

    public abstract void Validate();
}

public class AccessUserDataManager : UserDataManager
{
    public AccessUserDataManager(string filename) : base(filename) { }

    public override void Validate()
    {
        Console.WriteLine("Access validated");
    }
}

public class ExcellUserDataManager : UserDataManager
{
    public ExcellUserDataManager(string filename) : base(filename) { }

    public override void Validate()
    {
        Console.WriteLine("Excel validated");
    }
}

And this is how to use it
class Program
{
    static void Main(string[] args)
    {
        IUserDataManager mgr = new AccessUserDataManager("access.db");
        mgr.Validate();
        mgr.SaveFile();
        mgr.DeleteFile();

        mgr = new ExcellUserDataManager("excel.xlsx");
        mgr.Validate();
        mgr.SaveFile();
        mgr.DeleteFile();

        Console.ReadLine();
    }
}


text:
Q: Web app not accesible after deploying to azure web app using azure devops I have one asp.net sample application. I want to deploy this web application to the Azure web app, I used azure DevOps to build and release the pipeline.
I successfully completed the build and release but when I try to access the web app though the azure web app URL it reflects You do not have permission to view this directory or page.
How to rectify the problem?

A: You can visit https://{yourwebsitename}.scm.azurewebsites.net to check if your app files are deployed to site/wwwroot foler in Kudu server.
If your app files are deployed to folder site/wwwroot/appname. You need to check the Path mappings of your  Application Settings. Then in the Virtual applications and directories section, You need to change your Physical path to "site/wwwroot/appname". You can find more details in this blog.
If above doesnot work out. You can do below steps to show more error messages and troubleshoot the issue.

*

*Go to Your Web App in Azure> App Service logs >turn on Detailed Error Messages.

*In the Web Config file add <customErrors mode="Off" /> under <system.web> tag, add <httpErrors errorMode="Detailed"></httpErrors>  under <system.webServer> tag. And update the web.config file to your azure web app.

Check out this thread for details.


text:
Q: How to build Webkit for Android? In my question How Android webview uses webkit? I know that WebViewCore.java loads webcore and chromium_net
static {
        // Load libwebcore and libchromium_net during static initialization.
        // This happens in the zygote process so they will be shared read-only
        // across all app processes.
        try {
            System.loadLibrary("webcore");
            System.loadLibrary("chromium_net");
       }
}

*

*Where is libwebcore.so and libchromium_net.so located?

*I know that webcore is from external/webkit source? So what is chromium_net?

*How can I use webkit source to build .so file so that I can replace the 2 .so file that come with Android source (I heard that Android uses old webkit version)

Thanks in advance

A: There are several open-source web browsers available for Android, considering your question is probably better that you learn from them instead of us trying to reply to all your questions.
Try zirco.


text:
Q: how Bootstrap framework identifies the browser and device width? I am new to web development, and this is my assignment of developing our lab's website.Bootstrap framework says they support various 11 frameworks. How does it identify whether it is chrome or IE or opera? and how does it identify the device width? I think some function must be written in javascript to identify it, so i was trying to understand bootstrap.min.js. But unable to find such function.
Can you please help me, help will be appreciated

A: Its just simple Media Queries. Its very simple concept. Go through this CHRIS COYIER's tutorial to find how it work, again it very simple.
Here is simple example of the mediaquery
@media (min-width: 600px) and (max-width: 800px) {
  html { background: red; }
}

This code says at screen size from 600px to 800px the html background color should be red;


text:
Q: Variable results do not match cout So I am fairly new to C++ and I have this class assignment. Normally I would ask my professor for help, but he does not answer e-mail for students and our class is once a week. I have tried to make this work for days with weird results, so here is the problem.
Here is the prompt:

Sort a single column array and/or sort a 2 dimensional array
  of characters given any column.  Here is what I used as my
  template specification.

Here is the class he gave use to use (we cannot change this):
//This class sorts arrays either ascending or descending
template<class T>
class Prob2Sort
{
private:
    int *index;  //Index that is utilized in     the sort
public:
    Prob2Sort(){index=NULL;}; //Constructor
    ~Prob2Sort(){delete []index;};  //Destructor
    T * sortArray(const T*,int,bool); //Sorts a single column array
    T * sortArray(const T*,int,int,int,bool); //Sorts a 2 dimensional array
};

and here is the driver program (also can't touch it):
cout<<"The start of Problem 2, the sorting problem"<<endl;
Prob2Sort<char> rc;
bool ascending=true;
ifstream infile;
infile.open("Problem2.txt",ios::in);
char *ch2=new char[10*16];
char *ch2p=ch2;
while(infile.get(*ch2)){cout<<*ch2;ch2++;}
infile.close();
cout<<endl;
cout<<"Sorting on which column"<<endl;
int column;
cin>>column;
char *zc=rc.sortArray(ch2p,10,16,column,ascending);
for(int i=0;i<10;i++)
{
    for(int j=0;j<16;j++)
    {
        cout<<zc[i*16+j];
    }
}
delete []zc;
cout<<endl;

And output:

The output from this problem.

The start of Problem 2, the sorting problem
    Lcekoeddhoffbmg
    Lkcmggjcdhhglif
    Cgldjhcekjigcdd
    Cgldjhcekjigcdn
    Bffmdbkcenlafjk
    Fggdijijegfblln
    Jjlncnimjldfedj
    Amliglfohajcdmm
    Balgfcaelhfkgeb
    Kmlhmhcddfoeilc

Sorting on column 15
    Cgldjhcekjigcdn
    Fggdijijegfblln
    Amliglfohajcdmm
    Bffmdbkcenlafjk
    Jjlncnimjldfedj
    Lcekoeddhoffbmg
    Lkcmggjcdhhglif
    Cgldjhcekjigcdd
    Kmlhmhcddfoeilc
    Balgfcaelhfkgeb

Now I did change few things just to get it working; here is my crazy code in main.cpp:
cout<<"The start of Problem 2, the sorting problem"<<endl;
Prob2Sort<char> rc;
bool ascending=true;
ifstream infile;
infile.open("Problem2.txt",ios::in);
char *ch2=new char[(4*17)+ 1];
char *ch2p=ch2;
while(infile.get(*ch2)){ch2++;}

infile.close();
cout<<endl;
cout<<"Sorting on which column"<<endl;
int column;
cin>>column;
char *zc=rc.sortArray(ch2p,4,17,column,ascending);
for(int i=0;i<4;i++)
{
        for(int j=0;j<17;j++)
        {
                cout<<zc[i*17+j];
        }
}
delete []zc;
cout<<endl;

Now here is my class:
template<class T>
T* Prob2Sort<T>::sortArray(const T* arry, int rows, int cols, int column, bool order)
{
    // put into new array to sort and return
    T* a_ray = new T[(rows*cols) + 1];

    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
               a_ray[i*cols+j] = arry[i*cols+j];
        }
        cout << endl;
    }

    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
               cout << a_ray[i*cols+j] ; // displays fine
        }
        cout << endl;
    }

    T temp;
    bool test = true;

    do
    {
        test = false;
        for(int i = 0; i < rows - 1; i++)
        {
            cout << "Row " << i << endl;
            if(a_ray[i*cols+column] > a_ray[(i+1)*cols+column])
            {
                cout << "ELEMENT 1 IS " << a_ray[i*cols+column] << endl;
                temp = arry[i*cols+column];
                cout << "TEMP IS " << temp << endl;
                a_ray[i*cols+column] = a_ray[(i+1)*cols+column];
                cout << "ELEMENT 1 NEW is  " << a_ray[(i)*cols+column] << endl;
                cout << "ELEMENT 2 is " << a_ray[(i+1)*cols+column] << endl;
                a_ray[(i+1)*cols+column] = temp;
                cout << "ELEMENT 2 NEW is  " << a_ray[(i+1)*cols+column] << endl;
                test = true;
             }

        }
    }while(test);

Now the problem is (and  I had this before I touched everything) was... not sure how to explain it, but I added those couts to view the problem so I will post the output
I choose row 0 to sort so the way I have it only sorts that one character in each element so I haven't attempted to do what my professor wants just yet
 // this is the file read in (i also has 2 elements at end of each line for the newline
 //characters which I can see in a hex editor)

abcdefghijklmno
ABCDEFGHIJKLMNO
1234567890pqrst
uvwxyzPQRSTUVWX
Row 0
ELEMENT 1 IS a
TEMP IS a
ELEMENT 1 NEW is  A
ELEMENT 2 is A
ELEMENT 2 NEW is  a
Row 1

// **PORBLEM HERE***

ELEMENT 1 IS a
TEMP IS A

//**the two couts above should be the same... as you can see why here,

   cout << "ELEMENT 1 IS " << a_ray[i*cols+column] << endl;
   temp = arry[i*cols+column];
   cout << "TEMP IS " << temp << endl;

//////////////////////////////// should be same value!!!! but it is not
// t only does this every other loop if I remember right. it will not change the vlauebut retain the last one in it

ELEMENT 1 NEW is  1
ELEMENT 2 is 1

ELEMENT 2 NEW is  A

Thank you for anyone who helps, sorry for my mess but  I reallllly need this and I can't figure out what is going on and even my professor at some point when I was able to ask him, could not but we still have to turn it in, I just can't get this error fixed


text:
Q: Using Unity with ASP.NET MVC 3 for an object stored in Session I've got an MVC controller that stores an object in Session. Different controller actions retrieve the object from Session, do stuff with it, and save it back.
I'd like to use Unity so that the controller just deals with an interface, but I'm not sure how to achieve this (I'm fairly new to the whole dependency injection thing). Here's some sample code:
public class MyController : Controller
{
   [HttpGet]
   public ActionResult Index()
   {
      var state = new State();
      // do stuff with state
      Session[Key] = state;
      return View();
   }

   [HttpPost]
   public ActionResult Change()
   {
      var state = Session[Key] as State;
      // do stuff with state
      Session[Key] = state;
      return View();
   }
}

So basically I want to use IState instead of State. But where/how does Unity inject the concrete implementation? It seems like it can't happen in the constructor, because I only need to instantiate a new object in the Index() action. Is there maybe some magic way I can add a parameter to Index() that Unity can use?

A: If you want to use Unity you must change your implementation little bit. You must define your controller as:
public class MyController : Controller
{
   private IState _state;

   public MyController(IState state)
   {
       _state = state;
   }

   [HttpGet]
   public ActionResult Index()
   {
      // Fill the state but you cannot change instance!
      _state.A = ...;
      _state.B = ...;

      return View();
   }

   [HttpPost]
   public ActionResult Change()
   {
      // Fill the state but you cannot change instance!
      _state.A = ...;
      _state.B = ...;

      return View();
   }
}

Now you need two additional step. You must use PerSessionLifetime manager for your IState resolving and you must configure Unity to resolve controllers and their dependencies - there is some build in support for resolving in ASP.NET MVC 3.
Unity doesn't provide PerSessionLifetime manager so you must build your own.
public class PerSessionLifetimeManager : LifetimeManager
{
    private readonly Guid _key = Guid.NewGuid();

    public override object GetValue()
    {
        return HttpContext.Current.Session[_key];
    }

    public override void SetValue(object newValue)
    {
        HttpContext.Current.Session[_key] = newValue;
    }

    public override void RemoveValue()
    {
        HttpContext.Current.Session.Remove(_key);
    }
}

You can use this lifetime when configuring controller or you can configure extension in unity configuration and define your IState:
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="perSession" type="NamespaceName.PerSessionLifetimeManager, AssemblyName"/>
    <alias alias="IState" type="NamespaceName.IState, AssemblyName" />
    <alias alias="State" type="NamespaceName.State, AssemblyName" />
    <container name="Web">
      <register type="IState" mapTo="State" >
        <lifetime type="perSession" />
      </register>
    </container>
  </unity>
</configuration>

A: You might want to do this with an ActionFilter.  The ActionFilter could grab the object from session state (instantiating it if needed), and add it to your ActionParameters collection.
public class IncludeStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(...)
    {
        var currentState = filterContext.HttpContext.Session[Key] as State;
        if (currentState == null)
        {
            currentState = new State();
        }

        filterContext.ActionParameters["state"] = currentState
    }

    public override void OnActionExecuted(...)
    {
        filterContext.HttpContext.Session[Key] = filterContext.ActionParameters["state"];
    }
}

Then, your Index action looks like this:
[HttpGet]
[IncludeState]
public ActionResult Index(State state)
{
    // do stuff with state
    return View();
}

The only thing I'm unsure about is where your key comes from.
I realize that this doesn't use Unity, but maybe you don't need it.


text:
Q: geom_contour_filled color scale does not correspond to breaks I would like to plot contour fills with colour based on a range of breaks that is larger than the range of the data, so that different plots have the same scale. In the following example, blue and red are expected to correspond to more negative or positive values, respectively. However, when the plot does not contain the full range, geom_contour_filled recognizes the breaks but does not match the colour scale. So, positive values are all blue.
library(ggplot2)

grid <- expand.grid(x=0:10,y=0:10)
grid$z <- with(grid, x*y) # 0 to 100 does not work as expected
# grid$z <- with(grid, 2*x*y-100) # -100 to 100 works as expected

ggplot(grid,aes(x=x,y=y,z=z)) +
  scale_colour_manual( aesthetics = 'fill',
                       values = colorRampPalette(c('blue','white','red'))(20) ) +
  geom_contour_filled( breaks=floor(seq(-100,100, length.out=20)) )

A: You need to add drop = FALSE to your color scale:
ggplot(grid,aes(x=x,y=y,z=z)) +
  scale_colour_manual( aesthetics = 'fill', drop = FALSE,
                       values = colorRampPalette(c('blue','white','red'))(20) ) +
  geom_contour_filled( breaks=floor(seq(-100,100, length.out=20)) )


text:
Q: Node.js: How do I $pull from an array of $oid in Mongo/Mongoose? I'm trying to remove an object from an array of $oid from within a single document with mongoose using update.
Here is a hypothetical schema based on the schema I'm using now:
var TestSchema = Schema({
  name: { type: String },
  otherRefs: [ {type: Schema.ObjectId, ref: 'OtherSchema' } ]
});

An example document would look like (note: these aren't actual ObjectIDs from my db - I just randomly typed them in to give an idea of what the document would look like - the documents in my actual db have valid $oid values:
{ "_id" : { "$oid" : "56da0b6326008d0c24a4f029" },
  "name" : "name1",
  "otherRefs" : [
      {"$oid" : "56c340259402505c2720541b"},
      {"$oid" : "56c340259402505c2720541e"},
      {"$oid" : "56c340259402505c2720541f"},
      {"$oid" : "56d758862494c411001ca603"}
  ]
}

Here is the query I'm trying to use:
TestSchema.update(
    { '_id': testResult._id },
    { $pull: { 'otherRefs': { $oid : mongoose.Schema.ObjectId( refResult._id ) } } },
    false,
    true,
    function(err, success) {
        if (err) {
            res.json(err);
        } else {
            res.json('success', success);
        }
    }
)

Have also tried { $pull: { 'otherRefs': refResult._id } } with no success.
testResult._id and refResult._id are received from previous queries.
Been at this for a while now and can't seem to wrap my head around this problem. Hoping someone can help me figure out what I'm doing wrong.
Thanks!
EDIT:
Now using:
TestSchema.update(
    { '_id': testResult._id },
    { $pull: { 'otherRefs': refResult._id ) } },
    function(err, success) {
        if (err) {
            console.log(err);
        } else {
            console.log('Success');
        }
    }
)

The query doesn't hang anymore and "Success" is getting logged but nothing is changed in the actual document in DB.


text:
Q: How to set pageCount manually in vuejs-paginate? My HTML:
<paginate
        :pageCount="max"
        :containerClass="'pagination'"
        :clickHandler="redirectToPage"
        :force-page="selectedPage">
</paginate>

max is getter from vuex. When paginate is loading max = undefined, so I need to set pageCount after value max is changed.
In offical docs only static value:

A: Taking Belmin Bedak's comment into account, here it is working with a v-if to make it wait for pageCount to load. In testing, I found that updating pageCount works as expected: the number of pages available is updated.

vm = new Vue({
  el: '#app',
  data: {
    max: null
  },
  components: {
    paginate: VuejsPaginate
  },
  methods: {
    clickCallback: function(page) {
      console.log(page);
    }
  },
  mounted() {
    // Pretend we're getting from vuex
    setTimeout(() => {
      this.max = 7;
    }, 1000);
  }
});
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://unpkg.com/vuejs-paginate@0.8.0"></script>
<div id="app">
    <paginate v-if="max"
      :page-count="max"
      :container-class="'pagination'"
      :click-handler="clickCallback">
    </paginate>
    <div v-else>
    Loading...
    </div>
</div>


text:
Q: DRF (Django Rest Framework) verify google token I need to verify google token in my backend drf. I use React library reactjs-social-login, and it works perfect and send data:
{
"access_token": "...",
"token_type": "Bearer",
"expires_in": 3599,
"scope": "...",
"authuser": "0",
"prompt": "none",
"sub": "...",
"name": "...",
"given_name": "...",
"family_name": "...",
"picture": "...",
"email": "...",
"email_verified": true,
"locale": "en"
}

Then I send this data to APIView. I install google-auth library for django. The question is, how can I check validation of this google access token. Library expect another token:
def verify_token(
    id_token,
    request,
    audience=None,
    certs_url=_GOOGLE_OAUTH2_CERTS_URL,
    clock_skew_in_seconds=0,
):

And in this case I've got the exception. My view:
try:
    id_token.verify_oauth2_token(google_user['token'], requests.Request())
except ValueError:
    raise AuthenticationFailed(code=403, detail="Bad token Google")

Thanks for any advices

A:

import jwt
import requests
from rest_framework.serializers import ValidationError

class GoogleAuthProvider:
    def __init__(self, token):
        self.token = token

    def validate_token(self):
        r = requests.get(
            "https://www.googleapis.com/oauth2/v3/tokeninfo",
            params={"id_token": self.token},
        )
        r.raise_for_status()

    def get_decoded_data(self):
        try:
            self.validate_token()
        except Exception:
            error = {"message": "Google token invalid."}
            raise ValidationError(error)
        else:
            data = jwt.decode(self.token, options={"verify_signature": False})
            return {
                "username": data["sub"],
                "email": data["email"],
                "name": data.get("name"),
                "provider": "google",
            }

Basically, create an instance of GoogleAuthProvider and pass the id_token in init.
Then call get_decoded_data() to get info from that id_token.


text:
Q: Ruby: Building a hash from a string and two array values at a time I'm trying to build a hash with:
hash = {}

strings = ["one", "two", "three"]

array = [1, 2, 3, 4, 5, 6]

so that I end up with:
hash = { "one" => [1, 2] ,
         "two" => [3, 4] ,
         "three" => [5, 6] }

I have tried:
strings.each do |string|
  array.each_slice(2) do |numbers|
    hash[string] = [numbers[0], numbers[1]]
  end
end

But that yields:
hash = { "one" => [5,6] , "two" => [5,6], "three" => [5,6] }

I know why it does this (nested loops) but I don't know how to achieve what I'm looking for.

A: If you want a one-liner:
hash = Hash[strings.zip(array.each_slice(2))]

For example:
>> strings = ["one", "two", "three"]
>> array = [1, 2, 3, 4, 5, 6]
>> hash = Hash[strings.zip(array.each_slice(2))]
=> {"one"=>[1, 2], "two"=>[3, 4], "three"=>[5, 6]}

A: hash = {}
strings.each { |string| hash[string] = array.slice!(0..1) }

This is a solution using methods and techniques you seem familiar with. It is not a 'one liner' solution but if you are new might be more understandable for you. The first answer is very elegant though.

A: As Mu says, Zip method is the best choose:
Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. This generates a sequence of self.size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than enumObj.size, nil values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned.


text:
Q: Axios Node.Js GET request with params is undefined I am running a react app with nodejs on backend. Whenever I make an axios call without parameters, everything works, but when I try to add paramaters and use them with req.body.variableName, it prints undefined. Printing req.body is just an empty curly brace so somehow my data is not being sent.
React File with axios call
getFriendCount(){
    var data = {
        UserID: this.state.UserID,
    }
    console.log(data)
    axios.get("http://localhost:8081/getFriendCount", data).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })
}

serversql.js
const HTTP_PORT = process.env.PORT || 8081;
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const cors = require("cors");
const mysql = require('mysql');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const {addNewMemory,getAllMemories, getFriendCount} = require('./db-services.js');

//Database connection...

app.get('/data', getAllMemories);
app.post('/addMemory',urlencodedParser,addNewMemory);
app.get('/getFriendCount',urlencodedParser, getFriendCount);

app.listen(HTTP_PORT, ()=>{console.log("API listening on: " + HTTP_PORT)});

db-services.js (req.body.UserID is undefined)
module.exports={
  getFriendCount:(req,res) => {
    console.log(req.body)        //empty curly brace
    console.log(req.body.UserID) //undefined
    console.log(req.params)      //empty curly brace
    var sql = "SELECT COUNT(*) AS friendCount FROM friendship WHERE UserId1 = (?) OR UserId2 = (?)";
    var values = [req.body.UserID, req.body.UserID]
    dbconnection.query(sql, values, function(err,result,fields){
        if(err){
            return res.status(500).send(err);
        } else {
            res.send(result);
        }
    })
},
}

A: In the Axios.get(), the data represent the params not body data.
So please use the req.params instead the body.
And then node you use the route that way.
app.get('/getFriendCount/:Id',urlencodedParser, getFriendCount);

And then please get the Id using below.
console.log(req.params.Id);

And then you need to change your API like this.
axios.get(`http://localhost:8081/getFriendCount/${this.state.UserID}`)

Please try this.

A: try the following in the client side
  axios.get("http://localhost:8081/getFriendCount", {
          params: {
            UserID: yourUserID
          }
        }).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })

and in the server side instead of using the body use the query like this console.log(req.query.UserID). Hope this helps :)

A: If you want to send a body you can't use a GET method. Only a POST or a PUT method should be used in this case.
GET methods will only take param and query, where `params can be used like this:
app.get('/getFriendCount/:id', handler);
if you would call /getFriendCount/123, req.param.id would return 123
and query could be used like this:
/getFriendCount?name=pedro - req.query would yield { name:"pedro" }


text:
Q: Problem with a Jquery toggleClass script when hovering I'm new to the community, also pretty new in this world of web programming, this is the issue that is driving me nuts,
I tried this code to add a class when I hover the ul list element, so I can display the nav element, but instead of open only the hovered dropdown menu, it displays all the ul element with the class I selected.
Here is the Jquery code:
$(document).ready(function() {
  $("ul").hover(function() {
    $(this)
      .find(".dropdown-list")
      .toggleClass("dropdown-menu");
  });
});

and these are the element targered in my html file:

HOME

    LAYOUT

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

Options

Layout Demos

    FEATURES

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

    ELEMENTS

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

    PAGES

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

    PORTFOLIO

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

    BLOG

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

    SHOP

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

Here is the CSS snippet:
.header-nav-responsive .dropdown-list {
    display: none;
}

.header-nav-responsive .dropdown-menu, .nav-icons-big-screen .dropdown-menu {
    flex-direction: column;
    position: absolute;
    align-items: flex-start;
    background-color: #fff;
    margin-top: 11rem;
    padding: 14px 20px;
    border-radius: 5px;
    display: none;
    visibility: hidden;
    border: 1px solid #e6e8eb;
    box-shadow: 0 14px 20px rgba(0,0,0,.1);
}

.header-nav-responsive .dropdown-menu {
    margin-top: -1.1rem;
}

.nav-icons-big-screen i {
    line-height: 80px;
}

.header-nav-responsive:hover .dropdown-menu, .nav-icons-big-screen:hover .dropdown-menu {
    display: flex;
    visibility: visible;
}

.header-nav-responsive .dropdown-menu li, .nav-icons-big-screen .dropdown-menu li {
    font-size: 0.8125rem;
    font-weight: 400;
    line-height: 25px;
}

.header-nav-responsive .dropdown-menu li a, .nav-icons-big-screen .dropdown-menu li a{
    color: #484848;
    padding: 3px 2px;
}

.header-nav-responsive .dropdown-menu li a:hover, .nav-icons-big-screen .dropdown-menu li a:hover {
    color:#2250fc;

}

At last, you can see how the page display in this link: https://patricio1984.github.io/Polo-template-emulation/
Thanks so much to all in advance! cheers!

A: The problem is because you are adding the event listener to the ul tag(This includes the parent ul too). Instead, you should have an event listener to the li, say with the class 'menu-item' and toggle the class based on that.
$(document).ready(function(){
  $(".menu-item").hover(function(){
    $(this).find(".dropdown-list").toggleClass("dropdown-menu");
  });
});

Here is the fiddle link https://jsfiddle.net/eskcrd3n/

A: Actually your issue here is lies under your main selector. You did go for listening to ul whilst you should listen to li elements. So whenever you listening to ul, the $(this) will refer to
 so all your elements with class dropdown-list will be called for the trigger event.

$(document).ready(function() {
  $("li").hover(function() {
    $(this).find(".dropdown-list").toggleClass("dropdown-menu");
  });
});
.header-nav-responsive .dropdown-list {
  display: none;
}

.header-nav-responsive .dropdown-menu,
.nav-icons-big-screen .dropdown-menu {
  flex-direction: column;
  position: absolute;
  align-items: flex-start;
  background-color: #fff;
  margin-top: 11rem;
  padding: 14px 20px;
  border-radius: 5px;
  display: none;
  visibility: hidden;
  border: 1px solid #e6e8eb;
  box-shadow: 0 14px 20px rgba(0, 0, 0, .1);
}

.header-nav-responsive .dropdown-menu {
  margin-top: -1.1rem;
}

.nav-icons-big-screen i {
  line-height: 80px;
}

.header-nav-responsive:hover .dropdown-menu,
.nav-icons-big-screen:hover .dropdown-menu {
  display: flex;
  visibility: visible;
}

.header-nav-responsive .dropdown-menu li,
.nav-icons-big-screen .dropdown-menu li {
  font-size: 0.8125rem;
  font-weight: 400;
  line-height: 25px;
}

.header-nav-responsive .dropdown-menu li a,
.nav-icons-big-screen .dropdown-menu li a {
  color: #484848;
  padding: 3px 2px;
}

.header-nav-responsive .dropdown-menu li a:hover,
.nav-icons-big-screen .dropdown-menu li a:hover {
  color: #2250fc;
}

HOME

LAYOUT

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

Options

Layout Demos

FEATURES

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

ELEMENTS

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

PAGES

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

PORTFOLIO

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

BLOG

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

SHOP

Topbar

Header

Main Menu

Page Title

Page Menu

Sidebars

Footers

NOTE: The best way to do this is to use a unique class for your menu titles to avoid any inconsistency.

A: THANKS SO MUCH to both you guys!! the Jsfiddle gave me the right idea, here is the corrected function:
$(document).ready(function(){

  $(".menu-item").hover(function(){
    $(this).find(".dropdown-list").toggleClass("dropdown-menu");
  });

});

And I added the menu-item class to all my li items!
Thanks!!! problem SOLVED! That was pretty quick =)


text:
Q: Overleaf and Section Fonts Oveleaf say that it's possible to use a set of pre-installed fonts
 here. One of these is "CMU Classical Serif" I want to change the section title in my document to be "CMU Classical Serif"
I try the following, but the font does not change at all (using package titlesec, XeLaTex compiler for fontspec)
    \newfontfamily\sectionfonts{CMU Classical Serif}
    \titleformat*{\section}{ \center \large \bf}
    \titleformat*{\subsection}{\bf}
    \titleformat*{\subsubsection}{\it}

Is this a problem with Overleaf or have I done something wrong?
Edit: there are no errors, not even "font not found", just no changes...

A: You are using the deprecated font commands such as \bf they will always use the document default encoding and family, they do not combine in the way that latex2e font commands do
Presumably you want something like
\titleformat*{\section}{\centering\sectionfonts\large\bfseries}

A: I think I found a solution: I just need to define a fontfamily separately and then call this inside \titelformat* as @LianTze Lim was suggesting, i.e:
\newfontfamily\headingfont[]{Alexander}
 \titleformat{\section}{\headingfont \centering \large\bfseries}{\S \thesection.}{0.5em}{}[{\titlerule[0.2pt]}]

(the last parts are irrelevant). Thanks also to @DavidCarlisle, although I admit I haven't checked this :)


text:
Q: How to have a collection of objects that the objects are unique based on a special field? I'm new in c#. I want to have a collection that at the first step it is empty. and each object can add to this collection in the way that it becomes unique by a value of a field. For example I want to add a new object to this collection it checks if we have an object with the value of the field "Name" of this object, don't create and add a new object and return this object, otherwise create a new object by the value of the field of "Name", add it to the collection and return it.
if there is an object with the same name:
return it
else:
create a new object add it to the collection and return it.

A: Well, let me visualise your example:
public class Team
{
    public string Name { get; set; }
)

And now you have some collection of teams:
private List<Team> _teams = new List<Team>();

public Team AddAndGetTeam(Team team)
{
    // Try get the team and if it is found, return found object.
    // If not, add the team passed to method and return it.
    var t = _teams.SingleOrDefault(t => t.Name == team.Name);
    if(t == null)
    {
        _teams.Add(team);
        return team;
    }
    else
        return t;
}

I used SingleOrDefault LINQ method, which will help keep teams unique.
You can use any other method/way of getting the team with specified name.


text:
Q: UISearchbar how to determine if last character typed is a backspace I have a UISearchbar with delegate method
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length>3){
 [self updateSearchString:searchText];
}
}

updateSearchString goes out to the internet to get the results, formats them and updates the table view. I do not want this to occur if the user hits the backspace key. So I am thinking something like:
if(searchText.length>3 && lastCharacterTyped!=backspace){
  }

How do i determine the 2nd part?

A: While I don't know of a particular way to detect backspace in Objective-C, the most reliable would be to check the length of the string before and after the lastCharacterTyped is typed. if the latter is less, means a backspace was pressed. Hope that helps.


text:
Q: Loop through array in linq query Hi all I have a query using Linq that returns a set of records, one of which is the country id, I also have an array of desired countries. Is there a way of either looping through the countries array and seeing if the id is in the results, i want to do something like this
results = from r in results
where
//jump to my c# array
for(int x = 0;x < array.count; x++)
{
r.countryId.ToString().Contains(array[x])
}
select r

thanks

A: Try this
var list  =  from r in results
             where array.Contains(r.countryId.ToString())
             select r;

A: You could join the collections, but I think Yograj Gupta's answer is probably the better one.
var query = from a in results
            join b in array
            on a.CountryId equals b.CountryId
            select a;

A: You didn't give the array type so assuming it's testclass1
    class TestClass1
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    List<Country> countries = new List<Country>();
    TestClass1[] arrays = new TestClass1[30];

    countries.Where(x => arrays.Select(y => y.Id).Contains(x.Id)).ToList();

I'm not sure if this is the best approach but i think this will work.
UPDATE : didn't notjce the array is of type country as well so. sorry.


text:
Q: Generate Odoo11 Custom Reports with Wizard. Format error: Not a PDF or corrupted i'm trying to print an Odoo custom report based on a wizard.
it takes inputs from a wizard view. The wizard lets the user select a project with start_date and end_date. and click print button. so the list of activities that match the wizard form fields filter should be printed in a PDF. but i got a PDF file with 0 KB and when i try to open i get Format error: Not a PDF or corrupted. and there is no errors in console
Here is some key files
reports/__init__.py
# -*- coding: utf-8 -*-

from odoo import models, api
class ReportWorkPlan(models.AbstractModel):
    _name = 'ewonga_pta.report_model_work_plan'

    @api.model
    def render_html(self, docids, data=None):
        docs = self.env['ew.pta.line'].browse(docids)

        docargs = {
            "doc_ids": docs.ids,
            "doc_model": "ew.pta.line",
            "docs": docs,

        }
        return docargs

reports/print_work_plan_template.xml
<?xml version="1.0" ?>
<odoo>

    <template id="report_work_plan_template">
   <t t-call="web.html_container">
        <t t-foreach="docs" t-as="o">
            <t t-call="web.external_layout">

Report title

            </t>
        </t>
    </t>
</template>

</odoo>

reports/work_plan_report.xml
<?xml version="1.0" ?>
<odoo>
    <report
        id="action_work_plan_print_report"
        string="Print Report"
        model="ewonga_pta.report_model_work_plan"
        report_type="qweb-pdf"
        name="ewonga_pta.report_work_plan_template"
        file="print_work_plan_template"
    />

</odoo>

wizards/workplan.py
# -*- coding: utf-8 -*-
from odoo import models, fields, api

class WorkPlanWizard(models.TransientModel):
    _name = "ewonga_pta.work_plan_wizard"

#     attendee_ids = fields.Many2many('res.partner', string="Attendees")
    project_id = fields.Many2one("account.analytic.account", domain=[("type_interne", "=", "projet" )])
    start_date = fields.Date("Date de début")
    end_date = fields.Date("Date de fin")

    @api.multi
    def check_report(self):
        data = {}
        data["form"] = self.read(
            [
                "project_id",
                "start_date",
                "end_date"
            ]
        )[0]
        return self.env.ref("ewonga_pta.action_work_plan_print_report").report_action(self, data=data)

wizards/wizard_work_plan.xml
<?xml version="1.0" encoding="utf-8"?>
<odoo>

        <record id="action_work_plan_wizard_action" model="ir.actions.act_window">
    <field name="name">Generate Workplan Report</field>
    <field name="res_model">ewonga_pta.work_plan_wizard</field>
    <field name="type">ir.actions.act_window</field>
    <field name="view_type">form</field>
    <field name="view_mode">form</field>
    <field name="view_id" ref="work_plan_wizard_form_view"/>
    <field name="target">new</field>
</record>

    <record model="ir.ui.view" id="work_plan_wizard_form_view">
            <field name="name">work_plan_wizard.form</field>
            <field name="model">ewonga_pta.work_plan_wizard</field>
            <field name="arch" type="xml">
                <form string="Add Attendees">
                    <group col="4" colspan="4">
                        <field name="project_id"/>
                        <field name="start_date"/>
                        <field name="end_date"/>
                    </group>

                    <group col="4" colspan="4">

                  <button name="check_report" string="Imprimer" type="object" default_focus="1" class="oe_highlight"/>
                  or
                  <button string="Annuler" class="oe_link" special="cancel"/>

                    </group>
                </form>

            </field>
        </record>

</odoo>

os: Window 10 x64
python: version 3.6.5
wkhtmltopdf: version 0.12.3.2 (with patched qt)
please help me to solve this issues. Thanks

A: Try to remove your "data" parameters pass thru "report_action" call. Self already contain datas.
Thanks


text:
Q: Underscore: Wrap array with collection methods I have an array full of objects:
var myArray = [{ "user": "anton" }, { "user": "joe" }];

I would now like to wrap the array into a Underscore Collection object so that I can nativly use underscore's collection methods (remove, add) with it:
myArray = _(myArray); // this only add object methods
myArray.add({ "user": "paul" });

So how do I wrap an array with underscore to use underscores collection methods

A: For the record since the accepted answer is missleading:
Underscore used as a function, will wrap its argument, i.e.
_([a, b, c])

is equivalent to:
_.chain([a, b, c])

In fact chain is defined as:
_.chain = function(obj) {
  return _(obj).chain();
};

Now to your question:
You confuse Backbone which provides Collections, with Underscore which does not. Backbone collections can be easily initialized from an array, for example:
var c = new Backbone.Collection([{ "user": "anton" }, { "user": "joe" }]);

will work just fine. You can further do:
c.add({ "user": "paul" });

A: Generally underscore api doesn't wrap array or object. just passing it first argument.
ex)
_.first([5, 4, 3, 2, 1]); //Note first argument
=> 5
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

But chain (_.chain(obj)) Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used.
var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

check underscore api : http://underscorejs.org/#


text:
Q: i want to capture the output of every output from the terminal to a text file but it either over writes the ole output or only saves the last one so im runnung a semi-local chat gpt but with extra customization and i want to save all the chats to a text file. it only overwrites the old message with the new one instead of putting them on new lines as they come. is there a way to record all of the terminal input and outputs to a text file? the script doesnt end till i manually stop it it just loops back to the beginning after each response.
oh and its python im really new to this lol.
from contextlib import redirect_stdout
import sys
import openai,pyautogui
import tkinter as tk
from tkinter import simpledialog
import datetime
from datetime import datetime

# Set the API key
openai.api_key = "THATS MY PRIVATE API KEY"

# Choose a model
MODEL_ENGINE = "text-davinci-002"

def get_response(prompt):
    """Returns the response for the given prompt using the OpenAI API."""
    completions = openai.Completion.create(
             engine = MODEL_ENGINE,
             prompt = prompt,
         max_tokens = 1024,
        temperature = 0.7,
    )
    return completions.choices[0].text

def handle_input(
               input_str : str,
    conversation_history : str,
                USERNAME : str,
                 AI_NAME : str,
                 ):
    """Updates the conversation history and generates a response using GPT-3."""
    # Update the conversation history
    conversation_history += f"{USERNAME}: {input_str}\n"

    # Generate a response using GPT-3
    message = get_response(conversation_history)

    # Update the conversation history
    conversation_history += f"{AI_NAME}: {message}\n"

    # Print the response
    print(f'{AI_NAME}: {message}')
    pyautogui.alert('You Said: ' + USER_INP + '''

    ''' + f'{AI_NAME}: {message}')
    now = datetime.now()
    dt_string2 = now.strftime("%d/%m/%Y %H:%M:%S")

    return conversation_history

# Set the initial prompt to include a personality and habits
ROOT = tk.Tk()
ROOT.withdraw()
# the input dialog and prompt
#use "USER_INP" as the tag

USER_INP_USERNAME = simpledialog.askstring(title="MattGPT ~ Local",
                                  prompt="What is your name?",
                                  initialvalue="Matt")
ROOT = tk.Tk()
ROOT.withdraw()
# the input dialog and prompt
#use "USER_INP" as the tag

USER_INP_NAME = simpledialog.askstring(title="MattGPT ~ Local",
                                  prompt="Would you like to change the AI Name?",
                                  initialvalue="MattGPT")
ROOT = tk.Tk()
ROOT.withdraw()
# the input dialog and prompt
#use "USER_INP" as the tag

USER_INP_PERSONALITY = simpledialog.askstring(title="MattGPT ~ Local",
                                  prompt="Would you like to change the AI personality?",
                                  initialvalue='''private stuff ;)''')

INITIAL_PROMPT = (USER_INP_PERSONALITY)
conversation_history = INITIAL_PROMPT + "\n"

print('Current Prompt: ' + INITIAL_PROMPT)

USERNAME = USER_INP_USERNAME
AI_NAME = USER_INP_NAME

while True:
    # Get the user's input
    ROOT = tk.Tk()
    ROOT.withdraw()
# the input dialog and prompt
#use "USER_INP" as the tag

    USER_INP = simpledialog.askstring(title="MattGPT ~ Local",
                                  prompt="What would you like to say?")
    user_input = USER_INP

    if(user_input=="None"):
            pyautogui.hotkey('command', 'q')
    else:
    # Handle the input
        print(USER_INP_USERNAME + ': ' + user_input)
        handle_input(user_input, conversation_history, USERNAME, AI_NAME)
        now = datetime.now()
        dt_string1 = now.strftime("%d/%m/%Y %H:%M:%S")

        class Logger(object):
            def __init__(self):
                self.terminal = sys.stdout
                self.log = open("/Users/matthew/Desktop/MattGPT_Log", "a")

            def write(self, message):
                self.terminal.write(message)
                self.log.write(message)

            def flush(self):
            #this flush method is needed for python 3 compatibility.
            #this handles the flush command by doing nothing.
            #you might want to specify some extra behavior here.
                pass

        sys.stdout = Logger()

#        f = open("/Users/matthew/Desktop/MattGPT_Log", 'w')
#        sys.stdout = f


text:
Q: Is there an implementation of mixed analog (SPICE) and digital (HDL) simulations? I wonder how it could be possible to do mixed circuits simulations. In my imagination, there is a circuit netlist which contains analog and digital components. Since XSPICE (and I think ngspice) has the possibility to implement digital circuits why shouldn't it be possible to define these digital circuits using a HDL such as Verilog or VHDL? There is even a paper showing how to combine HDL and SPICE simulations [10.1109/ICCD.2001.955043].
During my research I found there are some open source tools which claim to have these properties.
Here are a few:

*

*eSIM which uses the GHDL tool

*QUCS
When it comes the mixed circuit simulations none of the provide the promised experience. In both cases, I am not able to implement a simulation of a VHDL written digital component in combination with an analog SPICE circuit.

*

*Has anyone managed to implement such a simulation in any of the mentioned or maybe different open source tools?

*Is there a paid proprietary tool which is able to implement this kind of simulations?

*Am I looking completely in the wrong direction and this is not the best way to perform mixed analog and digital simulations?

A: To mix two simulation paradigm (SPICE, VHDL) you need a package that supports both. These however are few and far between.  SIMextrix is a SPICE simulator but can also accept Verilog HDL.
One option is CO-Simulation permitting one simulation domain to communicate with another. Matlab for instance can simulate some SPICE parts and can co-simulate with MODELSIM.
Finally, there is VHDL-AMS, the analogue extension to VHDL. You however do need to write the SPICE model equations in VHDL-AMS.
https://en.wikipedia.org/wiki/VHDL-AMS
library IEEE;
use IEEE.math_real.all;
use IEEE.electrical_systems.all;

-- this is the entity
entity DIODE is
   generic (iss : current := 1.0e-14;
            af  : real    := 1.0;
            kf  : real    := 0.0);
   port (terminal anode, cathode : electrical);
end entity DIODE;

architecture IDEAL of DIODE is
  quantity v across i through anode to cathode;
  constant vt : voltage := 0.0258;
begin

  i == iss * (exp(v/vt) - 1.0);

end architecture IDEAL;

A: After a while of searching I found this post on GitHub describing the issue verry well:
https://github.com/ghdl/ghdl/issues/1052
Here some ways are shown how to combine gHDL and different Spice tools.
My research on advanced, payed tools showed tat cadence would be most used tool for such mixed simulations.


text:
Q: Angular route redirects to /# and thus refreshes the page I have an angular application that uses the below router.
/abc/efg

But whenever i click on any of the routers in the html it all gets redirected to the below format.
/#

and thus refreshes the page. This is affecting all of the routers in the app. The routers are properly defined in the routing module. Can someone help me to resolve these.

A: I think you have some href="#" defined in your anchors, replace them with routerLink and the routes you defined in your router module


text:
Q: EF optional one to many multiplicity error I have a very simple schema, simplified further for this question
Table: Airport
IATA char(3) Primary Key
Name varchar(20)

Table: Airport_Terminal
IATA char(3) (comp key1)
TerminalName (comp key2)

POCOs
public sealed class Airport
{
    [Key]
    public string IATA { get; set; }

    public string Name { get; set; }

    public ICollection<AirportTerminal> Terminals { get; set; }
}

    public class AirportTerminal
{
    [Key, Column(Order = 0)]
    public string IATA { get; set; }

    [Key, Column(Order = 1)]
    public string Terminal { get; set; }

    public Airport Airport { get; set; }

}

AirportTerminal Configuration
modelBuilder.Entity<AirportTerminal>()
    .HasOptional<Airport>(s => s.Airport)
    .WithMany(s => s.Terminals)
    .HasForeignKey(s => s.IATA);

Some airports (in my application) have multiple terminals and some do not. I simply want to react to Terminals property when there are Terminals defined for a given airport. If I enter a single record for every airport, this configuration works. But when I attempt to lookup any airport, I get:
 "One or more validation errors were detected during model generation: Multiplicity conflicts with the referential constraint in Role 'AirportTerminal_Airport_Target' in relationship 'AirportTerminal_Airport'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'."

Research shows that this error occurs when a non-nullable property exists on the optional member, so it cannot be set to null. AirportTerminal contains two strings, nullable.
Any ideas?

A: Consider using only key to the tables. This is best instead of multiple key. Place index constraint to ensure uniqueness in the properties  IATA and Terminal.
POCOs:
public sealed class Airport
{
    [Key]
    public Guid Id { get; set; }

    public string IATA { get; set; }

    public string Name { get; set; }

    public ICollection<AirportTerminal> Terminals { get; set; }
}

public class AirportTerminal
{
    [Key]
    public Guid Id { get; set; }

    public string IATA { get; set; }

    public string Terminal { get; set; }

    public Airport Airport { get; set; }

    public Guid? AirportId { get; set; }
}

Configuration:
modelBuilder.Entity<AirportTerminal>()
    .HasOptional<Airport>(s => s.Airport)
    .WithMany(s => s.Terminals)
    .HasForeignKey(s => s.AirportId);


text:
Q: Adding dynamically text in JavaScript Javascript:
function changeIt()
{
    var i = 1;
    var j = 1;
    my_div.innerHTML = "

<input type='text' name='mytext' + i  value='pleaseEnter malzeme' >   <input type='text' name='mytet2'+j value='please quantity'> "
}

HTML:
<input type="button" value="Add Ingredients" onClick="changeIt()" />

I have these code piece to add textbox dynamically in my HTML file. Problem is that I cannot reach text.
System.out.print(request.getParameter("mytext1")); //doesnt work to reach mytext1 value.

How can I solve this problem? Thanks in advance.

A: Try changing your innerHTML to this:
my_div.innerHTML ="

<input type='text' name='mytext" + i + "' value='pleaseEnter malzeme' >   <input type='text' name='mytet2" +j + "' value='please quantity'> "

A: Okay, first to get a reference of an element in JavaScript you need to call document.getElementById("my_div"). There is no such thing as automatic global scope population with IDs in JS.
Then your HTML string contains variables which are written as part of the string. Concatenation in JS works with the plus sign (+). So your string should be:
"

<input type='text' name='mytext" + i + "' value='pleaseEnter malzeme'><input type='text' name='mytet2" + j + "' value='please quantity'>"

Everything assembled together:

<input type="button"  value="Add Ingredients" onClick="changeIt()">

Regarding the print I have no idea what you're actually trying there...


text:
Q: glm poisson regression warnings and error I was fitting a linear mixed effects model when I realised that my outcome variable CORRECTNESS is actually the proportion of correct responses, and so is bounded between 0 and 1, and there is I suppose a finite number of possible values it can take in my data.
It was therefore suggested to me  that I use a generalized linear model with a poisson distribution. When I tried to re-run my null model with a poisson distribution I get two warnings and an error message.
My data looks like this (CORRECTNESS is a numeric variable, and ID is a factor):

CORRECTNESS <- c(0.625, 0.375, 0.5, 1,1,0.875)
ID <- c('p01', 'p02','p03', 'p04', 'p05', 'p06')
guesses <- as.data.frame(cbind(CORRECTNESS,ID))

mdl_null <- glm(CORRECTNESS ~ (1|ID), data = guesses , family = 'poisson')

The warnings:
Warning message in Ops.factor(1, ID):
"'|' not meaningful for factors"Warning message in glm.fit(x = structure(numeric(0), .Dim = c(0L, 2L), .Dimnames = list(:
"no observations informative at iteration 1"

Warning message:
    "glm.fit: algorithm did not converge"

The error message is either:
Error in glm.fit(x = structure(numeric(0), .Dim = c(0L, 2L), .Dimnames = list(: object 'fit' not found

or:
Error in model.matrix.default(mt, mf, contrasts): variable 1 has no levels

Can someone help me understand? How can I run this model?
Thank you.


text:
Q: Checking to see if a RethinkDB shard is in use? I am wondering if there is a way to check to see if a RethinkDB shard is in use before performing so ReQL query on it.
I am currently calling two functions back to back, the first creating a RethinkDB table and inserting data, the second will read the data from that newly created table. This works okay if the data being inserted is minimal, but once the size of the data set being inserted increases, I start getting:
Unhandled rejection RqlRuntimeError: Cannot perform write: Primary replica for shard ["", +inf) not available

This is because the primary shard is still doing the write from the previous function. I guess I am wondering if there is some RethinkDB specific way of avoiding this or if I need to emit/listen for events or something?

A: You can probably use the wait command for this. From the docs:

Wait for a table or all the tables in a database to be ready. A table
  may be temporarily unavailable after creation, rebalancing or
  reconfiguring. The wait command blocks until the given table (or
  database) is fully up to date.

http://rethinkdb.com/api/javascript/wait/


text:
Q: Javascript in HTML and ASP file Since JavaScript can be written (or contained) within an HTML file or in an ASP file, is there any difference?

A: ASP runs on the server-side. Any HTML or JavaScript generated by this is simply sent to the browser, which is where the HTML is rendered and JavaScript is executed.

A: ASP is a server side technology that (usually) outputs an HTML document when executed.
Any JavaScript you write might be part of the HTML document (and thus identical to any JS you might put in a static HTML document) or it might be written as server side code (in which case it will execute on the server, have access to ASP APIs instead of Browser APIs, and will generate output instead of being output).

A: The marvellous thing about Javascript and server-side programming languages like ASP and PHP is that they can be (sort of) intertwined. So, for example, if you have a server-side variable that you want to be able to mess about with using Javascript, you can include it in the JS when you output the page:
// THIS IS THE ASP CODE
string mystring = "This is my ASP string";
string html = "<script type=\"text/javascript\">var mystring = "+mystring+"</script>";
// then output the html

That's a terrible, badly-coded example, but you hopefully get the idea. You can emit Javascript to the page using ASP variables and the like. It's very handy.

A: One difference I can think of is, the way you bind HTML/ASP controls
--HTML button control--
<input type = "button" id = "myButtonHTML" />

--ASP button control--
<asp:button runat = "server" id = "myButtonASP" />

the way you bind this in javascript will be as follows
--HTML control--
document.getElementById("#myButtonHTML").value

AND

--ASP control--
document.getElementById("#myButtonASP.ClientID").value


text:
Q: Capture packets on Asus router I have Asus RT-AC87U router in my home network. I would like to analyse packets on specific ports like Wireshark does. Is it possible to build such system that could make traffic going trough router analysis? How?

A: First things first, you need to enable ssh access on your router. Someone asked a question regarding this here
Once you have your ssh setup done, you can connect to your user via SSH using a Linux VM or Putty or any other tool that supports ssh. You can then use the tcpdump utility to scan packets. Example of tcpdump commands :
Scan on all interfaces (-i any) any traffic that has source or desto as 123.123.123.123
tcpdump -i any host 123.123.123.123

Scan on interface eth0 for any traffic going through port 443
tcpdump -i eth0 port 443

Let me know if you need help with the tcpdump utility.

A: If you use stock firmware, you first need to setup Entware following this guide:
https://github.com/Entware/Entware/wiki/Install-on-Asus-stock-firmware
And then you can install tcpdump with:
opkg install tcpdump


text:
Q: Is there any way to cancel background noise from being recorded into my microphone? Globally? On Windows I used to take advantage of acoustic echo cancellation and noise suppression but no such features exist in PulseAudio and haven't since I can remember. My system is a laptop, Acer Aspire V3-571G and you can guess it ran Realtek drivers as usual.
Ubuntu 13.04, 13.10, 12.10, I don't mind which version a fix applies too, as long as it's one of those three.

A: Echo cancellation in Ubuntu can be done by running:
pactl load-module module-echo-cancel


text:
Q: How can I increase the Match Rate on Admob? My Admob Ad Requests have gone up about 30% this year for Vidalingua dictionary apps.
However, during the same time, the Match Rate has gone down from above 97% to below 89%.
Is there anything I can do as a developer to increase the Match Rate?


text:
Q: Clarification on functionality of Typescript's target and lib settings When tsconfig.json has the following
"target": "es5",
"lib": [ "es6", "dom", "es2017" ]

it doesn't seem to convert es2017 constructs to es5.  For instance, the following will fail on IE11:
var foo = [1, 2, 3].includes(1);

Is this by design or am I missing a setting in tsconfig.json?

A:
Clarification on functionality of Typescript's target and lib settings

The simplified way I think about it is that target says what syntax the output JavaScript will have, and lib says what API members your TypeScript source code can use. There is more detail in the answers to these two questions:

*

*Typescript- What is target in tsconfig?

*What does the tsconfig option "lib" do?

...it doesn't seem to convert es2017 constructs to es5... Is this by design or am I missing a setting in tsconfig.json?

You're right. This is by design. TypeScript transpiles to the target syntax; it does not polyfill the API members that are missing from the target. Here is a quote from a core member of the TypeScript team:

I think you're confusing transpilation with auto-polyfilling. TypeScript doesn't automatically polyfill for you like Babel does, but does perform syntactic downleveling (e.g. for arrow functions). If you want to use ES6 runtime prototype methods, I'd simply include an appropriate ES6 polyfill and its accompanying definition file.

If your lib includes API members (such as Array.prototype.include) that aren't present in the target runtime, then you need to install polyfills that provide those API members.

A: You can see list Browser compatibility for includes method here.

In this, it did not support IE.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes


text:
Q: set-car! and let in scheme language I am little bit confused by the result of this example:
(define mk-q
  (lambda ()
    (let ([l '(x)])
      (cons l l))))

(define q (mk-q))

q
=> ((x) x)

(set-car! (cdr q) 'y)
=> ((y) y)

I am wondering why both x atoms have been replaced by set-car! procedure (my first guess for what the result would be was ((x) y))?
For example:
(define mk-q2
  (lambda ()
    (let ([l '(x)])
      (cons l (cons l l)))))

(define q2 (mk-q2))
(set-car! (cdr q2) 'y)
=> ((x) y x) which fits my understanding of set-car!

Why are both xs in the first example replaced?

A: In the first example, you have something equivalent to this:
(define cell (cons 'x null))
(define q (cons cell cell))

As you can see, there's only one cons cell with x at the car position, that is being shared in two different parts of the resulting list structure. When you execute (set-car! (cdr q) 'y) the x in the single cell gets replaced by y in all the parts where it's being shared. Remembering that both (cons 'x null) cells are really the same, we're going from this:
(cons (cons 'x null) (cons 'x null))
; '((x) x)

to this:
(cons (cons 'y null) (cons 'y null))
; '((y) y)

For the second example the same considerations apply (all three (cons 'x null) cells are actually the same one being shared), but you're replacing a whole cons cell, so basically we're going from this:
(cons (cons 'x null) (cons (cons 'x null) (cons 'x null)))
; '((x) (x) x)

to this:
(cons (cons 'x null) (cons 'y (cons 'x null)))
; '((x) y x)

To prove my point that both of the examples in the question demonstrate the same situation, execute this expressions:
(define q2 (mk-q2))
(set-car! (cadr q2) 'y) ; notice the extra `a`
q2
=> '((y) (y) y)


text:
Q: Finding the frequency of object key VALUES in an array of objects I have an array of objects (police data, each one is a crime). The array of objects is 1000 in length.
Every object has a key/value such as community_area: 22.
I am trying to iterate over the array of objects to find the top three community areas that exist in the array. So if community areas 22, 70 and 1 had the most crime (each object occurrence) it would return those three.
What is an efficient way of doing this other than creating arrays of the 77 different community areas with the crimes then comparing the length?

A: Pattern for this sort of thing is fairly simple.
Create an object , iterate the array and use the common property of data objects as keys in new object and values will be incremental counts.
Then iterate the new object and compare those counts

var data = [
 {community_area:22},
 {community_area:22},
 {community_area:9},
 {community_area:9},
 {community_area:9},
 {community_area:5},
 {community_area:5},
 {community_area:5},
 {community_area:5},
 {community_area:1},
 {community_area:2},
 {community_area:3},

];

var countObj = data.reduce((a,c)=>{
   a[c.community_area] =  (a[c.community_area] || 0 ) + 1;
   return a
},{});

console.log('Community counts', countObj)

var top3 = Object.keys(countObj)
                  .sort((a,b) => countObj[b] - countObj[a] )
                  .slice(0,3)
                  .map(Number);//optional if need number vs string

console.log('Top 3', top3)

A: I came up with this code - it works.  Looks very similar to the other answer.

var testData = [{
  area: 22
}, {
  area: 23
}, {
  area: 17
}, {
  area: 12
}, {
  area: 45
}, {
  area: 12
}, {
  area: 17
}, {
  area: 23
}, {
  area: 34
}, {
  area: 22
}, {
  area: 12
}, {
  area: 45
}, {
  area: 45
}, {
  area: 45
}];

var result = testData.reduce((acc, obj) => {
  if (acc.hasOwnProperty(obj.area)) {
    acc[obj.area]++;
  } else {
    acc[obj.area] = 1;
  };
  return acc;
}, {});

var resultArr = [];
for ( var key in result ) { resultArr.push([key, result[key]]) }

resultArr.sort( (a, b) => b[1] - a[1] );
// now output the first 3 items
for ( var i = 0; i < resultArr.length && i < 3; i++) {
    console.log( `area: ${resultArr[i][0]} =  count ${resultArr[i][1]}`);
    }


text:
Q: Why doesn't Java's JIT compiler translate everything to native code? I have been looking into the Java JIT compiler and i cannot figure out why some of the code is still interpreted. Why doesn't the JIT compiler translate everything to native code? Interpretation is much slower, am I missing something?

A: It's all a matter of tradeoffs

*

*the time taken to compile + execute code can be longer than the time to interpret once

*you can often optimise things much more efficiently if you have statistics on branching, etc

*some things can't be compiled (anything that does RTTI, probably)

*some things you don't want compiled (line numbers for stack traces, etc)

*I'm sure there's others.

A: If you are running a JVM like HotSpot, it JIT-compiles opportunistically, only focusing on code that executes frequently. It determines which code to optimise on the fly by counting frequency of each code block (or method — I'm not sure which). Consequently, at startup time, everything is interpreted.
The intent behind this is allow for much more aggressive and expensive optimisations by only requiring a small fraction of the code to be optimised.

A: Two main reasons:

*

*Interpretation is not slower if code is only run a few times. The cost of compilation alone can be much more expensive than interpreting the code if it is only run a few times.

*While interpreting it is possible to gather statistics at runtime that are useful for optimising the code later. For example, you can count how many times a particular branch is taken and optimise the code to be faster for the more frequent case. This kind of trick can make JIT compilation better than ahead-of-time compilation (which doesn't have the opportunity to exploit the runtime statistics)

Hence the Java JIT takes a sensible strategy: don't compile until you observe that the same code is being run multiple times, at which point you have evidence that doing the compilation is probably worthwhile and you are able to make some additional optimisations.


text:
Q: Image Isn't Properly Sizing in GridBagLayout I am attempting to resize an ImageIcon and use it in my GridBagLayout JPanel. It does resize... but it still also displays at full size. So you have a resized image inside of the larger image. Anyone see anything glaringly wrong with the code below? Thank you!
public CharacterPage(WikiDB db) throws IOException {
    super("Character Page");

    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    setSize(new Dimension(1000,1000));

    rootPanel.setLayout(new GridBagLayout());
    final GridBagConstraints c = new GridBagConstraints();
    rootPanel.setSize(new Dimension(500,500));

   searchButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            BufferedImage img1 = null;

                for (int x = 0; x < characterImages.size(); x++){
                    String imageURL = "http://cosplayidol.otakuhouse.com/wp-
                           content/uploads/2012/06/s-1-1.jpg"

                    try
                    {
                        URL url1 = new URL(imageURL);

                        URLConnection conn1 = url1.openConnection();
                        conn1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
                        InputStream in1 = conn1.getInputStream();

                        img1 = ImageIO.read(in1);
                    } catch (IOException ioe)
                    {
                        ioe.printStackTrace();
                    }

                }

                Graphics2D g2 = img1.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(img1, 0,0,100, 100, null);
                g2.dispose();

                ImageIcon newIcon = new ImageIcon(img1);

                c.fill = GridBagConstraints.HORIZONTAL;

                JLabel cIcon = new JLabel(newIcon);
                c.gridx = 0;
                c.gridy = 6;
                rootPanel.add(cIcon,c);
               }
          });

       setContentPane(rootPanel);
    pack();
    setVisible(true);
      }

A: Graphics2D g2 = img1.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img1, 0, 0, 100, 100, null);
g2.dispose();

Should be something like:
int w = 100;
int h = 100;
// create an image of the appropriate size!
BufferedImage img2 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img2.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img1, 0, 0, w, h, null);
g2.dispose();

A: These lines draw the resized image back over the original:
Graphics2D g2 = img1.createGraphics();
g2.drawImage(img1, 0,0,100, 100, null);

Drawing onto a graphics created from the rootPanel itself.


text:
Q: Vanilla JS equivalent of jQuery's slice method How can I implement jQuery's slice method in Vanilla JS? The slice method selects a subset of the DOM elements.

A: Use querySelectorAll, then convert it into an array (you can use slice or spreading) then call slice on the resulting array to select the items you want:

const elements = Array.prototype.slice.call(document.querySelectorAll(".select"));
console.log(elements.slice(1));

1

2

3

4

5

You can also use the below equivalents for the first line:
const elements = Array.from(document.querySelectorAll(".select"));
const elements = [...document.querySelectorAll(".select")];


text:
Q: Why doesn't windows explorer show my removable / USB drive even though the command prompt does? I'm running WinXP SP2. Around 50% of the time, when I slot in my USB drive. Windows explorer refuses to show the drive.

*

*If I click on the Safely remove hardware icon on the tray,
I can see a menu item for the drive - say drive G: (the light on the USB drive is also on)

*

*If I type in G: into the address bar of explorer,
it says 'Cannot find...'

*If I type in G: into a command prompt window,
it works and I can do a dir to see the list of directories on the drive.

To fix this, I've to remove-reinsert the pen-drive. But doing it every day is annoying. Also this happens only on this machine.. I use this drive on my home machine and it works flawlessly each time.
Can anyone suggest things that I could try ?
Thanks for reading...

A: You could use the Microsoft DevCon command-line utility to do some things.

*

*devcon rescan -- Rescans for new Plug and Play devices.

*

*More examples at MSDN

I referred the drivetools site at this answer.
You will probably find an answer to your problem in the notes on that page.

A: Firstly, do you have any network drives mapped to G:\ at any time? You can get all sorts of odd behavior by having a network drive and a USB device mapped to the same drive letter. This is why Windows assigns lower letters for removable drives, and higher ones for network drives.
That aside, here's what I would do.

*

*Backup your information and reformat the pen drive.

*Once the format has complete, use Disk Management to remove the drive's letter.

*Unplug the drive, then plug it back in.

*The drive should then be assigned a new letter, and all should be right with the world.

*If the drive isn't assigned a letter, use Disk Management to assign it a new one.

Other things to try:

*

*chkdsk /r on the affected drive. Most problems that could be fixed here would be fixed by formatting though.

*sfc /scannow - you may have a wonky USB driver file or file system driver. You'll need an XP CD.

A: Try refreshing the explorer window that's looking at the drives with F5 or CTRL-F5.

A: this is old but I had the same problem in W7.
The drive was visible in WE until I deleted all partitions and created one and formatted it NTFS.
WE did not show the drive although when I plugged it in it was acknowledged.
When I went to drive mgmt it was there alive and well.
the answer was simple - the drive did not have a drive letter assigned to it.
Without a drive letter it is unmounted and unmounted drives do not appear in WE.
Simple add a drive letter in the mgmt screen

A: (Just a few guesses)

*

*Try reinstalling your USB drivers for that port in device manager.

*Try using a different USB port on your computer.

*Grab another USB drive and test it on the same port to find out if it is the drive or your computer that is making the issue. (From reading your Q it sounds like the computer but you should never assume)

A: These are just things to try:
If it's always the same pendrive, try reformating it.
Also, see if there's anything you can do in the disk management utility (right-click My Computer > Manage > Disk Management.