text:
Q: Find string within JSON with Python I'm currently getting a very long JSON and I'm trying to pick out 2 pieces of information from it through Python 2.7.
The JSON looks roughly like this:
{
  'device': [
    {
      'serial': '00000000762c1d3c',
      'registered_id': '019'
    },
    {
      'serial': '000000003ad192f2',
      'registered_id': '045'
    },
    {
      'serial': '000000004c9898aa',
      'registered_id': '027'
    }
  ],
}

Within this JSON I'm looking for a specific serial that might match with one in the JSON. If it does, it should print out the registered_id as well.
I've tried using a simple script, even without the registered_id but I'm getting nowhere.:
if '00000000762c1d3c' not in data['device']:
        print 'not there'
else:
        print 'there'

Thanks for your suggestions!

A: first, your input isn't json. Json uses double quotes. But suppose you successfully loaded it with json, it's now a dictionary, called d.
Then you can scan all sub-dicts of d and test serial key against your value, stopping when found using any and a generator comprehension:
print(any(sd['serial']=='00000000762c1d3c' for sd in d['device']))

returns True if serial found False otherwise.

A: date['device'] contains a list of objects, so you should treat it as such and iterate over them:
for element in data['device']:
    if element['serial'] == '00000000762c1d3c':
        print 'there'
        print element['registered_id']
        break
else:
    print 'not there'

This is using the somehow lesser-known for-else construct: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

A: Maybe this will help you:
if [x for x in data['device'] if x.get('serial')=='00000000762c1d3c']:
  print "IN"
else:
  print "NOT"

Python: List Comprehensions can be used to construct lists in a very natural, easy way, like a mathematician is used to do.


text:
Q: Looping through objects Suppose you have this array with objects:
array
0 =>
object(User\Entity\User)[297]
  public 'id' => int 1
  private 'first_name' => string 'Peter' (length=5)
  private 'last_name' => string 'Johnson' (length=7)
  private 'initials' => string 'J.J.' (length=4)
  private 'email' => string 'test@gmail.com' (length=21)
 1 =>
object(User\Entity\User)[296]
  public 'id' => int 2
  private 'first_name' => string 'Edith' (length=8)
  private 'last_name' => string 'Peters' (length=7)
  private 'initials' => string 'R.J.' (length=4)
  private 'email' => string 'edit@gmail.com' (length=26)

Now i want to put them in a table. But since i want to make it universal i try to do it on an abstract way.
I have a $aColnames array in the function below in to be able to only show the get the values of the fields i want to see in the table.
This is the method i am trying to build:
private function generateTable()
{

    foreach($this->aData as $aData){
      $this->sTable.= '
';
      foreach($this->aColnames as $sColname){
          $this->sTable.= '';
/****What code goes here ****/
              $this->sTable.= '	';
      }
          $this->sTable.= '
';
        }
    }

The question is no how do i get the values from the objects? Do i need to instantiate the objects each time? Can anyone help me out please?

A: No, you do not need to instantiate the objects again. They are instantiated when you placed them in the array in the first place!
You will however need to either declare these variables public, so that they may be accessed, or have some sort of getter functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symfony2 form builder constraints don't work in collection of forms I want to embed a Collection of Forms. That works fine! But the problem is, that the validation of a non mapped field ist not working. The code:
UserType.php
class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('contactPersons', CollectionType::class, array(
                'entry_type' => ContactPersonCreateType::class,
                'allow_add' => true,
                'prototype' => true,
                'cascade_validation' => true,
        ))
        ...
    }

ContactPersonCreateType.php
class ContactPersonCreateType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('kind', 'text', array(
            'mapped' => false,
            'required' => true,
            'constraints' => array(
                new NotBlank(),
                new Length(array('min' => 3)),
            )
        ))
        ...
    }

I don't know why, but it will not be validated!
Can somebody help?


text:
Q: Can't create new entity with null string values I have a super annoying issue when I try to create a new CRMTItem entity in C# EF (using database first approach).
The code:
using (var db = new ADVWKSPEntities())
{
    foreach (var adv in advs)
    {
        var crmtItem = new CRMTItem()
        {
            Id = adv.PrimaryId,
            ProjectTitle = adv.ProjectTitle,
            // ProjectId = adv.id
            CreatedByUser = new Guid(adv.CreatedBy),
            Opportunity = new Guid(adv.Opportunity),
            BidNoBid = adv.Bnb,
            SPUrl = adv.SPUrl,
            BnbId = new Guid(adv.BnbId),
            Stage = adv.ProjectStage,
            Confidential = adv.Confidential,
            OpportunityStatus = adv.OpportunityStatus,
            OpportunityNumber = adv.OpportunityNumber,
            CRMTNumber = adv.CrmtNumber,
            ProjectNumber = adv.ProjectNumber,
            Sector = adv.Sector,
            Service = adv.Service,
            CreatedDate = adv.CreatedDate,
            Archive = adv.Archive,
            ProjectManager = adv.ProjectManager,
            WorkTeam = adv.WorkTeam,
            Custodian = adv.Custodian
        };

        db.CRMTItems.Add(crmtItem);
    }
    await db.SaveChangesAsync();
}

The database:

The values:
Archive             null                                    string
Bnb                 null                                    string
BnbId               null                                    string
Confidential        false                                   bool
CreatedBy           "e1ef8e25-1624-46f0-9336-1674f1cffaeb"  string
CreatedDate         {2/03/2018 4:15:59 AM}                  System.DateTime
CrmtNumber          "121659"                                string
Custodian           null                                    string
ModifiedBy          "e1ef8e25-1624-46f0-9336-1674f1cffaeb"  string
ModifiedDate        {2/03/2018 4:15:59 AM}                  System.DateTime
Opportunity         "be67b7e9-eb3f-e211-8d73-78e3b5108e61"  string
OpportunityNumber   ""                                      string
OpportunityStatus   ""                                      string
PrimaryId           1                                       int
ProjectManager      null                                    string
ProjectNumber       null                                    string
ProjectStage        "Opportunity"                           string
ProjectTitle        "Some project name"                     string
RecordId            0                                       int
SPUrl               null                                    string
Sector              "aef0a38b-29fe-e111-9f8b-78e3b51146cb"  string
Service             "Deliver"                               string
WorkTeam            null                                    string

The error:

Value cannot be null. Parameter name: g

StackTrace:
[ArgumentNullException: Value cannot be null.
Parameter name: g]
   System.Guid..ctor(String g) +12961864
   ADVWKSP.Controllers.<Index>d__0.MoveNext() in C:\Users\Bassie\source\repos\TFS\ADVWKSP\ADVWKSP\Controllers\HomeController.cs:22
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +152
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +126

It seems as though it doesn't want me to insert NULL values into string columns, even though those columns are nullable... Why is this happening?

A: The issue was because I was trying to convert a null string to Guid - the error message is just really unhelpful, and the reason why object initialisers cam actually end up wasting a lot of time...
after splitting the object creation out like this
crmtItem.Id = adv.PrimaryId;
crmtItem.ProjectTitle = adv.ProjectTitle;
crmtItem.CreatedByUser = (adv.CreatedBy == null) ? (Guid?)null : new Guid(adv.CreatedBy);
crmtItem.Opportunity = (adv.Opportunity == null) ? (Guid?)null : new Guid(adv.Opportunity);
crmtItem.BidNoBid = adv.Bnb;
crmtItem.SPUrl = adv.SPUrl;
crmtItem.BnbId = (adv.Bnb == null) ? (Guid?)null : new Guid(adv.BnbId);
crmtItem.Stage = adv.ProjectStage;
crmtItem.Confidential = adv.Confidential;
crmtItem.OpportunityStatus = adv.OpportunityStatus;
crmtItem.OpportunityNumber = adv.OpportunityNumber;
crmtItem.CRMTNumber = adv.CrmtNumber;
crmtItem.ProjectNumber = adv.ProjectNumber;
crmtItem.Sector = adv.Sector;
crmtItem.Service = adv.Service;
crmtItem.CreatedDate = adv.CreatedDate;
crmtItem.Archive = adv.Archive;
crmtItem.ProjectManager = adv.ProjectManager;
crmtItem.WorkTeam = adv.WorkTeam;
crmtItem.Custodian = adv.Custodian;

I could narrow it down to the Guids.
However, because C#/entity framework somehow can't handle ternary operators with Guid/null, I have to cast my null value to Guid? with
(Guid?)null

And it seems to work ..... for now


text:
Q: How can I use external article in my website? I would like to know if it is legal to use external article on my website?
I think that if I reference the author it should be OK, but I don't know where to find information about this.

A: See ezinearticles.com

A: By default you must always ask writer of the article.

A: Some articles are released under some license. In this case you should check details of that license.

A: In most cases you should be OK when you attribute the article to the original author, as most authors like to see their work being shared.
Usually, the author's website will contain copyright statements or license information, which inform you about what you can and cannot do with the content. These should provide you with sufficient information. If you're still in doubt, you can contact the author.
If you've published the article without letting them know (e.g. by automated trackbacks), then it's always a good idea to send the author an email, in which you notify him about the use of his article and your reasons to do so. Then the author has a chance to let you know whether he approves of his content being used by you.

A: By default, you are not allowed to reproduce any article without the author's explicit consent. Some authors put their articles in the public domain, others explicitly allow citing or even full reproduction under certain circumstances.
If in doubt, contact the author.


text:
Q: Maximum number of sides when cutting n sided polyhedron How can I calculate maximum number of sides that could be obtained by cutting n-sided polyhedron with a plane? For some reason, I was not able to find clear answer to this question online.
EDIT: I am particularly interested in convex case


text:
Q: Java best practice for outside access to inner private class fields I searched a lot for an answer to my question and found several options, would like to know what you this is best practice.
Use case:
So I have a singleton class AccontManager, that has an inner class which is relevant to only it, which is a User class.
public class AccontManager {

private static final AccountManger ourInstance = new AccountManger();
private User user;

public static AccountManger getInstance()
{
    return ourInstance;
}

private AccountManger(){}

public User getUser(){
    return this.user;
}

private class User{
    private String id;

    private User (String id){
        this.id = id;
    }
}
}

Now, the situation is that User fields have to access to outside package class, but the user class is unique only to this singleton class, hence the inner class has to be private.
Optimally, creating public getter methods in the inner class to get the user fields would be best, but since the inner class is private, that's not possible.
Possible practice:

*

*Practice: create respective getter methods in the outer AccountManager class for the User field.
Drawback: the user fields relate to the User, hence the outer class should not have getter methods to its fields.
Code example:
 public class AccountManger {

     private static final AccountManger ourInstance = new AccountManger();
     private User user;

     public static AccountManger getInstance()
     {
         return ourInstance;
     }

     private AccountManger(){}

     public User getUser(){
         return this.user;
     }

     public String getUserId() // <-- get User id
     {
         return user.id;
     }

     private class User{
         private String id;

         private User (String id){
             this.id = id;
      }
 }
 }

*Practice: Change the User modifier to public, but keep the constructor private, so it couldn't be instantiated.
Drawback: the inner User class will be visible as a member of the AccountManager singleton class, which it shouldn't be.
Code example:
 public class AccountManager {

     private static final AccountManger ourInstance = new AccountManager();
     private User user;

     public static AccountManager getInstance()
     {
         return ourInstance;
     }

     private AccountManger(){}

     public User getUser(){
         return this.user;
     }

     public String getUserId() // <-- get User id
     {
         return user.id;
     }

     private class User{
         private String id;

         private User (String id){
             this.id = id;
         }
     }
     }

*Practice:

*

*Create a public interface, for example, IUser

*Make inner class User implement that interface

*Add to the outer class, in this case AccountManager a getter method to the User instance

Drawback: An interface needs to be used in order to obtain the data from User.
Code example:
    public class AccountManager {

    private static final AccountManager ourInstance = new AccountManager();
    private User user;

    public interface IUser{
        String getName();
    }

    private AccountManager(){}

    public static AccountManager getInstance(){
        return ourInstance;
    }

    public User getUser(){
        return this.user;
    }

    private class User implements IUser{
        private String id;

        private User(String id){
            this.id = id;
        }

        @Override
        public String getName() { // <-- get user id
            return id;
        }
    }
    }

So what do you think?
Any one of the listed options?
Some other way?
Thank you for your input

A: I would say that the User class needs to be private, and that the AccountManager should implement the getters and setters to it's attributes.
You won't have to know what is a User, because the AccountManager will tell you what you can know. As a plus, you can obey the Law of Demeter, which is always good thing.
IMO, inner classes should be used as a way to make the code in the outer class cleaner, and they shouldn't be able to be used elsewhere.
But I guess making the constructor in User private is better than nothing.

A: I see three alternative approaches:

*

*Make the User class stand-alone and public (and give it an AccountManager field, if necessary). Then User becomes part of your public API - probably not what you want.

*In the AccountManager class, create getters and setters for the publicly-relevant User properties. That keeps the User entity an invisible component of the Account Manager. (Analogy: if you talk about your car's horse powers, you are hiding the fact that it's a property not of the car itself, but of its engine, and that's quite OK).

*If you want the notion of a user to become part of your API, but still want to keep your inner User class private, create an interface IUser with the publicly-relevant methods and have User implement IUser. Then you can expose a public IUser getUser() method in your AccountManager, and the outside world only sees the functionality declared in the interface.

A: Seeing as AccountManager (you misspelled "Manager" in your code example) is a singleton class, it won't really make an effective difference, but you said yourself that "the user class is unique only to this singleton class", so the purpose of the User class might be better represented if you make it static.
Anyway, in your original code example, you included a method public User getUser(). With the class User being private, I don't really see a point in doing that, because outside the class AccountManager, any reference to a User object will be useless, because you will never be able to access any of its members or declare a User variable to which to assign the thus obtained User reference to. The only possible use case I could envision would be if AccountManager declared a public (or any access modifier higher than that of User) method that accepts a User parameter. But even if that were the case, I would question whether such a design is really what you want.
So you might want to think over whether you really need the method public User getUser(), provided User stays private. Which already leads us to your original question. I think your first proposed solution is better. This, to me, seems exactly the reason why a superclass is allowed to access `private' members of a subclass. Quoted from this answer on stackoverflow:

The inner class is (for purposes of access control) considered to be part of the containing class. This means full access to all privates.

So if you think of User as being part of AccountManager, then you don't have to feel guilty about accessing its private fields from within AccountManager but from outside User, because apparently, the designers of Java would also think that way.
Finally, if you don't intend to change the field id during the existence of a User, you could make id final.


text:
Q: OleDB addressing XLS cell position I am trying to get familiar with OLEDB and I am trying to read a xlsx file with it. However, when I try to read only one cell, I can not address it correctly. In this example I am trying to simply print out first cell (A1) but I am getting B3 cell. What Am I missing?
CODE:
 private void button1_Click(object sender, EventArgs e)
    {
        string path =@"C:\Users\Martin\Desktop\CLUSTER\FILES\bla.xlsx";
        String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
        OleDbConnection xlConn = new OleDbConnection(connectionString);
        xlConn.Open();

        OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM [List1$]", xlConn);

        OleDbDataAdapter xlAdapter = new OleDbDataAdapter();
        xlAdapter.SelectCommand = selectCmd;
        DataSet xlDataset = new DataSet();
        xlAdapter.Fill(xlDataset, "XLData");

       string variable = xlDataset.Tables[0].Rows[1][1].ToString();

       MessageBox.Show(variable);
    }

Can anyone help me? In the next step I would like to read whole xls table with this, so I guess, that I have to set up the range, right? But without knowing how to address cells its difficult.


text:
Q: Google Cloud Datastore vs Cloud SQL I am building a mobile app with Google Cloud as back-end. It stores information about restaurants including their menu. I would need to search based on the menu items and geo location.
I am fairly confused about which Google Cloud solutions to use. Initially I have planned to use Google App Engine with Cloud Datastore for storing data, but later found out, it doesn't support geolocation search, and even if I use the App Engine search api, I won't get 'like' text search. About using cloud SQL, I am worried about its price. I am also thinking about using Google Compute Engine and installing required MongoDB or SQL in it and use some custom search libraries.
So my question is which of the below should be an feasible and economical solution for storing large amount of data and searching using text and geo-location

*

*GAE with Cloud Datastore

*GAE with Cloud SQL

*GCE with MongoDB or SQL installed

Any other feasible solutions are also welcome

A: Google has a page to give high-level guidance on what storage option to choose on GCP, called Choosing a storage option.
Specifically for Cloud Datastore:

Description: A scalable, fully-managed NoSQL document database for your web and mobile applications.
Good for:

*

*Semi-structured application data

*Hierarchical data

*Durable key-value

Common Workloads:

*

*User profiles

*Product catalogs

*Game state

Specifically for Cloud SQL:

Description: A fully-managed MySQL database service that is built on the strength and reliability of Google's infrastructure.
Good for:

*

*Web-frameworks

*Structured data

*OLTP workloads

Common Workloads:

*

*Websites, blogs, and content management systems (CMS)

*Business Intelligence (BI) applications

*ERP, CRM, and eCommerce applications

As you can see, your use case could border either option. Restaurants + Menus is very similar to product catalogs.
Cloud Datastore would require less ops work/thoughts on your side. For example, you don't need to think about what type of VM instance and memory size it should use. However, to do analytics on data rather than just serving the menus, you'd probably want to do daily dumps into BigQuery.
Cloud SQL will require a little more thought at the beginning, and at small sizes will be a little more expensive than Cloud Datastore. It does give you more flexibility on the analytics side in that it doesn't really need you to dump into BigQuery.
Running a different database on GCE is certainly an option if you want more control. The trade-off here will be in requiring much more active ops work on your behalf, such as installing, patching, tuning, etc.


text:
Q: How can I avoid: identifier "L__FUNCTION__" is undefined I've got a log macro that looks something like this:
#define LOG(formatString, ...) \
{ Log( TEXT(__FUNCTION__) TEXT(" ") ## formatString TEXT("\r\n"), ##__VA_ARGS__);  }

It compiles and works fine, however it seems to trip up visual studio intellisense which underlines all uses of the macro in red with the error:
IntelliSense: identifier "L__FUNCTION__" is undefined

I'm thinking of raising this to microsoft, but in the meantime, is there a workaround that is as efficient at runtime which will not trip intellisense up?


text:
Q: Run length encoding of a list in scheme (R5RS) (Question Details image -- describes RLE encoding)
The (if ((equal? (car coins) (cadr coins))) piece of code in my rle function is not working, and the function stops working.
 (define (element-index  lst element)
  (let loop ((counter 1) (temp lst))
    (if (= element (car temp))
        counter
        (loop (+ counter 1) (cdr temp)))))

 (define (rle coins)
   (cond ((null? coins) '()))
      (if ((equal? (car coins) (cadr coins)))
          (rle (cdr coins))
           (append '( cons (element-index (coins) (car coins)) (car coins))
                   '( cons (rle (cdr coins))))))

A: I'm not going to answer how to solve the problem of run-length encoding something, but the basic syntax problem.
The summary of this is: in many programming languages, and often in mathematical notation, parentheses serve to control the order of operations, and are often more-or-less optional.  So for instance 1 + 2 * 3 probably means 'multiply 2 by 3 then add 1 to the result', while (1 + 2) * 3 means 'add 1 and 2 and then multiply the result by 3'.  But 1 + (2 * 3) means the same as 1 + 2 * 3 which means the same as (((1 + (2 * 3)))).
This is not the case in Scheme or Lisp-family languages, ever.  In these languages parentheses are part of the syntax of the language and they are never optional: they must either be there, or they must not be there.
So, in particular, a simplified version of the syntax of an expression in Scheme might be: an expression is either

*

*some atomic thing like a variable reference;

*a form like (op ...), where op is some operator.

In the second case the parentheses are not optional: they are part of the syntax of the language.  And in particular if you consider an expression like
((foo ...))

then this matches the second case, where op is now (foo ...) as a whole (and there are no arguments), and that in turn again matches the second case where op is foo.  So this is an expression, whose operator is another expression, and the operator of that expression is foo: it's not an expression wrapped in some optional parentheses, and in particular it is not the case that ((foo ...)) is the same as (foo ...).
So then, the syntax of if is: (if expression consequent alternate).  Well, let's look at your if:
(if ((equal? (car coins) (cadr coins)))
    ...
    ...)

So the expression here is ((equal? (car coins) (cadr coins))).  Well this matches the (op ...) case where op is (equal? (car coins) (cadr coins)), and this in turn matches that case, so it will evaluate this to return either #tor #f.  So the expression is the same thing as (#t) or (#f).  And #t or #f are Booleans: they're not things you can call as functions.
And that's at least one of the errors in your code.  There are others, but this seems to be the most important one, as it's also an error you've made in a comment to another answer.
In summary: parentheses are never optional in Scheme: they are either required or forbidden by the syntax of the language.

Another way of putting this is that, in a 'conventional Algol-style' language, parentheses usually serve two purposes:

*

*they serve as critical and mandatory parts of the syntax, usually for function arguments as f(x, ...), but sometimes also for other syntactic purposes as if (...) ... in C say;

*they serve to group expressions to control evaluation order where they are sometimes needed but often optional.

In Lisp-family languages only the former purpose exists.


text:
Q: I want to add my app is Deafult apps list I want to show my app in the default app  list . For example if my App is a music player , then i want to open all files with .mp3 with my app.
I mean that i want my app to be listed in the deafult apps list for that specic extenison .1I want my app to come in the list of deafult lists of app. Just like this1
Note ..
I am new

A: You need to declare in your AndroidManifest that your app can handle these types of files. You do this with an intent-filter:
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="content"/>
    <data android:scheme="file"/>
    <data android:mimeType="audio/*"/>
</intent-filter>

This means that any time an app launches an implicit Intent to play an audio file, your app will show up on the list of selectable apps.


text:
Q: git completion broken by bash profile alias 'test' I had an alias in my bash profile like this:
alias test='cd /Usr/work/dir/test'
every time I would try to use bash completion for git in a terminal it would:

*

*freeze the terminal immediately after hitting tab.

*take me to that directory.

As soon as I removed that alias bash completion for git works fine. Why's that?
git version 2.26.2
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19)
Copyright (C) 2007 Free Software Foundation, Inc.

A: test is a built-in command, and creating an alias named test shadows it, which could lead to unforeseen issues. Pick a different name.
alias goto_test='cd /Usr/work/dir/test'

However, this is probably the least desirable solution. First, consider using a function instead:
goto_test () {
    cd /Usr/work/dir/test
}

Second, you can add /Usr/work/dir to your CDPATH variable, so that you can quickly switch to any subdirectory without having to use the entire path.
$ CDPATH=/Usr/work/dir
$ cd test
/Usr/Work/dir
$ pwd
/Usr/Work/dir/test

This saves you from having to define multiple aliases or functions if there are several directories you might commonly switch to.


text:
Q: Установка идентификатора для List Проблема заключается не в самом идентификаторе, а в его установке, в качестве уникального (например, на первое свободное место).
Например я имею коллекцию:
List<list_item> list = new List<list_item>();
List.Add(new list_item(???));

Где в конструкторе, я устанавливаю значение идентификатора:
public list_item(int id)
{
    public int item_id = id;
    string some_data;
}

Предполагается, что коллекция имеет достаточно большое число динамично обновляющихся (убывающих, поступающих) элементов, поэтому постоянный инкремент одного идентификатора не подойдет, а ручной перебор коллекции при поступающем элементе займет критичное число вычислительных ресурсов. Желательно чтобы тип его был int.
Возможно задача заключается в выборе первого свободного идентификатора составив linq запрос к списку элементов list.
A: Возможно вам следует воспользоваться методом GetHashCode().
Можете его переопределить для вашего класса, а можете воспользоваться стандартным.
A: Имхо, лучший вариант смотреть на индекс в коллекции как на индефикатор или использовать мапу, так как прятать ид внутри элемента нечего не даст при его поиске, прийдется переберать все и смотреть в каждый...
A: Да, это отличный вариант. Возможно стоило бы выделить в качестве ответа. Только небольшое но: когда основная коллекция опустошается до минимума, коллекция идентификаторов вырастает в противоположном направлении и хранит макс. число некогда элементов. Но это, я думаю не проблема.
List<int> identifier_list = new List<int>();
private int GetIdentifire()
{
    lock (identifier_list)
    {
        int id = identifier_list.FirstOrDefault();
        if (id == 0) return list.Count;
        else identifier_list.Remove(id);
        return id;
    }
 }


text:
Q: Java - inheritance implementation Let's consider the simple interface:
interface Simple{
     void doSth();
}

ANd two classes that implement it:
class A implements Simple{

     void someOtherMethod(){ .... }

     void doSth(){ ... }

     private void doSth(int x){ ... }
}

class B implements Simple{

     void methodA(){ ..}
     // many other methods

     void doSth(){ ... }

     private void doSth(Object o, long y){ ... }
}

Now,I can easily write:
Simple s = new A();
s.doSth();

And the polymorphism nature of Java will do the rest. Does anyone know how e.g. Hotspot, makes sure that the Linker will link to the right method, considering there can be many more defined in the implementing classes, or even their return types can be a subclass of the original? Does Java make sure that the interface methods are always starting at some offset in the vtable, e.g. at 0?

A: Before we investgate this, let's simplify the example:
interface Foo {
    void bar();
}

class AFoo implements Foo {
    int i;

    @Override
    public void bar() {
        i++;
    }
}

class AnotherFoo implements Foo {
    int i;

    @Override
    public void bar() {
        i--;
    }
}

public class Test {
    public static void main(String[] args) {
        Foo foo = new AFoo();
        foo.bar();
    }
}

After compiling, we use

javap.exe -verbose Test.class

to inspect the generated byte code:
  public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=2, args_size=1
         0: new           #16                 // class tools/AFoo
         3: dup
         4: invokespecial #18                 // Method tools/AFoo."<init>":()V
         7: astore_1
         8: aload_1
         9: invokeinterface #19,  1           // InterfaceMethod tools/Foo.bar:()V
        14: return

At class load time, the code will be linked, which is specified by the Java Language Specification as follows:

The binary representation of a class or interface references other classes and interfaces and their fields, methods, and constructors symbolically, using the binary names (§13.1) of the other classes and interfaces (§13.1). For fields and methods, these symbolic references include the name of the class or interface type of which the field or method is a member, as well as the name of the field or method itself, together with appropriate type information.
Before a symbolic reference can be used it must undergo resolution, wherein a symbolic reference is checked to be correct and, typically, replaced with a direct reference that can be more efficiently processed if the reference is used repeatedly.

Note that this "direct reference" refers to the declaration of the method. In case there are several implementations, the runtime can not, at this time, know which method will be used. That is, polymorphism is not resolved during what the Java Language Specification calls linking, but when the actual method invocation expression is executed. This is specified by the Java Virtual Machine Specification:

Let C be the class of objectref. The actual method to be invoked is selected by the following lookup procedure:

*

*If C contains a declaration for an instance method with the same name and descriptor as the resolved method, then this is the method to be invoked, and the lookup procedure terminates.

*Otherwise, if C has a superclass, this same lookup procedure is performed recursively using the direct superclass of C; the method to be invoked is the result of the recursive invocation of this lookup procedure.

*Otherwise, an AbstractMethodError is raised.

It is up to the implementation of the JVM how to actually implement this. For the Oracle Hotspot JVM, the documentation contains a rather detailed explanation:

When an invokeinterface call is linked, the linker resolves the call to an abstract target method, in an interface. This boils down to a target interface and a so-called itable index within that interface.
Target interfaces are never statically guaranteed by the JVM verifier; every invokeinterface receiver is typed as a simple object reference. Therefore (unlike invokevirtual calls), no assumptions can be made about the receiver's vtable layout. Instead, the receiver's class (as represented by its _klass field) must be checked more carefully. Where a virtual call can blindly perform two or three indirections to reach the target method, an interface call must first inspect the receiver's class to determine (a) if that class actually implements the interface, and (b) if so, where that interface's methods are recorded within that particular class.
There is no simple prefixing scheme in which an interface's methods are displayed at fixed offsets within every class that implements that interface. Instead, in the general (non-monomorphic) case, an assembly-coded stub routine must fetch a list of implemented interfaces from the receiver's InstanceKlass, and walk that list seeking the current target interface.
Once that interface is found (within the receiver's InstanceKlass), things get a little easier, because the interface's methods are arranged in an itable, or "interface method table", a display of methods whose slot structure is the same for every class that implements the interface in question. Therefore, once the interface is found within the receiver's InstanceKlass, an associated offset directs the assembly stub to an itable embedded in the InstanceKlass (just after the vtable, as one might expect). At that point, invocation proceeds as with virtual method calls.
Nearly the same optimizations apply to interface calls as to virtual calls. As with virtual calls, most interface calls are monomorphic, and can therefore be rendered as direct calls with a cheap check.
Here is a generic instruction trace of a polymorphic interface call:

callSite:
    set #calledInterface, CHECK
    call #itableStub[itableSlot]
---
itableStub[itableSlot]:
    load (RCVR + #klass), KLASS_TEM
    load (KLASS_TEM + #vtableSize), TEM
    add  (KLASS_TEM + TEM), SCAN_TEM
tryAgain:
        # this part is repeated zero or more times, usually zero
    load (SCAN_TEM + #itableEntry.interface), TEM
    cmp TEM, CHECK
    jump,eq foundInterface
    test TEM
    jump,z noSuchInterface
    inc #sizeof(itableEntry), SCAN_TEM
    jump tryAgain
tryAgain:
    load (SCAN_TEM + #itableEntry.interface), TEM
    cmp TEM, CHECK
    jump,eq foundInterface
foundInterface:
    load (SCAN_TEM + #itableEntry.offset), TEM
    load (KLASS_TEM + TEM + #itableSlot), METHOD
    load (METHOD + #compiledEntry), TEM
    jump TEM
---
compiledEntry:
    ...

In all, that is six memory references and two nonlocal jumps.

Pedantic note: All of the above applies to invoking interface methods. Invoking a abstract method declared in a class uses a different bytecode instruction, and a slightly simpler implementation in the Oracle Hotspot JVM.

A: interface InterfaceA{void method();}
class ClassA implements InterfaceA{void method(){}}
void methodA(InterfaceA[]o){
    for(int i=0;i<o.length;++i)o[i].method();
}
void methodB(ClassA[]o){
    for(int i=0;i<o.length;++i)o[i].method();
}

so calling methodA is much more slower than calling methodB


text:
Q: Prove $ f(c)\int_{a}^{b}g(x)dx=\int_{a}^{b}g(x)f(x)dx$
Assume that $f:[a,b]\rightarrow\mathbb{R}$ is continuous on $[a,b]$ and $g:[a,b]\rightarrow\mathbb{R}$ is integrable and $g(x)\geq0$ for all $x\in[a,b]$. Then there exists a $c\in(a,b)$ such that $$ f(c)\int_{a}^{b}g(x)dx=\int_{a}^{b}g(x)f(x)dx$$

Suppose that $f:[a,b]\rightarrow\mathbb{R}$ is continuous on $[a,b]$ and $g:[a,b]\rightarrow\mathbb{R}$ is integrable on $[a,b]$. Since $[a,b]$ is a compact set, then by the extreme value theorem, there exist $x_1,x_2\in[a,b]$ such that $f(x_1)\leq f(x)\leq f(x_2)$. As $g(x)\geq 0$ for all $x\in[a,b]$, thus $g(x)f(x_1)\leq g(x)f(x)\leq g(x)f(x_2)$. Since $g$ is integrable on $[a,b]$, so $\int_{a}^{b}g(x)dx>0$; thus $$\int_{a}^{b}g(x)f(x_1)dx\leq\int_{a}^{b}g(x)f(x)dx\leq\int_{a}^{b} g(x)f(x_2)dx\Longrightarrow f(x_1)\leq\frac{\int_{a}^{b}f(x)g(x)dx}{\int_{a}^{b}g(x)dx}\leq f(x_2)$$ Now, apply the Intermediate Value Theorem for $f$, there exists a $c\in(a,b)$ satisfy $$f(c)=\frac{\int_{a}^{b}f(x)g(x)dx}{\int_{a}^{b}g(x)dx}\Longrightarrow f(c)\int_{a}^{b}g(x)dx=\int_{a}^{b}g(x)f(x)dx$$

Can someone give me a hint to write a different proof? Thanks

A: The proof contains a small gap, which can be fixed, I guess. You say that $g(x) \geq 0$ yet $\int\limits_{a}^{b} g(x) dx >0$. What happens if $g(x)$ is identically zero?


text:
Q: Difference between NUMBER & NUMBER(16) in oracle? In current database I have column with NUBMER(16) however due to transaction size ncreased to 17 char I am planning to make it NUMBER which supports 32 char numeric.
As size and performance wise I want to know how it would impact to database?

A: From the Oracle documentation,

Oracle Database stores numeric data in variable-length format. Each
  value is stored in scientific notation, with 1 byte used to store the
  exponent. The database uses up to 20 bytes to store the mantissa,
  which is the part of a floating-point number that contains its
  significant digits. Oracle Database does not store leading and
  trailing zeros.

Therefore, the storage would depend on the actual numeric value and not just the precision.

Precision is the number of significant digits.

To see the storage, use vsize and dump.
For example,
SQL> CREATE TABLE t (val NUMBER(16));

Table created.

SQL> INSERT INTO t VALUES (-12);

1 row created.

SQL> INSERT INTO t VALUES (1);

1 row created.

SQL> INSERT INTO t VALUES (12);

1 row created.

SQL> INSERT INTO t VALUES (1234);

1 row created.

SQL> INSERT INTO t VALUES (12345);

1 row created.

SQL> INSERT INTO t VALUES (123456789012345);

1 row created.

SQL> COMMIT;

Commit complete.

Let's check the size:
SQL> SELECT val, vsize(val), dump(val) FROM t ORDER BY val DESC;

             VAL       VSIZE(VAL) DUMP(VAL)
---------------- ---------------- --------------------------------------
 123456789012345                9 Typ=2 Len=9: 200,2,24,46,68,90,2,24,46
           12345                4 Typ=2 Len=4: 195,2,24,46
            1234                3 Typ=2 Len=3: 194,13,35
              12                2 Typ=2 Len=2: 193,13
               1                2 Typ=2 Len=2: 193,2
             -12                3 Typ=2 Len=3: 62,89,102

6 rows selected.


text:
Q: How to call controller method from view RAILS 4.0 I think I stated the title of this question right, but this is the issue:
I have the following in my SurveysController-
  def pull_responses
    call= "/api/v2/surveys/"
    auth = {:username => "test", :password => "password"}
    url = HTTParty.get("https://fluidsurveys.com#{call}",
                       :basic_auth => auth,
                       :headers => { 'ContentType' => 'application/json' } )
    response = JSON.parse(url.body)
    survey_ids = response["surveys"].map { |s| s["id"] }

    survey_ids.each do |x|

      call= "/api/v2/surveys/#{x}/responses/?_completed=1"
      auth = {:username => "test", :password => "password"}
      url = HTTParty.get("https://Fluidsurveys.com#{call}",
                         :basic_auth => auth,
                         :headers => { 'ContentType' => 'application/json' } )

      response = JSON.parse(url.body)
      response_count = response["count"]
      Survey.create(y: response_count)
    end
  end
  helper_method :pull_responses

All I am trying to do is put the variable response_count in my Surveys view. I may not need Survey.create(y: response_count), but that was a peice of one of my attempts to get this to work. Essentially, I just want to write this in a view:
puts response_count
What is the proper way to put that response into a view?

A: You need to assign the value to an instance variable (by adding @ before the name) so that it will persist to the view:
@response_count = response["count"]

then in the view you can print it like so:
<%= @response_count %>


text:
Q: Formatting text scraped with headless chrome crawler The code below scrapes text from multiple elements on the page, however the text needs formatting (adding spaces etc) so that I'm able to use it elsewhere.
I have some JavaScript (working in the browser console) that loops over the elements, adding their text to an array and then turning that into a string, which does what I want. Is that code that can be reused here? I'm not sure where/if I can add it?
const HCCrawler = require("headless-chrome-crawler");
const CSVExporter = require("headless-chrome-crawler/exporter/csv");

const FILE = "result.csv";

const exporter = new CSVExporter({
  file: FILE,
  fields: ["response.url", "response.status", "result.text"],
});

(async () => {
  const crawler = await HCCrawler.launch({
    maxDepth: 9999,
    exporter,
    allowedDomains: ["example.com"],
    // Function to be evaluated in browsers
    evaluatePage: () => ({
      text: $("h1, h2, p").text(),
    }),
    // Function to be called with evaluated results from browsers
    onSuccess: (result) => {
      console.log(result.result.h1);
    },
  });
  // Queue a request
  await crawler.queue("https://example.com");

  await crawler.onIdle(); // Resolved when no queue is left
  await crawler.close(); // Close the crawler
})();

A: yeah i think you could add a post-crawling step in the evaluatePage callback applying your code:
 function cleanCrawledText(text) {
   // clean text here and return it
 }

 ...
 evaluatePage: () => ({
   text: cleanCrawledText($("h1, h2, p").text()),
 }),
 ...


text:
Q: python regular expression(re) - how to extract this? import re
a = re.search('2(34)', '1234134').group()
print(a)

I expected this output:
34

but I got this:
234

how can I extract only 34 next to 2, not 34 next to 1?

A: you can use:
re.search('2(34)', '1234134').group(1)

output:
34

you can read more about grouping here


text:
Q: Is it right to say 'a marriage proposal to me from my beloved'? Is it right to say:

I was very excited when I heard a marriage proposal to me from my beloved ?

A: It is grammatically correct to say such a thing, but it is an awkward-sounding phrasing.
Some more "natural" alternatives would be:

*

*when I received a marriage proposal from my beloved

*when my beloved proposed to me

*when my beloved asked me to marry him

*when I was proposed to by my beloved


text:
Q: Find most favorite products from a large table on SQL server For SQL server, I have a table with
CostumerID  TITLE   DATE
1   m1  1999-05-08
1   m1  2000-07-10
1   m1  2001-12-11
1   m2  2008-03-20
1   m2  2005-09-05
1   m2  2011-07-08
1   m3  2006-07-22
1   m3  2009-01-19
1   m3  2012-02-18
2   m1  2007-09-28
2   m1  2010-11-19
2   m1  2009-08-09
2   m2  2010-04-22
2   m2  2008-10-16
2   m2  2010-07-22
2   m3  2013-07-31
2   m3  2011-01-11
2   m3  2010-02-20
3   m1  2010-04-07
3   m1  2011-06-11
3   m1  2010-11-09
3   m2  2013-08-21
3   m2  2014-07-19
3   m2  2015-12-29
3   m3  2011-04-17
3   m3  2014-01-31
3   m3  2012-09-19
2   m3  2010-02-03
…

Q1: I need to find the CostumerID that has consumed a product in Jan and Feb.
Select a.CostumerID
From
(Select distinct CostumerID  from theTable  where month(date) = '2') as a
Inner join
(Select distinct CostumerID  from theTable where month(date) = '1') as b
On a.CostumerID  = b.CostumerID

Q2: Also, I need to find the most favorite one in all products that are consumed at the first time by each costumer.
Select b.title, count(b.title) as cnt
from
(
Select a.CostumerID , min(a.date) as earliestDate
from [DJX_test1].dbo.ama_services  as a
group by a.CostumerID
) as c
inner join [DJX_test1].dbo.ama_services  as b
on b.CostumerID = c.CostumerID and b.[date] = c.earliestDate
group by b.title
order by cnt desc

The table size may be large with 10+ millions rows.
Are there better  queries without using subqueries ?
Also, how to estimate a query's performance without running it ?
thanks

A: For the first question, try this:
SELECT DISTINCT costumerID
FROM theTable
WHERE month(date)='1' OR month(date)='2'

A: Q1: I need to find the CostumerID that has consumed a product in Jan and Feb.
SELECT costumerID
FROM theTable
WHERE month(Convert(date,[date]))='1' OR month(Convert(date,[date]))='2'

Q2: Also, I need to find the most favorite one in all products that are consumed at the first time by each costumer.
You can easily achieve it by using dense_rank() function as below.
;with cte as
(
    select costumerID,title,date,
    dense_rank() over (partition by costumerid order by convert(Date,[date])) as rn
    from theTable
)
select * from cte where rn=1


text:
Q: Auth and ACL with condition in CakePHP I can't find a solution to my problem.
I have an CakePHP website using Auth Component and ACL component.
I do not want users who are not active to be able to log in.
I found that userScope in Auth component can do that.
So in my AppController inside the beforeFilter, i added this :
    $this->Auth->userScope = array('User.active' => 1);

Of course in my UserController beforeFilter, a call to the parent method is made.
However, this doesn't worj, I am still able to login in with a user who have active set to 0.
I think it might be because of ACL component ?
Here is my beforFilter in AppController
    public function beforeFilter()
    {
    if (!$this->Session->check('Auth.User'))
        $this->layout = 'identification';
    $this->Auth->allow('display');

    //Configure AuthComponent
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
    $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
    $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'welcome');
    $this->Auth->userScope = array('User.active' => 1);
    }

What am I missing ?

A: If you don't make it, you can always use an alternative:
$user = $this->Auth->user();
if($user['User']['active'] == 0){
   $this->redirect($this->Auth->logout());
   $this->Session->setFlash('You are not active.');
}

A: The code you use is not valid with Cake 2. See http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
Here is some code that should work:
$this->Auth->authenticate = array('Form' => array('scope' => array('User.active' => 1)));


text:
Q: Replace characters in string based on preceding and following character The following two strings are the result of the expansion of a biblatex citation command:

Unicom Computer Corp. (in re), 13 F.3d 321, 30 Collier Bankr. Cas. 2d 655, 25 Bankr. Ct. Dec. 152 (9th Cir. 1994)
Personal Property Security Act (P.E.I.), R.S.P.E.I. 1988, c. P-3.1

What I want to do is wrap the biblatex citation command in a macro that will replace all dots, with a replacement character determined by the following condition set:

*

*If the character to the right of the dot is not a number, the dot should be removed entirely.

*If the character to the right of the dot is a number, and the character to the left of the dot is a number, the dot should be replaced by a dot, that is the dot should be kept in place.

*If the character to the right of the dot is a number, and the character to the left of the dot is not a number, the dot should be replaced by a space.
Applying the conditions on the example strings above, the macro should yield the following results:

Unicom Computer Corp (in re), 13 F 3d 321, 30 Collier Bankr Cas 2d 655, 25 Bankr Ct Dec 152 (9th Cir 1994)
Personal Property Security Act (PEI), RSPEI 1988, c P-3.1

It should be noted that the dots in the examples are already in the entries in the bibtex file. The reason that the dots are in there are that certain legal citation styles require the punctuations, whereas others require they are not present, the biblatex style I am writing should have an option to turn punctuation on or off, and it seems way easier to remove dots automatically but to add them automatically.
I have looked into the xstring package, but I was not able to find an appropriate macro in there. Furthermore, I would prefer being able to do that in plain TeX, so that the resulting style can be used without too many dependencies.

A: Here is a solution using LaTeX packages (works with l3regex, xparse and the expl3 bundle from 2011-10-09 onwards).
\RequirePackage{l3regex,xparse}
\ExplSyntaxOn
\tl_new:N \l_removedots_tl
\tl_new:N \l_removedots_str
\DeclareDocumentCommand{\removedots}{+v}
  {
    % Store the verbatim argument into a macro.
    \str_set:Nn \l_removedots_str {#1}

    % Remove all dots followed by a non-digit.
    \regex_replace_all:nnN { \.(\D) } { \1 } \l_removedots_str

    % Replace "non-digit--dot--digit" by "non-digit--space-digit".
    \regex_replace_all:nnN { (\D)\.(\d) } { \1\ \2 } \l_removedots_str

    % Re-tokenize the result, storing it into `\l_removedots_tl`
    \tl_set_rescan:Nno \l_removedots_tl
      {
        \int_set:Nn \tex_newlinechar:D { `\^^M }
        \int_set:Nn \tex_endlinechar:D { `\^^M }
      }
      \l_removedots_str

    % Then simply typeset that, but you could do other things to it.
    \tl_use:N \l_removedots_tl
  }
\ExplSyntaxOff

\documentclass{article}
\begin{document}

\removedots |Unicom Computer Corp. (in re), 13 F.3d 321, 30 Collier Bankr. Cas. 2d 655, 25 Bankr. Ct. Dec. 152 (9th Cir. 1994)

Personal Property Security Act (P.E.I.), R.S.P.E.I. 1988, c. P-3.1|

\end{document}

Under the hood, this is doing a lot of work, because TeX is not well suited to regular expression parsing. It will be difficult to do the same directly in TeX primitives.

A: With a simple loop, xstring is also able to do such things:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xstring}
\def\removedot#1{%
    \def\citation{#1}%
    \loop
        \StrPosition\citation.[\dotpos]%
        \ifnum\dotpos>0
        \StrMid\citation1{\number\numexpr\dotpos-1}%
        \StrChar\citation{\number\numexpr\dotpos-1}[\antechar]%
        \StrChar\citation{\number\numexpr\dotpos+1}[\postchar]%
        \antechar
        \IfInteger\postchar{\IfInteger\antechar.{\unless\ifx\postchar\space\space\fi}}{}%
        \postchar
        \StrGobbleLeft\citation{\number\numexpr\dotpos+1}[\citation]%
    \repeat
    \citation
}
\begin{document}
\removedot{Unicom Computer Corp. (in re), 13 F.3d 321, 30 Collier Bankr. Cas. 2d 655, 25 Bankr. Ct. Dec. 152 (9th Cir. 1994)\endgraf
Personal Property Security Act (P.E.I.), R.S.P.E.I. 1988, c. P-3.1}
\end{document}

EDIT: sorry for the bug. Here is a code in which the bug is fixed and the result is stored in the macro \newcitation:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xstring}
\def\expaddtocs#1#2{%
    \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter
    #1\expandafter\expandafter\expandafter{\expandafter#1#2}}
\def\removedot#1{%
    \def\citation{#1}\def\newcitation{}%
    \loop
        \StrPosition\citation.[\dotpos]%
        \ifnum\dotpos>0
        \StrLeft\citation{\number\numexpr\dotpos-2}[\temp]\expaddtocs\newcitation\temp
        \StrGobbleLeft\citation{\number\numexpr\dotpos-2}[\citation]%
        \StrChar\citation1[\antechar]\expaddtocs\newcitation\antechar
        \StrChar\citation3[\postchar]%
        \IfInteger\postchar
            {\IfInteger\antechar{\expaddtocs\newcitation.}{\unless\ifx\postchar\space\expaddtocs\newcitation\space\fi}}
            \relax
        \StrGobbleLeft\citation2[\citation]%
    \repeat
    \expaddtocs\newcitation\citation
    \newcitation% use the \newcitation macro
}
\begin{document}
\removedot{Unicom Computer Corp. (in re), 13 F.3d 321, 30 Collier Bankr. Cas. 2d 655, 25 Bankr. Ct. Dec. 152 (9th Cir. 1994)\endgraf
Personal Property Security Act (P.E.I.), R.S.P.E.I. 1988, c. P-3.1}
\end{document}

For sure, none of the codes shown in this thread are written with pure plain-TeX macros. It would be so hard that it is much better to use a package, either latex3 parser or xstring, both written in plain-teX.

A: "and it seems way easier to remove dots automatically but to add them automatically"
Tex is, by nature, already iterating through the tokens.
Inserting a dot then becomes easy.
Using David Carlisle's famous zz macro,

MWE
\documentclass{article}

\def\zz#1{\def\zzsep{}\zzz#1\relax}
\def\zzz#1{\ifx\relax#1\else\def\zzsep{.}#1\zzsep\expandafter\zzz\fi}

\begin{document}

DLR

\zz{DLR}
\end{document}

I set zzep to \- and hyphenchar to blank to do quick package-less line-breaks on long Chinese and Japanese text blocks, where otherwise the material would run off the edge of the page.

\documentclass[12pt]{article}

\def\zz#1{\def\zzsep{}\zzz#1\relax}
\def\zzz#1{\ifx\relax#1\else\def\zzsep{\-}#1\zzsep\expandafter\zzz\fi}

\newenvironment{hyphblnk}{%
\let\oldhyphenchar\hyphenchar%
\hyphenchar\font=\string"20}{\let\hyphenchar\oldhyphenchar}

\usepackage{fontspec}
\setmainfont{Noto Serif CJK SC}
\begin{document}

From Wikipedia (article about the solar system):

太陽系是一个受太阳引力约束在一起的行星系统,包括太阳以及直接或间接围绕太阳运动的天体。在直接围绕太阳运动的天体中,最大的八颗被称为行星,其余的天体要比行星小很多,比如矮行星、太阳系小行星和彗星。軌道間接围绕太陽运动的天體是衛星,其中有兩顆比最小的行星水星還要大。

\vskip2em
With line-breaks:

\begin{hyphblnk}
\zz{太陽系是一个受太阳引力约束在一起的行星系统,包括太阳以及直接或间接围绕太阳运动的天体。在直接围绕太阳运动的天体中,最大的八颗被称为行星,其余的天体要比行星小很多,比如矮行星、太阳系小行星和彗星。軌道間接围绕太陽运动的天體是衛星,其中有兩顆比最小的行星水星還要大。}
\end{hyphblnk}

\end{document}

To expand on the comment about using options:
An illustration may help of what I mean about using option settings.
In these citations:

the cases (fully in footnotes) are set to dotless italic v, upright party names, just for fun, and case year last, US-style, bib setting (default setting, footnote 10; override setting, 11), and then entry-level setting overriding that with case year first (12). Independently, the SCC favoured MNC style of a bare (bracketless) year (16), compared with the non-bare override version (17). And so on with other elements, with secondary materials, bibliography item grouping and labelling, whether the citation prints the case name inline and reference in a footnote, or all inline, or all footnote. Etc.
It's turning out to be very flexible. And also open-ended.
The options for the above look like this:
lawrefstyle=caseallbelow, %name and ref in footnote: caseallabove, caseabovebelow, caseallbelow
    party-names-italic=false,%default true
    statute-name-italic=false,%default true
    party-separator-italic=true, %default true
    party-separator-dotted=false, %defau--lt false
    printbib-legal=true, %print a McGill bib: default false; print command = \printbibliographylc
    printbib-aglc=true, %print an AGLC bib: default false; print command = \printbibliographylc
%   print-toc-tos=false, %table of cases and statutes: default true
      allbib-mnc-bare=false, %print MNC squareless: default false = not bare = with square brackets
      allbib-mnc-override=false, %bib option for MNC has priority: default true
      case-year-last=true,


text:
Q: Index out of bounds error with Gensim 4.0.1 Word2Vec model Error image1:
    Error image2:

I am new to study word2vec model. Here is the code, I want to use sentences list to finetune word2vec model (From Gensim 4.1.0)
from gensim.models import Word2Vec, KeyedVectors
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'

sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
            ['this', 'is', 'the', 'second', 'sentence'],
            ['yet', 'another', 'sentence'],
            ['one', 'more', 'sentence'],
            ['and', 'the', 'final', 'sentence']]

# load GoogleNews-vectors-negative300.bin
model = Word2Vec(sentences, vector_size=300, min_count=1, epochs=10)
model.build_vocab(sentences)
total_examples = model.corpus_count
print('total_examples:', total_examples)

model.wv.intersect_word2vec_format("GoogleNews-vectors**strong text**-negative300.bin", binary=True, lockf=1.0)

print('success')
model.train(sentences, total_examples=total_examples, epochs=model.epochs)
model.save("word2vec_model1")

I first got error below:

model.wv.intersect_word2vec_format("GoogleNews-vectors-negative300.bin",
binary=True, lockf=1.0) self.vectors_lockf[self.get_index(word)] =
lockf  # lock-factor: 0.0=no changes IndexError: index 12 is out of
bounds for axis 0 with size 1

Then I look into resource code in keyedvectores.py, code as below:
if word in self.key_to_index:
     overlap_count += 1
     self.vectors[self.get_index(word)] = weights
     self.vectors_lockf[self.get_index(word)] = lockf  # lock-factor: 0.0=no changes

I use ctrl+right click "vectors_lockf" to see this variance's declaration, but it shows "cannot find declaration to go"...
After that, when debugging, I find vectors_lockf is ndarray{ (1,)}[1.], but I don't know how it's generated... which code generates it.

A: This issue was not in gensim 3.8, vectors_lockf array was initialized internally but after update in gensim 4 they expect users to initialize this array manually when needed(you can see the comment in code).

After that, when debuging, I find vectors_lockf is ndarray{(1,)}[1.], but I don't know how it's generated...which code generate it..

It is initialized in init() method of Word2Vec class (word2vec.py)
if not hasattr(self, 'wv'):  # set unless subclass already set (eg: FastText)
    self.wv = KeyedVectors(vector_size)
    # EXPERIMENTAL lockf feature; create minimal no-op lockf arrays (1 element of 1.0)
    # advanced users should directly resize/adjust as desired after any vocab growth
    self.wv.vectors_lockf = np.ones(1, dtype=REAL)  # 0.0 values suppress word-backprop-updates; 1.0 allows

You can initialize this numpy array whenever you build vocab
model.build_vocab(sentences)
model.wv.vectors_lockf = np.ones(len(model.wv), dtype=REAL)

you can ignore dtype since default is float in numpy or you can import REAL dtype from gensim.


text:
Q: Invalid token 'event' in class, record, struct, or interface member declaration i got post response from slack with event property so i want to create model for event with below code
public Event event { get; set; } //getting error here

public class Event
        {
            public string type { get; set; }
            public string user { get; set; }
            public string text { get; set; }
            public string ts { get; set; }
            public string channel { get; set; }
            public string event_ts { get; set; }
        }
'''

got error in declaring event as name

A: Since event is a reserved keyword in C#, you'd need to tell the compiler that this is specifically not using that keyword.  You can use @ for that:
public Event @event { get; set; }

(As an aside: This is most commonly seen in View code where we need an anonymous object to have a class property for CSS rules.)

If possible however, it's recommended that you maintain C# naming conventions and translate between those conventions in your JSON serialization/deserialization.  Depending on how you perform that task there are different ways to approach it, such as using property attributes or a custom serializer.
Using Event as a class name might not be ideal either.  Try to be descriptive to avoid conflicting with anything common in the language.  Your udpated code might look something like:
public ChatEvent Event { get; set; }

//...
public class ChatEvent
{
    public string Type { get; set; }
    public string User { get; set; }
    public string Text { get; set; }
    public string Ts { get; set; }
    public string Channel { get; set; }
    public string Event_ts { get; set; }
}


text:
Q: Open multiple Projects/Folders in Visual Studio Code How do I open multiple projects/folders in a single Visual Studio Code instance, and open multiple files in single view? Does it has any option for future change request?

A:
October 2017 (version 1.18):
Support for multi-root workspaces is now enabled by default in the Stable release: https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces

Now we can open multiple folders in one instance, Visual studio code has named as Workspace ("Area de Trabajo"). Take a look at the images, it´s very simple.

A: Or you can just select multiple folders and then click open.
Go to File> Open Folder, then select multiple folders you want to open and click Select Folder

A: Support for multi-root workspaces is now enabled by default in the latest stable release [November 2017 release].
The File > Add Folder to Workspace command brings up an Open Folder dialog to select the new folder.

A: Not sure why the simplest solution is not mentioned. You can simply do File>New Window and open the other project in the new window.

A: Just put your projects in the same folder and simply open that folder in vscode.
Now your projects will appear like:
GROUP OF PROJECTS

*

*PROJECT 1

*

*Contents

*Contents

*PROJECT 2

*

*Contents

*Contents

A: It's not possible to open a new instance of Visual Studio Code normally, neither it works if you open the new one as Administrator.
Solution: simply right click on VS Code .exe file, and click "New Window"
you can open as many new windows as you want. :)

A: You can install the Open Folder Context Menus for VS Code extension from Chris Dias
https://marketplace.visualstudio.com/items?itemName=chrisdias.vscode-opennewinstance

*

*Restart Visual Studio Code

*Right click a folder and select "Open New Workbench Here"

Open New Workbench Here

A: If you are using unix like OS, you can create a soft link to your target folder.
E.g. I want to see golang source while I am using VSCode. So, I create a soft link to go/src under my project folder.
ln -s /usr/local/go/src gosrc

Hope this helps!

Update: 11/28, 2017
Multi Root Workspaces[0] landed in the stable build, finally.
https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces
[0] https://github.com/Microsoft/vscode/issues/396

A: Update
This is now available out of the box as of October 2017. From the blog post:

This was our #1 feature request - it's been a while coming but it's here now.

The complete documentation is here.

You can work with multiple project folders in Visual Studio Code with multi-root workspaces. This can be very helpful when you are working on several related projects at one time. For example, you might have a repository with a product's documentation which you like to keep current when you update the product source code.

Original answer
Currently the Insider channel of VSCode gives us this out of the box.

Read more from the blog post.

A: Update
As mentioned in several other answers here, this 'accepted' answer is outdated and is no longer correct.  VS Code now has the concept of a 'workspace' which lets you add several 'root' folders to VS Code in the same window.
For instance, when working on a project in one folder that utilizes shared code held in a different folder, you can now open both the project folder and the shared folder in the same window.
To do this you use the Add folder to Workspace... command.  VS Code then saves this configuration in a new file with a .code-workspace extension.  If you double-click that file, VS Code will re-open with both folders present.
Original Accepted Answer (Outdated)
As described in The Basics of Visual Studio Code article:
"VSCode is file and folder based - you can get started immediately by opening a file or folder in VSCode."
This means the concept of solution and project files, like the .sln and .csproj, have no real function in VSCode other than that it uses these only to target and identify which language to support for Intellisense and such.
Simply put, the folder you open is the root you work with. But of course there is nothing from stopping you to open multiple windows.
As for the request features options, navigate to Help > Request Features which will redirect you to the UserVoice page of VSCode.

A: You can open any folder, so if your projects are in the same tree, just open the folder beneath them.
Otherwise you can open 2 instances of Code as another option

A: On Windows it's possible to use mklink to create directory symbolic links to the needed folders. Then keep them together in a folder, and VSCode will list the content of these.
    c:\>mklink /D c:\dev\MyWork\scripts c:\ProjA\scripts
    symbolic link created for c:\dev\MyWork\scripts <<===>> c:\ProjA\scripts

    c:\>mklink /D c:\dev\MyWork\styles c:\ProjB\styles
    symbolic link created for c:\dev\MyWork\styles <<===>> c:\dev\ProjB\styles

This is very similar to @NeilShen's idea, I guess.

A: Multiple Folders in VS

Click ->File ->Add Folder to Workplace.

Step 1.

Choose which project to work ->Add(press)

Step 2.

A: You can open up to 3 files in the same view by pressing [CTRL] + [^]

A: What I suggest for now is to create symlinks in a folder, since VSCode isn't supporting that feature.
First, make a folder called whatever you'd like it to be.
$ mkdir random_project_folder
$ cd random_project_folder
$ ln -s /path/to/folder1/you/want/to/open folder1
$ ln -s /path/to/folder2/you/want/to/open folder2
$ ln -s /path/to/folder3/you/want/to/open folder3
$ code .

And you'll see your folders in the same VSCode window.

A: you can create a workspace and put folders in that :
File > save workspace as
and drag and drop your folders in saved workspace

A: You can use this extension known as Project Manager
In this the projects are saved in a file projects.json, just save the project and by pressing Shift + Alt + P you can see the list of all your saved projects, from there you can easily switch your projects.

A: To run one project at a time in same solution
Open Solution explorer window -> Open Solution for Project -> Right click on it  -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.

A: You can simply add folders (as many you want) in your workspace as shown in this image:
Image
And use them unhesitatingly.


text:
Q: Smart pointer not able to deallocate memory I have my smart pointer implementation as bellow which is NOT deallocating memory at exceptions ..
template <class T>
class SMARTPOINTER
{
public:
   SMARTPOINTER(T* pointee) : SMART_POINTEE(pointee) {
    cout <<"\n Inside class SMARTPOINTER CONSTURCTOR \n";
   }

   ~SMARTPOINTER() {
     cout <<"\n Inside class SMARTPOINTER DESTRUCTOR \n";
      delete SMART_POINTEE;
   }

   T& operator*() const
   {
      cout <<"\n Inside class SMARTPOINTER operator* \n";
      return *SMART_POINTEE;
   }

   T* operator->() const
   {
      cout <<"\n Inside class SMARTPOINTER operator->()  \n";
      return SMART_POINTEE;
   }

private:
   T* SMART_POINTEE;

};

class Widget
{
public:

  Widget() {
      cout <<"\n Inside Widget CONSTRUCTOR \n";
  }

   void Fun() {
     cout <<"\n Inside Widget::Fun() \n";
   }

  ~Widget() {
      cout <<"\n Inside Widget DESTRUCTOR \n";
  }

};

class THROWME{

};

int main() {

SMARTPOINTER<Widget> sp(new Widget);
sp->Fun();
throw new THROWME;
(*sp).Fun();

return 0 ;
}

I find that the output is
Inside Widget CONSTRUCTOR

 Inside class SMARTPOINTER CONSTURCTOR

 Inside class SMARTPOINTER operator->()

 Inside Widget::Fun()
uncaught exception of type THROWME*
Aborted.

As far as I know Smart pointers are supposed to help me in such cases!! I do not find destruction of Widget getting called via smart pointer .
So I must be missing some implementation here .
EDIT AFTER COMMENTS READ
With try catch i got my result  . But i still dont know if its right approach
change in code
  int main() {
        try {
        SMARTPOINTER<Widget> sp(new Widget);
        sp->Fun();
        THROWME tm;
        throw tm;
        (*sp).Fun();
        }
        catch(...) {
          cout <<"\n **SOME EXCEPTION CAUGHT**  \n";
        }
        return 0 ;
        }

result
 Inside Widget CONSTRUCTOR

 Inside class SMARTPOINTER CONSTURCTOR

 Inside class SMARTPOINTER operator->()

 Inside Widget::Fun()

 Inside class SMARTPOINTER DESTRUCTOR

 Inside Widget DESTRUCTOR

 **SOME EXCEPTION CAUGHT**

A: The destructor is not being called as the unhandled exception THROWME causes std::terminate to be called. See also this question, specifically the first quotation in the accepted answer:

C++11 15.2 Constructors and destructors [except.ctor]
1 As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.

As you have no try block to handle the exception, no destructor is called.

A: Calling of the destructor is part of stack unwinding, which is done when the exception "bubbles up" the call stack... except when the exception is unhandled. In that case, whether or not the stack is unwound is implementation-defined:

If no matching handler is found in a program, the function terminate() (except.terminate)  is  called.  Whether or not the stack is unwound before calling terminate() is implementation-defined.

To handle this more gracefully, you could use a function try block:
int main()
try {
  // main body
} catch (...) {
  std::cerr << "Unhandled exception\n";
  std::terminate();
}

... although this will swallow the exception and make it hard to debug.


text:
Q: Apache htdocs access restricted I'm running an Apache web server 2.2 inside a Windows 10 VM. Whenever I try to edit the index.html file in the htdocs directory, I get an error that prevents me from saving any new documents to the folder. Is there any way to circumvent this?
Thanks.

A: Brendan
I had the same problem as you and I figured out a way. You need to edit the file as administrator.
Here is the way I did it:

*

*Open CMD as administrator.

*Run the command net user.

*Run the commandnet user administrator /active:yes.

*Run net user administrator *.

*Enter your new password.

*Click the windows tab and click on your current user account.

*Switch over to the newly created Admin account.

*Go to the file you want to edit.

*Edit Away, my friend!


text:
Q: Constructor confusion This is part of class  Balls that come from Dart samples(clock sample):
  DivElement root
  num lastTime;
  List<Ball> balls;

Balls() :
lastTime = new Date.now().millisecondsSinceEpoch,
balls = new List<Ball>() {                           \\I do not understand here, why use
root = new DivElement();                             \\ List<Ball>(){...}
document.body.nodes.add(root);
makeAbsolute(root);
setElementSize(root, 0.0, 0.0, 0.0, 0.0);
}

Because I do not understand, I change constructor :
    Balls() {

    lastTime = new Date.now().millisecondsSinceEpoch;
    balls = new List<Ball>() ;
    root = new DivElement();
    document.body.nodes.add(root);
    makeAbsolute(root);
    setElementSize(root, 0.0, 0.0, 0.0, 0.0);

  }

The application still work. Are there different between constructor Ball(): and Ball(){}?. Thanks.
Sorry about my English.

A: Both versions should work fine. The code in : notation is ran before the constructor body, so it's often used for things like calling the super:
class Person {
  String name;

  Person(this.name);
}

class Employee extends Person {
  Employee(name) : super(name) {
    print('ran after the super call');
  }
}

I think the function body is a cleaner approach and I believe the "balls" example wanted to show off different styles, because you could initialize the values inline as well.
I usually use the function body approach unless it looks cleaner or I'm calling parent constructors.
Update: Ladicek added fair points. You may initialize final fields inline or within the initializer list. And unlike some languages, in Dart there's a guarantee the fields will never be in uninitialized state. It's also good to remember that initializers are run in the order they are listed.


text:
Q: Python regular expressions with OR function I want to extract the strings "981","1922","1849","1819" from both string 1 and string 2 in one regular expression.
 #string 1
 :3:LKR5000->981:4:LKR1000->1922:5:LKR500->1849:6:LKR100->1819

 #string 2
 :1:LKR5000->981
 :2:LKR1000->1922
 :3:LKR500->1849:4:LKR100->1819

Written python code:
   firstNote=re.findall(':\d:LKR\w+\-\>(.*?)\:',strtosearch2,re.DOTALL)

   1000s=re.findall('LKR1000->(.*?)\:',strtosearch2,re.DOTALL)
   500s=re.findall('LKR500->(.*?)\:',strtosearch2,re.DOTALL)
   100s=re.findall('LKR100->(.*?)\n',strtosearch2,re.DOTALL)

Can anyone help me to complete the code?
Thank you

A: Try this regex:
(?<=->)\d+

Click for Demo
See the code output here
Explanation:

*

*(?<=->) - positive lookbehind to find the position immediately preceded by ->

*\d+ - matches 1+ occurrence of digits

OR, use this regex:
(LKR\d+)->(\d+)

Click for Demo
From this regex, for each match, you can extract the contents of Group 1 and check if it is LKR1000,LKR500,LKR100 and get its corresponding value from group 2 of that match

A: The following regex should word: r"LKR\d+->(\d+)":
re.findall(r"LKR\d+->(\d+)",s1)
#['981', '1922', '1849', '1819']
re.findall(r"LKR\d+->(\d+)",s2)
#['981', '1922', '1849', '1819']


text:
Q: SQL XML Insert multiple elements Please help! I have a field of xml within a database.  I am trying to insert a new element for each element in the field. E.g:
<some-element>

</some-element>
<some-element>

</some-element>

would insert element c and go to:
<some-element>

<c> </c>
</some-element>
<some-element>

<c> </c>
</some-element>

I know I can use @fieldname.modify('insert @CElement into (/some-element)[1]') but this only changes the first element! I want to repeat this for all elements.
Any help would be very much appreciated! (I am using SQL server 2008)
Moved from answer:
Thank you for your reply! Perhaps it would help if I was more specific... I am describing a simple table of data within the xml. I am trying to add a new column. I can add the column within the column descriptions but I need to add the column element to all the rows. (It would not be a simple task to change the structure and I would like to avoid this!) E.g:

   <Columns>
      <Column ID="0">
      <Column-Name>0NAME</Column-Name>
      </Column>
      <Column ID="1">
      <Column-Name>1NAME</Column-Name>
      </Column>
      <Column ID="2">
      <Column-Name>2NAME</Column-Name>
      </Column>
      <Column ID="3">
      <Column-Name>!!!! THIS COLUMN IS BEING ADDED !!!!!</Column-Name>
      </Column>
   </Columns>
 <Rows>
        <Row ID="0">
          <C ID="0">0 contents here</C>
          <C ID="1">0 contents here</C>
          <C ID="2">0 contents here</C>

         </Row>
        <Row ID="1">
          <C ID="0">1 contents here</C>
          <C ID="1">1 contents here</C>
          <C ID="2">1 contents here</C>

        </Row>
    <Row ID="2">
          <C ID="0">2 contents here</C>
          <C ID="1">2 contents here</C>
          <C ID="2">2 contents here</C>

        </Row>
</Rows>

A: You can recreate your XML, e.g.:
declare @x xml = '<some-element>
1
2
</some-element>
<some-element>
3
4
</some-element>'

select @x.query
('
   for $e in some-element
   return
     <some-element>
      { $e/a }
      { $e/b }
      <c/>
     </some-element>
')

A: Adapting the answer provided by Kirill Polishchuk to the new XML structure:
select @XML.query
('
   for $c in Table/Columns
   return

       <Columns>
         { $c/* }
       </Columns>
       <Rows>
         {
           for $r in Table/Rows/Row
           return
             <Row>
               { $r/* }
               <C ID="3"/>
             </Row>
         }
       </Rows>

')


text:
Q: Serializing BSON stream in Node.js I have a Node.js tcp server that receive BSON objects over stream and I would like to read every time the whole BSON object from the BSON.DeserializeStream (MongoDb npm).
The problem is when the BSON object is big I don't get the whole object on the data event and therefore I can't deserialize it (I get corrupted message error):
socket.on('data', function(data) {
// The data is partial and cannot be sent to the BSON.Serializer
})

I don't know if its possible to get the whole BSON object like .NET serializers or I will have to manage the parts until I receive the whole message (Send the first 4 bytes as the message length and then don't try to deserialize the object until the whole message received.


text:
Q: How to output only a part of values from ListBox? I would like to output only a part of items from listBox1 like:response.response.items[counter].first_name to lable_name.Text. How can I do that?
Part of method:
for (int counter = 0; counter < response.response.items.Count; counter++)
{
    listBox1.Items.Add(response.response.items[counter].first_name + " " + response.response.items[counter].last_name  + Environment.NewLine);
}

The way I output items to lable:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
    int count = listBox1.Items.Count -1;

    for (int counter = count; counter >= 0; counter--)
    {
        if (listBox1.GetSelected(counter))
        {
            lable_name.Text= listBox1.Items[counter].ToString();
        }
    }
}

A: lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];

could be one of the options ...
just make sure what charackter are qou spliting on as well as the text in string.


text:
Q: Get maximum values relative to the current index in pandas python Let me say I have a DataFrame where the data is ordered with respect to time. I have a column as weights and I want to find the maximum weight relative to the current index. For example the max value found for the 10th Row would be from elements 11 to the end.
I ended up writing this function. But performance is a big threat.
import pandas as pd

df=pd.DataFrame({"time":[100,200,300,400,500,600,700,800],"weights":
[120,160,190,110,34,55,66,33]})
totalRows=df['time'].count()
def findMaximumValRelativeToCurrentRow(row):
 index= row.name
 if index!= totalRows:
    tempDf = df[index:totalRows]
    val=tempDf['weights'].max()
    df.set_value(index,'max',val)
 else:
    df.set_value(index,'max',row['weights'])

df.apply(findMaximumValRelativeToCurrentRow,axis=1)
print df

Is there any better way to do the operation than this?

A: You can use cummax with iloc for reverse order:
print (df['weights'].iloc[::-1])
7     33
6     66
5     55
4     34
3    110
2    190
1    160
0    120
Name: weights, dtype: int64

df['max1'] = df['weights'].iloc[::-1].cummax()
print (df)
   time  weights    max  max1
0   100      120  190.0   190
1   200      160  190.0   190
2   300      190  190.0   190
3   400      110  110.0   110
4   500       34   66.0    66
5   600       55   66.0    66
6   700       66   66.0    66
7   800       33   33.0    33


text:
Q: Angular 6 router.events.filter 'filter' does not exist on type 'Observable' I have finished to update my App to Angular 6 (it was in 5.2 version).
I got an error syntax in :
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
...
constructor(private router: Router) {}

this.router.events.filter
      (event => event instanceof NavigationEnd).subscribe((res) =>
    {
      // DO something
    });

error TS2339: Property 'filter' does not exist on type
  'Observable'.

what's the right syntax in Angular 6 ?
thanks

A: I don't see in your code if you imported filter
for Rxjs 6:
import { filter } from 'rxjs/operators';

    .
    .
    .

     this.router.events.pipe(
       filter((event:Event) => event instanceof NavigationEnd)
     ).subscribe(res => console.log(res))

A: This is how to filter router events with Angular 6+ and latest RxJS:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';

import { filter } from 'rxjs/operators';

export class MyComponent implements OnInit {
    constructor(private router: Router, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.router.events.pipe(
            filter(event => event instanceof NavigationEnd)
        ).subscribe(() => {
            console.log(this.activatedRoute.root);
        });
    }
}

Uses the pipe operator instead of attempting to chain filter on the observable.

A: Activated Route wasnt giving me the url. So I tried this.
P.S: event['url'] worked instead of event.url
import { filter } from 'rxjs/operators';
import { Router,NavigationEnd } from '@angular/router';

 router.events.pipe(filter(event => event instanceof NavigationEnd))
        .subscribe(event =>
         {
            this.currentRoute = event['url'];
            console.log(this.currentRoute);
         });


text:
Q: Combine Gyroscope with accelerometer to get heading I'm using an Android device to get the heading(azimuth, or yaw angle).
Android API used the Accelerometer value + the mganetic field to compute a matrix rotation, the azimuth is then extracted form that matrix (aka SensorManager.getOrientation(...)) But the result is very inaccurate! especially if the phone is perturbed by some magnetic stuff.
And then I have the Gyroscope, If I integrate the value of the gyro trough time, I'm able to get an actual Angle, but like everybody knows :p, this is subject to drift... after 10 seconds even tough I'm not moving the angle drifted of 10°...
So here I have in one side the result of the accel + magneto, it's quite crap near magnetic field
and on the other side I have the result of the gyro that are really good, but drift over time...
So my question is, is there an easy or smart way to combine the two results together to get a kind of "robust" heading estimation? I say easy because I know there is kalman filters.. but even tough i read the theory 50 times I can't get a damn thing :).
Thank you!

A: As far as I know, either the Kalman filter or something similar is implemented in the SensorManager. Check out Sensor Fusion on Android Devices: A Revolution in Motion Processing.
You are trying to solve a problem that is already solved.

A: TO make it short:
It is not possible to combine Gyroscope + accelerometer TO GET THE AZIMUTH (I precise) Simply because the accelerometer can't sense acceleration on the XY axis..
A method would be to fuse the Gyroscope with the Compass but that won't work really good if there is magnetic pertubation

A: It seems to have a very generalized confusion about gyroscope sensor. I have recently answered a similar question here, so I recommend to anybody interested in these topics to have a look at that question and answer.
I have used the described technique in this application (a compass which integrates gyroscope readings to improve results). The result is not perfect, but is much better in general than other compasses.


text:
Q: Batch for each line in directory with spaces I'm trying to create a batch file that compresses all folders within the main folder to individual zip files with the same name as the subfolders.
Example folder structure:

So in the main folder, zips need to appear with the exact same name and contents as the subfolders.
The code I have right now is posted below. The problem occurs because I have to quote pathnames because they contain spaces and therefore "%CD%\folders.txt" in line 4 isn't parsed as filename, but as litteral input string. How can I get this to work?
P.s. I don't require a temporary folders.txt, this just came closest to working as intended.
set zip="P:\Programma's\x64\WINRAR\rar.exe" a -r -u -ep1
dir "%CD%" /d /ad /s /b > "%CD%\folders.txt"
set /a COUNT=0
pause
for /f "usebackq delims=|" %%f in ("%CD%\folders.txt") do (
echo %%f
%zip% "%CD%\%%~nf.zip" %%f\* >nul
set /a COUNT+=1)
del "%CD%\folders.txt"
echo.
echo ....................................................
echo.
echo Compressed %COUNT% folders
pause

A: Maybe use a variable to store it :
set cdfolder="%CD%\folders.txt"

then use it everywhere you need it
...
dir "%CD%" /d /ad /s /b > %cdfolder%
...


text:
Q: C++ SFML Font Problems sf::RenderWindow window(sf::VideoMode(800, 600), "CALENDAR");

sf::Font font;
if (!font.loadFromFile("arial.ttf"))
    std::cout << "no\n";

sf::Text text1;
text1.setFont(font);
text1.setCharacterSize(30);
text1.setColor(sf::Color::Black);
text1.setStyle(sf::Text::Regular);
text1.setString("ttestst");

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type){
        case sf::Event::Closed:
            window.close();
        }
    }

    window.clear(sf::Color::White);
    window.draw(text1);
    window.display();
}

This code isn't displaying text to the screen, and the font isn't loading, i've no idea what to do, any help is appreciated.

A: It seems like the path to the font is wrong. If you're using "arial.ttf", make sure that font file is in the same directory where your program starts executing.
As @twsaef said you can also use absolute path, but not in this way:
"C:\Coding\Fonts\Arial.ttf"

This is wrong. Instead of single backslash \ you have to use double backslash \\:
"C:\\Coding\\Fonts\\Arial.ttf"


text:
Q: Why trackBar2.Maximum show 16 steps and not 15? bitmaps is array and contain 15 indexs from 0 to 14.
But after setting trackBar2.Maximum to the bitmaps Length i see on the trackBar2 16 places not 15.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            trackBar2.Enabled = true;
            trackBar2.Maximum = bitmaps.Length;
            for (int i = 0; i < bitmaps.Length; i++)
            {
               ConvertTo24(bitmaps[i]);
            }
            timer2.Stop();
            b1.Dispose();
        }

Then in the trackBar2 scroll event:
private void trackBar2_Scroll(object sender, EventArgs e)
        {
            LoadPictureAt(trackBar2.Value, sender);
            mymem = ToStream(bitmaps[trackBar2.Value], ImageFormat.Bmp);
            backTexture = TextureLoader.FromStream(D3Ddev, mymem);
            scannedCloudsTexture = new Texture(D3Ddev, 512, 512, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
            timer1.Stop();
            Button1Code();
            timer1.Start();
            pictureBox1.Refresh();
        }

When i move the scrollBar2 to the top it's throwing exception: Index was outside the bounds of the array
System.IndexOutOfRangeException was caught
  HResult=-2146233080
  Message=Index was outside the bounds of the array.
  Source=My Weather Station
  StackTrace:
       at mws.ScanningClouds.trackBar2_Scroll(Object sender, EventArgs e) in d:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\ScanningClouds.cs:line 709
       at System.Windows.Forms.TrackBar.OnScroll(EventArgs e)
       at System.Windows.Forms.TrackBar.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WmVScroll(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmMouseMove(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.TrackBar.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at mws.Program.Main() in d:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Program.cs:line 28
  InnerException:

Line 709 is:
mymem = ToStream(bitmaps[trackBar2.Value], ImageFormat.Bmp);

The trackBar2 minimum is set to 0 i tried to set it to 1 but then i get the exception on the same line. Same exception even that now trackBar2 have 15 steps still same exception when i drag the trackBar2 scroller to the top to the end.

A: TrackBar's Minimum & Maximum bounds are inclusive. Try setting trackBar2.Maximum = bitmaps.Length - 1
If you want a "friendly" GUI, it's better to set .Minimum = 1 & .Maximum = bitmaps.Length and use its Value as int pictureIndex = trackBar2.Value - 1;


text:
Q: Equivalence of maximizing variance and sum-of-squares for a projection. (The following is motivated by the singular value decomposition:)
Say we have an N x D matrix $A$. The first principal component $v_1$ is the unit-length vector of dimension D which maximizes the variances of the projections $v_1^Tx_i$. But I have also heard it described as the vector that maximizes the sum-of-squares projections: i.e. $v_1 = argmax_v|Av|$. Why are these two interpretions equivalent? I played with some numbers and found maximizing the variance is equivalent to maximizing $n\sum_{i}(v^Tx_i)^2 - (\sum_iv^Tx_i)^2$. But it isn't clear to me that the mean projection should be 0.


text:
Q: Enumerate JumpList recent files? I'm populating a jumplist via:
    public static void AddToList(String path)
    {
        var jumpList = JumpList.GetJumpList(Application.Current);
        if (jumpList == null) return;

        string title = System.IO.Path.GetFileName(path);
        string programLocation = Assembly.GetCallingAssembly().Location;

        var jt = new JumpTask
        {
            ApplicationPath = programLocation,
            Arguments = path,
            Description = path,
            IconResourcePath = programLocation,
            Title = title
        };

        JumpList.AddToRecentCategory(jt);

        jumpList.Apply();
    }

Which works great. The only problem is that I also have a file menu in my application and would like to show the recent list there as well. I could do it easily by storing a second copy of the recent files, but I was wondering if I could possibly enumerate the list of files used by the jumplist. I haven't been able to figure out anything for doing so.
Am I missing something here? Can I enumerate the files in the jumplist, or do I need to store my own duplicate list?

A: I have checked your code. And I have the question to it. I looked into MSDN page that you provided. And there I see example of adding task:
private void AddTask(object sender, RoutedEventArgs e)
{
  //....
  //Mostly the same code as your
  JumpList jumpList1 = JumpList.GetJumpList(App.Current);
  jumpList1.JumpItems.Add(jumpTask1); // It is absent in your code!!!
  JumpList.AddToRecentCategory(jumpTask1);
  jumpList1.Apply();
}

I have created two my own methods Create and Extract and I can access to created during current session task at least. This is my code:
private void Extract()
{
    var jumpList = JumpList.GetJumpList(Application.Current);

    if (jumpList == null) return;

    foreach (var item in jumpList.JumpItems)
    {
        if(item is JumpTask)
        {
            var jumpTask = (JumpTask)item;
            Debug.WriteLine(jumpTask.Title);
        }
    }
}
private void Create() {
    var jumpList = JumpList.GetJumpList(Application.Current);

    if (jumpList == null)
    {
        jumpList = new JumpList();
        JumpList.SetJumpList(Application.Current, jumpList);
    }

    string title = "Title";
    string programLocation = "Location";
    var path = "path";

    var jt = new JumpTask
    {
        ApplicationPath = programLocation,
        Arguments = path,
        Description = path,
        IconResourcePath = programLocation,
        Title = title
    };
    jumpList.JumpItems.Add(jt);
    JumpList.AddToRecentCategory(jt);
    jumpList.Apply();
}

I am not sure that this is answer on your question, but I am looking to reason why you don't add your task to JumpItems list?