text:
Q: Count a grouped by SOQL So I've added a count field to the object and based on your advice I built this SOQL, how can I now order the result based on the SUM?
    List<AggregateResult> result = [SELECT Searched_Phrase__c, SUM(Count__c) sum
FROM Portfolio_Catalog_Searched_Term__c
GROUP BY Searched_Phrase__c
limit 5];

I'm looking for help on what is the right way to write this SOQL:
I have an object that holds the phrases that were entered into a search box (search terms), each record represents one search that was made.
I want to count how many searches were made for each phrase and order this in a descending order.
I want to use this to show on a VF page the top 5 searched.
What is the right SOQL statement for this?

A: Something like this?
SELECT Name, COUNT(Id)
FROM Search_Term__c
GROUP BY Name
ORDER BY COUNT(Id) DESC
LIMIT 5

(assuming you're storing the searched phrases in Name field)
Here's whole SELECT reference: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_soql_select.htm

You'll get the results as List<AggregateResult> and then you might have to cast them to some helper wrapper class or split into separate list of strings and integers... Something like this
List<Wrapper> results = new List<Wrapper>();
for(AggregateResult ar: [SELECT Name, COUNT(Id) c
FROM Search_Term__c
GROUP BY Name
ORDER BY COUNT(Id) DESC
LIMIT 5]){
    results.add(new Wrapper(String.valueOf(ar.get('Name')), Integer.valueOf(ar.get('c'))));
}

public class Wrapper{
    public String name {get;private set;}
    public Integer value {get;private set;}
    public Wrapper(String n, Integer v){
        name = n;
        value = v;
}

A: List<AggregateResult> result = [
  Select phrase__c, count(Id)
  From PhraseObject__c
  Group by phrase__c
  Order by count(Id) desc
  Limit 5
];

A:     public SelectOption[] UPloadNames{
    public get {
    SelectOption[] uploadNames;
    uploadNames= new SelectOption[]{};
    for (AggregateResult   ar: [SELECT UploadName__c Name, COUNT(Id)
         FROM Location_Uploads__c  GROUP BY UploadName__c ]) {
         uploadNames.add(new SelectOption(String.valueOf(ar.get('Name')),String.valueOf(ar.get('Name'))));
    }
       return uploadNames;
                 }

       private set;
    }


text:
Q: Overloading operators with dictionaries in Python I have a class L that takes multiple dictionaries like this:
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))

I'm trying to add two D objects together and return a new L object, such that
a = L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))
b = L((n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
>> a+b
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
c = (c:'carrot',d:'2')
>>a+c
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(c:'carrot',d:'2'))

I'm really lost, so far I've tried to use eval() with no success.. it returns nothing and I'm not sure what to do?

A: First off, stay away from eval() it is very, very seldom a good idea to use it.
Secondly, why can't you just do this:
def __add__(self, other):
    if type(other) == dict:
       return DL(*(self.dicts + [other]))
    elif type(other) == DL:
       return DL(*(self.dicts + other.dicts))
    raise ValueError("Only DL and dict are supported")

redpajama_set_name: RedPajamaStackExchange


text:
Q: online enviornment for visual studio developemnt can I get an online work environment for projects development in visual studio, where a user can login from browser and start coding, testing, and deployment to a web server. developers are not required to install visual studio on their local machine. And if its so, is it possible that we can restrict developers from copying in and out anything from that environment(that is not a must to have, but nice to have feature). Plus If  there is a similar environment for  xamarin for visual studio. I am sorry if this is not the right place for such queries.

A: A web based IDE is built into Azure. Called "Monaco" it allows you to edit web pages only.
There is no such thing as Visual Studio in the Web yet.


text:
Q: Add gradle resources unders custom output dir I have a project structure like this (using gradle 2.11):
submodule1
|
- src
  |
  - main
    |
    - resources
      |
      - file1
submodule2
|
- resources
  |
  - file2
  - file3

I'm adding some additional things to submodule1's resources via:
sourceSets {
   main {
      resources {
         srcDir("../submodule2/resources")
      }
   }
}

Is there an easy way to specify a custom output path for resources from submodule2? Currently when I jar it, all resource files file1, file2 etc. will be put inside the jar on the top level. I would like the submodule1 files to stay at top level and the submodule2 resources to be put inside the jar under a custom path i.e. submodule2resources.

A: You need to filter the files during the jar file is built. It's done in jar closure in build.gradle file using the DSL. The problem here lies in the fact that when you add a source set and jar is prepared the information about the origin of a given file is lost - all files belong to submodule1 now - hence a workaround here is needed:
apply plugin: 'java'

project.ext.sm2Resources = project.file("../sm2/src/main/resources")

sourceSets {
    main {
        resources {
            srcDir(sm2Resources)
        }
    }
}

jar {
  eachFile { f ->
      if(new File(sm2Resources, f.file.name).exists()) {
        f.path = "sm2/$f.name"
      }
  }
}

Check out the demo.


text:
Q: Overriding chain operations ? Greedy Is there a way to override/implement a chain operation.
What I mean ? lets take multiplication it handles a * b
In my case I use __mul__ to binary-OR the two operands and then apply destructive operation, which means that the result is different for 3 operands.
Here is pseudo code
class MyClass:

def fun(self, lst):
   for i in lst : x |= i
   ... destructive ops ...
   return x

def __mul__(self, rhs): return self.fun([self,rhs])

Now those two are equivalent :
 a * b   <==>  fun([a,b])

but those are not :
 a * b * c   <=/=>  fun([a,b,c])

because the multiplication is done in two steps and the function call in one.
Is there a way to make multiplication greedy, so that it can collect same operation if repeated ? The same goes for "+" ?

A: Destructive operations can make code very hard to reason about. Try to work out a pure, functional solution instead of hacking around operator precedence.


text:
Q: Optimize binded DataGridView search feature Hi everyone,
I've got my code running perfectly fine, but it looks nasty. Its purpose is to search and display workers from my database that match search criteria. I've got a DataGridView on my form filled with workers databinded from my database. After I press Search button I only want to display the list of workers matching the criteria from TextBoxes/ComboBoxes. If they're empty it's displaying a full list once again.

Search feature on form:

Code:
private void btnSearch_Click(object sender, EventArgs e)
{
    FillList();
    List<Worker> list = new List<Worker>();
    bool match = false;

    foreach (var worker in workerBindingSource)
    {
        if (txtName.Text.Length > 0 && !((Worker)worker).Name.ToLowerInvariant().Contains(txtName.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (txtLastName.Text.Length > 0 && !((Worker)worker).LastName.ToLowerInvariant().Contains(txtLastName.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (txtOIB.Text.Length > 0 && !((Worker)worker).OIB.ToLowerInvariant().Contains(txtOIB.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (txtLocation.Text.Length > 0 && !((Worker)worker).Location.ToLowerInvariant().Contains(txtLocation.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (txtAddress.Text.Length > 0 && !((Worker)worker).Address.ToLowerInvariant().Contains(txtAddress.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (txtPhoneNumber.Text.Length > 0 && !((Worker)worker).PhoneNumber.ToLowerInvariant().Contains(txtPhoneNumber.Text.ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (!cboProfessionalQualification.SelectedValue.ToString().Equals("Empty") && !((Worker)worker).ProfessionalQualification.ToString().ToLowerInvariant().Contains(cboProfessionalQualification.SelectedValue.ToString().ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (!cboDegree.SelectedValue.ToString().Equals("Empty") && !((Worker)worker).Degree.ToString().ToLowerInvariant().Equals(cboDegree.SelectedValue.ToString().ToLowerInvariant()))
        {
            match = false;
            continue;
        }
        else
            match = true;

        if (match)
        {
            list.Add(WorkerDAO.ReadWorker(((Worker)worker).ID));
        }
    }

    SortableBindingList<Worker> sortableList = new SortableBindingList<Worker>(list);
    workerBindingSource.DataSource = sortableList;
}

Everything in code with "txt" prefix is TextBox and everything with "cbo" prefix is ComboBox. ComboBoxes contain certain enums that user can pick. If ComboBox is displaying enum value "Empty" it means user picked nothing (same as zero length value of string). SortableBindingList is just for sorting purpose on column header click, nothing important in this case. ReadWorker method is returning a worker only if he's matching all searching values and he's then added to list I display on DataGridView after. FillList method is setting whole list of workers from database to DataBindingSource.

ReadWorker method:
public static Worker ReadWorker(int workerID)
{
    var worker = ReadEverything().Where(x => x.ID == workerID).FirstOrDefault();

    return worker;
}

Method ReadEverything returns list of all workers from database.
I'm looking for a LINQ solution (or any other better solution) to reduce my code drastically and make it more readable, but since I'm still pretty fresh to programming and LINQ I can't figure it out myself. So I wondered if you guys could help me a bit or at least point me at right direction.
Thanks in advance!

A: If your datagridview already has all the data from database, I'll suggest you not to go to database for search again, because you already have all the data. Just filter it in memory and show it.
If at all you need to hit database for some reason, there is no reason to get all the data from database and filter it in client side, just pass the "workerId" to stored procedure, let the SP add proper where condition and return the filtered data.
To implement in memory filtering using Binding Source:
bindingSource.Filter = "columnname = 'value'";

private void button1_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

     dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
     bindingSource.Filter = string.Format("{0} = '{1}'","YourColumnName", searchValue );
     //here you can do selection if you need
}

To remove filter use the following

bindingSource.RemoveFilter();
//or
bindingSource.Filter = null;

Originally posted as answer here.


text:
Q: Text-overflow ellipsis in  does not work --> Shadow-Dom-Element does not take parent width I have a problem with a List Page in Ionic 4.
I want to display some <ion-card> elements.
The texts in  can be very long (they are comming from the backend). I do not want them to line break, but to use the ellisis ("...") - See Screenshots below.
Normally I would just set overflow: hidden on the parent, and white-space: nowrap; text-overflow: ellipsis; on the element I want to have the ellipsis. However because of the web-component-shadow-dom-stuff this does not work out of the box, and I can't figure out why...
You can see, that <ion-card-title> is not taking the width of the parent. How do I manipulate the text "This is a long text. Lorem..." that it fits the container and correctly sets the ellipsis?

HTML
   <ion-card>
    <ion-card-header>
        <div class="card-header-title-wrapper">
            <ion-checkbox></ion-checkbox>
            <ion-card-title>This is a long text. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
                tempor</ion-card-title>
        </div>
        <ion-card-subtitle text-end>Subtitle</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
        Card Content...
    </ion-card-content>
</ion-card>

(simplified) CSS
div.card-header-title-wrapper {
  display: flex;
  overflow: hidden;

  ion-checkbox {
    margin-top: 3px;
    margin-right: 12px;
    flex-grow: 0;
    flex-shrink: 0;
  }
}

ion-card-header {
    ion-card-title {
        font-size: 16px;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}

It currently looks like this

I want it to look like this

A: in your ion-card-title css, add overflow: hidden;

A: just adding overflow: hidden did not seem to work.
following this from csstricks, width is required on the element:
https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/
.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

adding a width fixed it for me...


text:
Q: XML file to Oracle Здравствуйте. Требуется создать xml и записать не данные а сам xml файл в таблицу Oracle. Вычитал что для хранения самого файла в таблице есть типы clob либо xmltype. Создал таблицу с таким полем. И проблема в загрузке туда файла непосредственно кодом.
String str = "D:\\file.xml";
XmlTextWriter textWritter = new XmlTextWriter(str, Encoding.UTF8);
textWritter.Formatting = Formatting.Indented;
textWritter.WriteStartDocument();
textWritter.WriteStartElement("NAME");
textWritter.WriteString(TextBox1.Text);
textWritter.WriteEndElement();
textWritter.Close();

Это создание xml файла. И вот как я пытаюсь добавит его в таблицу.
con.Open();
OracleCommand com = new OracleCommand("insert into test3 (name) VALUES ('" + textWritter + "')", con);
com.ExecuteNonQuery();
con.Close();

Но как я уже понял textWritter не содержит сам файл в себе. Что мне нужно подставить вместо values что бы в таблицу записался именно файл. Спасибо заранее.


text:
Q: How to get debugging of an App Engine application working? I've got 10+ years in C/C++, and it appears Visual Studio has spoilt me during that time. In Visual Studio, debbuging issimple: I just add a breakpoint to a line of code, and as soon as that code is executed, my breakpoint triggers, at which point I can view a callstack, local/member variables, etc.
I'm trying to achieve this functionality under App Engine. I assume that is possible?
All the searching I've done to this point has led me to using Pydev in Eclipse. As best I can tell, I am successfully launching my simple 'hello world' program in Debug mode.
But the IDE doesn't even seem to have an option to set a breakpoint? I must be missing something.
I've googled long and hard about this, but am having no luck. Most results trace back to the same old threads that don't deal directly with my issue.
Can anyone shed some light on how you get basic debugging setup using Pydev/Eclipse with App Engine?
Alternatively, if there's an easier way to debug App Engine than using Pydev/Eclipse, I'd love to hear about it.
Thanks in advance.

A: In fact setting a breakpoint in eclipse is very easy. You have two options:
In the grey area next to your line numbers, doubleclick or right mouseclick -> toggle breakpoint.


text:
Q: How do the Scrum Master's responsibilities change over the years? If a team already practices Scrum method successfully, how does the Scrum Master participate in further development? Will he/she continue to fulfill the same responsibilities?

A: The Scrum Master is a coaching role. Lyssa Adkins borrows the Shu-Ha-Ri approach from Aikido when talking about coaching teams. (I only know this model from coaching, I have no idea how faithfully it's adopted).
Early in Scrum maturity, the team is in the Shu level. They need to understand how the mechanics of Scrum work, develop discipline in the practices, and learn how to be effective in the new approach. The Scrum Master acts as a guide in these areas.
In the Ha level, the team understands the rules of Scrum and wants to bend them or expand on them to adjust the method of working to their needs. Here, the Scrum Master helps the team structure these experiments and drives transparency so that the team gets the most out of these improvements.
Finally, in the Ri level, the team has a deep understanding of how and why Scrum works and can apply these principles to develop completely new and novel ways of working. The Scrum Master here acts in a purely coaching role, stimulating and encouraging the team in their thinking.
There is no timeline for this. If the team has never followed Scrum as recorded, they've never really settled into the Shu level. Similarly, if they have always stuck by the rules, they've probably had this level mastered for a long time, but never moved on.
This is just in coaching the team. Of course, there is a whole organization around the team to work with. This checklist shows some things the Scrum Master can be working on each day with and around the team: http://scrummasterchecklist.org/pdf/ScrumMaster_Checklist_12_unbranded.pdf
The checklist is by no means comprehensive, but gives a taste of the many things a scrum master can be doing to help the team.

A: The scrum master in such a scenario will need to spend less time with the team, freeing them up to be able to work with two or three teams at the same time.

A: There is more than one question here.
You can check the Scrum website for the 'by the book' definition of the Scrum master role, which includes a whole tonne of general management, consultancy and project management stuff in it. Plenty to fill a FTE.
Then you have the reality of most work places, where the Scrum Master is seen as a consultant position which can be dropped after you have switched from whatever you were doing before to scrum, or filled by a random employee, say the lead dev or a project manager, if you don't want to hire a consultant.
And then you have the career advice aspect 'I'm a scrum master but my team don't need me' question.
I think like any job, the title doesn't really define the role. It's down to the individual to carve a niche in the system.


text:
Q: Join two objects by key I stuck on mergin 2 objects into one. Let's say I have 2 arrays of objects:
One is childs:
let childsWithMoreInfo = [{
  id: 1,
  name: 'somename',
  parent: {
    id: 2
  },
}, {
  id: 2,
  name: 'some child name',
  parent: {
    id: 4
  }
}];

And the second one is Parents:
let parents = [{
  id: 1,
  parentName: 'The first',
  child: {}
}, {
  id: 2,
  parentName: 'The second',
  child: {}
}, {
  id: 3,
  parentName: 'The third',
  child: {}
}, {
  id: 4,
  parentName: 'The fourth',
  child: {}
}];

And I would to merge these objects like this:
        let combined = [
            {
                id: 1,
                parentName: The first,
                child: {}
            },
            {
                id: 2,
                parentName: The second,
                child: {
                    id: 1,
                    name: somename,
                }
            },
            {
                id: 3,
                parentName: The third,
                child: {}
            },
            {
                id: 4,
                parentName: The fourth,
                child: {
                    id: 2
                    name: some child name,
                }
            },

        ]
        ];

So basically it should be something like:
 let combinedList = parents.child = childsWithMoreInfo where parents.id = childsWithMoreInfo.parent.id . On which method I should take a look? Do you have any ideas how can easily achieve that?

A: I really know how to use forEach, I wanted to avoid it.
This is what I made:
    this.combined = _.map(parents, (parent) => {
            parent.child = childs.find(child => child.parent.id === parent.id);
        return parent;
    });

Thank you for all of your answers.

A: You could use a Map and iterate then with Array#forEach for every object.
Then have a lookup in the map and assign the values to ch parent object.

var childsWithMoreInfo = [{ id: 1, name: 'somename', parent: { id: 2 } }, { id: 2, name: 'some child name', parent: { id: 4 } }],
    parents = [{ id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: {} }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: {} }],
    map = new Map;

parents.forEach(p => map.set(p.id, p));
childsWithMoreInfo.forEach(c => {
    var o = map.get(c.parent.id);
    o.child = { id: c.id, name: c.name };
});
console.log(parents);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another solution would be the use of Array#find

var childsWithMoreInfo = [{ id: 1, name: 'somename', parent: { id: 2 } }, { id: 2, name: 'some child name', parent: { id: 4 } }],
    parents = [{ id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: {} }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: {} }];

childsWithMoreInfo.forEach(c => {
    var o = parents.find(p => p.id === c.parent.id);
    o.child = { id: c.id, name: c.name };
});
console.log(parents);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Following code has some pure functions to do your task. I have formatted/cleaned the input objects also:

'use strict';

let childsWithMoreInfo = [{
  id: 1,
  name: 'somename',
  parent: {
    id: 2
  },
}, {
  id: 2,
  name: 'some child name',
  parent: {
    id: 4
  }
}];

let parents = [{
  id: 1,
  parentName: 'The first',
  child: {}
}, {
  id: 2,
  parentName: 'The second',
  child: {}
}, {
  id: 3,
  parentName: 'The third',
  child: {}
}, {
  id: 4,
  parentName: 'The fourth',
  child: {}
}];

function makeObjectFromArray(arr) {
  let obj = {};
  arr.map(function(item) {
    if (obj[item.id] === undefined) {
      obj[item.id] = item
    }
  })
  return obj;
}

function toArray(obj) {
  return Object.keys(obj).map(function(key) {
    return obj[key]
  });
}

function sampleParentChildren(parent, children) {
  let Parent = {};
  if (parent.constructor === Array) {
    Parent = makeObjectFromArray(parent);
  } else {
    Parent = Object.assign({}, parent)
  }
  children.map(function(child) {
    if (Parent[child.parent.id] !== undefined) {
      if (Parent[child.parent.id].child === undefined) {
        Parent[child.parent.id].child = {};
      }
      Parent[child.parent.id].child[child.id] = child
    }

  });
  return Parent;
}
let resampledData = sampleParentChildren(parents, childsWithMoreInfo);
console.log(resampledData, toArray(resampledData));

A: To join the arrays in ES6, you can use the spread operator to join the arrays and just use plain old forEach to deduping. The spread operator is more declarative than Es5's array concatenation methods as mentioned here on MDN
[...parents, ...childsWithMoreInfo]

Here's a working example:

let childsWithMoreInfo = [{
    id: 1,
    name: 'somename',
    parent: {
      id: 2
    },
  }, {
    id: 2,
    name: 'some child name',
    parent: {
      id: 4
    }
  }],
  parents = [{
      id: 1,
      parentName: 'The first',
      child: {}
    }, {
      id: 2,
      parentName: 'The second',
      child: {}
    }, {
      id: 3,
      parentName: 'The third',
      child: {}
    }, {
      id: 4,
      parentName: 'The fourth',
      child: {}
    },

  ];

var conjoined = [...parents, ...childsWithMoreInfo];

conjoined.forEach(function(parentConjoinee, parentIndex) {
  conjoined.forEach(function(childConjoinee, childIndex) {
    if (parentConjoinee.id === childConjoinee.id && parentIndex !== childIndex) {
      conjoined.splice(childIndex, 1);
    }
  });
});

console.log(conjoined);

A: You can use nested for loops, break

var childsWithMoreInfo = [{
  id: 1,
  name: "somename",
  parent: {
    id: 2
  }
}, {
  id: 2,
  name: "some child name",
  parent: {
    id: 4
  }
}];

var parents = [{
    id: 1,
    parentName: "The first",
    child: {}
  }, {
    id: 2,
    parentName: "The second",
    child: {}
  }, {
    id: 3,
    parentName: "The third",
    child: {}
  }, {
    id: 4,
    parentName: "The fourth",
    child: {}
  }

];
let combined = [];
for (var i = 0; i < parents.length; i++) {
  for (var j = 0; j < childsWithMoreInfo.length; j++) {
    if (childsWithMoreInfo[j].parent.id === parents[i].id) {
      parents[i].child.id = childsWithMoreInfo[j].id;
      parents[i].child.name = childsWithMoreInfo[j].name;
      break;
    }
  }
  combined.push(parents[i])
};

console.log(combined);


text:
Q: Is there a way to query for documents that have a certain millisecond in a timestamp? [Mongo] I have a collection on my db with a "created" field that is a timestamp.
What I need to do is somehow get the milliseconds on that timestamp, divide it by 10 and then floor it and THEN match it to a number.
What I'm trying to achieve with this is have a random spread of this documents into "batches" that range from 0-100.
Is there a way to do all this in one query? Basically something like:
Tried aggregation to add that field but then I'm getting all the documents and filtering, was wondering if there's a way to do all this "in-query"
collection.find({<created.convertToMilliseconds.divideByTen>: X }})
// X being any number from 0 to 100

I


text:
Q: How to work around 403 Forbidden so I can view AMP version of page? https://amp.theguardian.com/education/2016/mar/05/harvard-law-school-drops-official-shield-over-slavery-links allows you to view the AMP version of the site on desktop.
But the NYT has blocked AMP pages on desktop (it 403's): http://mobile.nytimes.com/2016/03/05/books/pat-conroy-who-wove-his-family-strife-into-novels-of-carolina-dies-at-70.amp.html
I've tried spoofing the agent in DevTools and even throttling my connection speed, but they're still able to detect I'm on desktop.
Is there anything else I can do? I want to make a Chrome Extension that views the AMP version of all sites that have it available.


text:
Q: How to I read and write a txt file from android 10 and above from internal storage I've been trying to create an app that reads a TXT file from downloads internal storage and puts it into an ArrayList and writes an excel sheet to downloads internal storage from in android but android 10 isn't allowing me to read or write a file. I have already used Environment.getExternalStorageDirectory() but it keeps getting deprecated. Do you guys have any tips or know anyways out of this.

A: use context.getExternalFilesDir() or context.getExternalCacheDir(),these also work in 10. See https://developer.android.com/training/data-storage


text:
Q: Running an NSRunLoop with different dates changes observed thread count While writing an app, I encountered some odd behavior that I wasn't expecting and distilled it down to the following:
I made an app whose main function is as follows. While observing it in Activity Monitor, it uses one thread.
int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        while (YES)
        {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                     beforeDate:[NSDate distantFuture]];
        }
    }

    return 0;
}

If I change [NSDate distantFuture] to [NSDate dateWithTimeIntervalSinceNow:1.0], the app uses ~3 threads. After inspecting this a bit it appears that a dispatch_queue has been implicitly created on my behalf which in turn makes a thread pool.
Just curious: why does this happen? What about [NSDate dateWithTimeIntervalSinceNow:1.0] causes the run loop to create a dispatch_queue?

A: Most likely, an implementation detail and nothing to worry about....
One possibly implementation of distantFuture is "do it forever" and, therefore, no need for a timer like the one w/a specific date.  Given that "timer" might actually be dispatch_after(), that might explain the queue.
Or not.   Interesting question, but likely quite thoroughly irrelevant to your app.


text:
Q: Custom metric not showing up on New Relic I am using the Go's port of newrelic SDK to create custom metric in NR. I was able to create a  new metric for measuring throughput for my app and I am trying to create a metric for average response time.
I have added the necessary code to report the (average response time) data but I do not see it showing up in my new relic when I am trying to create a new graph (The metric does not recognize the custom metric name). However, if I change the GUID (which forces NR to create a new plugin entry), I am able to see the custom metric name in auto complete. I switched back to the old GUID and still I do not see the new custom metric name.
I can always delete the old New Relic Plugin and create a new one with a new GUID but is this really necessary???

A: If you're using GoRelic try clearing the metric data from the New Relic dashboard:

*

*Go to the drop down menu in the top right corner (near your username).

*Click on "Account Settings".

*Go to the "Connected agents" tab.

*Click the red "Clear metric data" button on the right.

That should wipe any stored measurements from your app and may cause it to refresh the metric labels again.

A: Are you attempting to put your Plugin metrics on a Custom Dashboard? https://docs.newrelic.com/docs/dashboards-menu/custom-dashboards
Or, are you attempting to use the new Agent SDK to monitor your Go app?
https://docs.newrelic.com/docs/features/agent-sdk
https://github.com/yvasiyarov/newrelic_go_api


text:
Q: Clear session on browser close,tab close button using c#.net in master pagr i have used following script for clearing the session on browser close button in C#,asp.net but the event  is raised when refresh button raised also How to resolve this please give responce as soon as poossible.
<script type="text/javascript">
       var sessionTimeout = <%= Session.Timeout %>;
        var Content="load";

        var lefttime=sessionTimeout;
        var interval;
        interval = setInterval('change()',60000);

        function change()
        {

           lefttime--;
           if (lefttime <= 1) {
           PageMethods.logOut();
           }

        }
     function divClick1() {
             Content="div";

            }

    window.addEventListener("beforeunload", function (e) {
     if(Content=="load")
      returnValue = PageMethods.logOut();

    });

  </script>

thank you


text:
Q: Change particular characters (escape characters) in a string by using regex or indexOf in Javascript I'm trying to change particular characters such as [ ', ", \ ] because I have a problem during INSERT. For example, the string I'm saying "Hi" will be I\'m saying \"Hi\". So basically this method is adding backslash in front of the characters. But I'm not sure how to do this with regex.
I was thinking to do this with IndexOf but the index of the string is changed when I add the backslash to the string.
Any idea how to do this?

A: This should do exactly what you want:
str = 'I\'m saying "Hi" \\ abc';
str = str.replace(/\\/g, '\\\\').replace(/(['"])/g, '\\$1');

but if you're using SQL, I would really look into prepared statements: https://github.com/felixge/node-mysql#escaping-query-values

A: You can use $1 the $ means "saved group", and 1 means the first saved group:
So:
string.replace( /(['"\\])/g, "\\$1" )

How this works is:
/           Start RegEx
  (         Start "saved" or capturing group
    ['"\\]  Matches any of the characters between []
  )         End "saved" group
/g          End RegEx, g means "global" which means it will match multiple times instead of just the first


text:
Q: How to pass arguments to a named event handler I am aware that you can use a closure and an anonymous function to pass arguments to an event handler, such as in:
function addClick(el, a, b) {
    el.addEventListener('click', function(e) {
        //a and b are available here
    });
}

But the problem is, when you do it this way, you can't remove the event listener since it's anonymous. Might need to both be able to pass arguments and remove the handler at some point, so I was wondering if this is possible in some way, or if there is another method to achieve the same end.
Only thing I can think of is to add properties to the handler and access them that way:
var handler = function() {
    console.log(handler.a);
    console.log(handler.b);
}

handler.a = 'argument1';
handler.b = 'argument2';

el.addEventListener('click', handler);


text:
Q: How to access each numerical element in cv::Point_ type? I have a cv::Rect object. From it, I am getting the bottom right point of the rectangle. I want to separate the point object into two separate int variables. How do I do this?
This is what I have so far:
cv::Rect rectangle;
bottomRight = rectangle.br() // this gives me a Point <int>, such as [545, 364]

I want to separate bottomRight into its two coordinate points as different int variables, such as:
// bottomRight is [545, 364]
bottomRight_x = bottomRight[0] // should be 545
bottomRight_y = bottomRight[1] // should be 364

When I try to subscript, I get this error:

type 'Point_' does not provide a subscript operator

In Python, I would just subscript as above. How do I do this in C++?

A: The x and y ordinates of the cv::Point_<T> structure are stored as public member variables (of type T) called x and y (rather than as a 2-element array).
So, your code should be:
// bottomRight is [545, 364]
bottomRight_x = bottomRight.x;
bottomRight_y = bottomRight.y;

(That is, if you really need to isolate them from the structure itself.)


text:
Q: how to convert unarranged dates to the default date format in R I'm working with hundreds of stores data with R.
And there is store open data.
But it's unarranged, for example "20061019".
I'd like to convert into "YYYY-MM-DD" format.
Plz teach me how to deal with it. thx :)

A: We can use as.Date with format argument (from base R)
as.Date("20061019", format = "%Y%m%d")
#[1] "2006-10-19"

A: One of the ways you can do this is with lubridate ymd function like this
library(lubridate)
ymd("20061019")

A:
paste(substr(aa,1,4),"")
  [1] "2006 " "2016 "
  paste0(substr(aa,1,4),"-",substr(aa,5,6),"-",substr(aa,7,8))
  [1] "2006-10-19" "2016-09-09"


text:
Q: Copy and Past Transpose of a Range Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim book As Workbook: Set book = ThisWorkbook
    Dim myfilename As String
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\Tellurian
    Inc Job Pricing\Job Families and Competencies - Report.xlsm")

    lRow = book.Sheets(2).Cells(Rows.Count, 3).End(xlUp).Row

    book.Sheets(2).Range(Cells(8, 3), Cells(lRow, 3)).Copy
    Report.Sheets(1).Range("B2").PasteSpecial Transpose:=True

End Sub

I'm trying to get this to work so it will copy and paste entered data without having to manually change the code every time new info is added because this will eventually load a bunch of info into a "Report" per se, so manually copy pasting data or changing the code won't be an option. I know the issue is with the lRow in the Copy line of the code, I'm just not sure what it is.

A: Using With

*

*Simplified, everything starting with a dot (".") is referring to the
object in the With statement.

*In your version without the With statement, what ever starts with a
dot (".") should have been preceded by book.Sheets(2)

*Not sure if 'Tellurian Inc' is with or without the SPACE. Correct
if necessary.

The Code
Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\" _
            & "Tellurian Inc Job Pricing\Job Families and Competencies " _
            & "- Report.xlsm")

    With ThisWorkbook.Sheets(2)
        lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        .Range(.Cells(8, 3), .Cells(lRow, 3)).Copy
    End With

    Report.Sheets(1).Range("B2").PasteSpecial Transpose:=True

    Application.CutCopyMode = False

End Sub

EDIT:

*

*You can do the same thing with the other worksheet.

*With .Parent you are referring to a higher level object e.g. you want
to save the changes and close the workbook, but you are referring to
Sheets(1) now, which you cannot close, so with .Parent you refer to the    higher level which is the workbook (Report). For safety reasons I left it commented.

Sub CommandButton2_Click()

    Dim Report As Workbook
    Dim lRow As Long

    Set Report = Workbooks.Open("S:\HR Compensation\Christapher Martin\" _
            & "Tellurian Inc Job Pricing\Job Families and Competencies " _
            & "- Report.xlsm")

    With ThisWorkbook.Sheets(2)
        lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        .Range(.Cells(8, 3), .Cells(lRow, 3)).Copy
    End With

    With Report.Sheets(1)
        .Range("B2").PasteSpecial Transpose:=True
        '.Parent.Close True ' Save changes and close workbook.
    End With

    Application.CutCopyMode = False

End Sub


text:
Q: Background tasks in flask I am writing a web application which would do some heavy work. With that in mind I thought of making the tasks as background tasks(non blocking) so that other requests are not blocked by the previous ones.
I went with demonizing the thread so that it doesn't exit once the main thread (since I am using threaded=True) is finished, Now if a user sends a request my code will immediately tell them that their request is in progress, it'll be running in the background, and the application is ready to serve other requests.
My current application code looks something like this:
from flask import Flask
from flask import request
import threading

class threadClass:

    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                       # Daemonize thread
        thread.start()                             # Start the execution

    def run(self):

         #
         # This might take several minutes to complete
         someHeavyFunction()

app = Flask(__name__)

@app.route('/start', methods=['POST'])
    try:
        begin = threadClass()
    except:
        abort(500)

    return "Task is in progress"

def main():
    """
    Main entry point into program execution

    PARAMETERS: none
    """
    app.run(host='0.0.0.0',threaded=True)

main()

I just want it to be able to handle a few concurrent requests (it's not gonna be used in production)
Could I have done this better? Did I miss anything? I was going through python's multi-threading package and found this

multiprocessing is a package that supports spawning processes using an
API similar to the threading module. The multiprocessing package
offers both local and remote concurrency, effectively side-stepping
the Global Interpreter Lock by using subprocesses instead of threads.
Due to this, the multiprocessing module allows the programmer to fully
leverage multiple processors on a given machine. It runs on both Unix
and Windows.

Can I demonize a process using multi-processing? How can I achieve better than what I have with threading module?
##EDIT
I went through the multi-processing package of python, it is similar to threading.
from flask import Flask
from flask import request
from multiprocessing import Process

class processClass:

    def __init__(self):
        p = Process(target=self.run, args=())
        p.daemon = True                       # Daemonize it
        p.start()                             # Start the execution

    def run(self):

         #
         # This might take several minutes to complete
         someHeavyFunction()

app = Flask(__name__)

@app.route('/start', methods=['POST'])
    try:
        begin = processClass()
    except:
        abort(500)

    return "Task is in progress"

def main():
    """
    Main entry point into program execution

    PARAMETERS: none
    """
    app.run(host='0.0.0.0',threaded=True)

main()

Does the above approach looks good?

A: Best practice
The best way to implement background tasks in flask is with Celery as explained in this SO post. A good starting point is the official Flask documentation and the Celery documentation.
Crazy way: Build your own decorator
As @MrLeeh pointed out in a comment, Miguel Grinberg presented a solution in his Pycon 2016 talk by implementing a decorator. I want to emphasize that I have the highest respect for his solution; he called it a "crazy solution" himself. The below code is a minor adaptation of his solution.
Warning!!!
Don't use this in production! The main reason is that this app has a memory leak by using the global tasks dictionary. Even if you fix the memory leak issue, maintaining this sort of code is hard. If you just want to play around or use this in a private project, read on.
Minimal example
Assume you have a long running function call in your /foo endpoint. I mock this with a 10 second sleep timer. If you call the enpoint three times, it will take 30 seconds to finish.
Miguel Grinbergs decorator solution is implemented in flask_async. It runs a new thread in a Flask context which is identical to the current Flask context. Each thread is issued a new task_id. The result is saved in a global dictionary tasks[task_id]['result'].
With the decorator in place you only need to decorate the endpoint with @flask_async and the endpoint is asynchronous - just like that!
import threading
import time
import uuid
from functools import wraps

from flask import Flask, current_app, request, abort
from werkzeug.exceptions import HTTPException, InternalServerError

app = Flask(__name__)
tasks = {}

def flask_async(f):
    """
    This decorator transforms a sync route to asynchronous by running it in a background thread.
    """
    @wraps(f)
    def wrapped(*args, **kwargs):
        def task(app, environ):
            # Create a request context similar to that of the original request
            with app.request_context(environ):
                try:
                    # Run the route function and record the response
                    tasks[task_id]['result'] = f(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['result'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['result'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task': threading.Thread(
            target=task, args=(current_app._get_current_object(), request.environ))}
        tasks[task_id]['task'].start()

        # Return a 202 response, with an id that the client can use to obtain task status
        return {'TaskId': task_id}, 202

    return wrapped

@app.route('/foo')
@flask_async
def foo():
    time.sleep(10)
    return {'Result': True}

@app.route('/foo/<task_id>', methods=['GET'])
def foo_results(task_id):
    """
        Return results of asynchronous task.
        If this request returns a 202 status code, it means that task hasn't finished yet.
        """
    task = tasks.get(task_id)
    if task is None:
        abort(404)
    if 'result' not in task:
        return {'TaskID': task_id}, 202
    return task['result']

if __name__ == '__main__':
    app.run(debug=True)

However, you need a little trick to get your results. The endpoint /foo will only return the HTTP code 202 and the task id, but not the result. You need another endpoint /foo/<task_id> to get the result. Here is an example for localhost:
import time
import requests

task_ids = [requests.get('http://127.0.0.1:5000/foo').json().get('TaskId')
            for _ in range(2)]
time.sleep(11)
results = [requests.get(f'http://127.0.0.1:5000/foo/{task_id}').json()
           for task_id in task_ids]
# [{'Result': True}, {'Result': True}]


text:
Q: Show image view intent with universal image loader I'm trying to start a image viewing application after loading the images with UIL. However, when I click the imageview, it shows a blank picture and gives me an exception:
05-25 18:34:44.908    1299-1386/com.android.gallery E/UriImage﹕ got exception decoding bitmap
    java.lang.NullPointerException
            at com.android.camera.Util.makeInputStream(Util.java:336)
            at com.android.camera.Util.makeBitmap(Util.java:307)
            at com.android.camera.Util.makeBitmap(Util.java:299)
            at com.android.camera.gallery.UriImage.fullSizeBitmap(UriImage.java:94)
            at com.android.camera.gallery.UriImage.fullSizeBitmap(UriImage.java:86)
            at com.android.camera.gallery.UriImage.thumbBitmap(UriImage.java:120)
            at com.android.camera.ImageGetter$ImageGetterRunnable.executeRequest(ImageGetter.java:173)
            at com.android.camera.ImageGetter$ImageGetterRunnable.run(ImageGetter.java:149)
            at java.lang.Thread.run(Thread.java:841)
05-25 18:34:44.908    1299-1386/com.android.gallery E/UriImage﹕ got exception decoding bitmap
    java.lang.NullPointerException
            at com.android.camera.Util.makeInputStream(Util.java:336)
            at com.android.camera.Util.makeBitmap(Util.java:307)
            at com.android.camera.Util.makeBitmap(Util.java:299)
            at com.android.camera.gallery.UriImage.fullSizeBitmap(UriImage.java:94)
            at com.android.camera.ImageGetter$ImageGetterRunnable.executeRequest(ImageGetter.java:204)
            at com.android.camera.ImageGetter$ImageGetterRunnable.run(ImageGetter.java:149)
            at java.lang.Thread.run(Thread.java:841)

Here is my image click listener:
   @Override
            public void onLoadingComplete(final String s, View view, Bitmap bitmap) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        File imageFile = DiscCacheUtil.findInCache(s, imageLoader.getDiscCache());
                        intent.setDataAndType(Uri.fromFile(imageFile),"image/*");
                        context.startActivity(intent);
                    }
                });
            }

UIL options:
options = new DisplayImageOptions.Builder()
        .showImageOnFail(android.R.drawable.ic_delete)//display stub image untiL image is loaded
        .cacheInMemory(true)
        .cacheOnDisc(true)
        .displayer(new RoundedBitmapDisplayer(10))
        .build();


text:
Q: How to create multiple environments using AWS amplify my app uses vue3, vuetify and amplify with rest api, dynamodb. Things were working as expected until I started getting errors in API calls that I couldn't explain. I deleted the "dev" enviornment using AWS console. When I tried to recreate the env using "amplify push", I got error saying "The specified bucket does not exist". So, I created a new env called "test" using "amplify init". Now "amplify push" is successful but the vue app seems to be pointing to older "dev" config.
I have two questions.
First, any thoughts on why I got "bucket doesn't exist" error.
Second, how do I get the vue app to use the new config that matches "test" env

A: It's actually very simple:
Goal: Have 1 environment for production and 1 environment for us to develop.

*

*Create a new environment by doing: amplify env add, when prompted with "Select the authentication method you want to use", use "Amplify Admin UI". Give this env the name "prod"

*Delete previous environment (ONLY IF YOU NEED TO DELETE IT) with name "staging, by typing amplify console and selecting "amplify console":

*Create a new environment by doing: amplify env add and give this env the name "dev"

When ever you create a new environment, you switch to it automatically. You can check your current env, by doing Amplify status
Source and more info about managing the environment: Here


text:
Q: printing a signed integer optimization There's this unanswered question in the Igor Zhirkov's book Low-Level Programming :
"Try to rewrite print_int without calling print_uint, copying its code, or using jmp. You will
only need one instruction and a careful code placement.
Read about co-routines.".
The supplied code for "print_int" and "print_uint":
print_uint:
    mov rax, rdi
    mov rdi, rsp
    push 0
    sub rsp, 16

    dec rdi
    mov r8, 10

.loop:
    xor rdx, rdx
    div r8
    or  dl, 0x30
    dec rdi
    mov [rdi], dl
    test rax, rax
    jnz .loop

    call print_string

    add rsp, 24
    ret

print_int:
    test rdi, rdi
    jns print_uint
    push rdi
    mov rdi, '-'
    call print_char
    pop rdi
    neg rdi
    jmp print_uint

print_char:
    push rdi
    mov rdi, rsp
    call print_string
    pop rdi
    ret
print_string:
    push rdi
    call string_length
    pop rsi
    mov rdx, rax
    mov rax, 1
    mov rdi, 1
    syscall
    ret

What could be that special single instruction he's talking about ?

A: I am so sorry, but it is unfortunately an error.
There is a pair of functions print_newline and print_char where print_newline can be expressed as one instruction if the control falls to print_char afterwards. I wrote a blog post about it. The basic idea is that printing a specific character i.e. the newline feed is like starting the "print any character" subroutine when its argument is assigned the code of the said character.
print_newline:
   mov rdi, '\n'  ; first integer argument is in rdi
print_char:
   ...

As to print_int I am sure that on AMD64 you can not express it through one instruction and fall to print_uint.


text:
Q: How to understand complex rotation? I come across A Visual, Intuitive Guide to Imaginary Numbers, and find it's difficult for me to understand this section:

Let's take a look. Suppose I'm on a boat, with a heading of 3 units East for every 4 units North. I want to change my heading 45 degrees counter-clockwise. What's the new heading?
......
Let's try a simpler approach: we're on a heading of 3 + 4i (whatever that angle is; we don't really care), and want to rotate by 45 degrees. Well, 45 degrees is 1 + i (perfect diagonal), so we can multiply by that amount!

Per my understanding, rotation should not change the distance from 0, but it's obviously the distance of 3 + 4i isn't same with -1 + 7j. How to understand complex rotation?

A: I'd suggest you to familiarize with a polar form of a complex number (see at Wikipedia), defined by an Euler's formula:
$$m(\cos \varphi + i\sin\varphi) = m\,e^{i\varphi}$$
where $m$ is a magnitude of the complex number (i.e. the corresponding vector's length) and $\varphi$ is its argument (i.e. the angle from the real axis).
Then, applying standard laws of multiplication of products and powers:
$$z_1 \cdot z_2 = |z_1|e^{i\varphi_1} \cdot |z_2|e^{i\varphi_2} = |z_1|\,|z_2|\cdot e^{i(\varphi_1 + \varphi_2)}$$
a product of two numbers has a magnitude being a product of magnitudes of the two terms, and an argument being a sum of their arguments.
Your number $(1+i)$ has a magnitude $\sqrt{1^2+1^2} = \sqrt 2$ and argument $\arctan \frac 11 = 45^\circ$, hence in multiplication of $(3+4i)$ by $(1+i)$ the vector representing a product is longer than that of $(3+4i)$ by a factor of $\sqrt 2$ and rotated by $45^\circ$.

A: They are only interested in the angle. If you want to preserve the magnitude, you must multiply by a complex number of absolute value one; in this example, you should take $(1+i)/\sqrt2$.


text:
Q: Группировка записи в файл-текстовик с временным разделением в 3 часа Всем привет, я пишу участок кода, который будет собирать инфу по логам раскидывая по папкам ../дата/файл(11:00:00- 14:00:00).txt;
у меня получился такой участок кода:
DirectoryInfo dir = new DirectoryInfo(@"logger");
        if (!dir.Exists)
        {
            dir.Create();
        }

        var data = Console.ReadLine();

        DirectoryInfo directory = new DirectoryInfo(@$"logger/{DateTime.UtcNow.ToShortDateString()}");
        if (!directory.Exists)
        {
            directory.Create();
        }

        File.AppendAllText(@$"logger/{DateTime.UtcNow
            .ToShortDateString()}/{DateTime.UtcNow
            .ToShortTimeString().Replace(':', '.')} - {DateTime
            .UtcNow.AddHours(3)
            .ToShortTimeString()
            .Replace(':', '.')}.txt", data + " \n", Encoding.UTF8);
    }

И у меня есть вопрос, как в течение 3 часов записывать в один и тот же файл? тоесть что бы не создавался ../дата/12:01:00 - 15:01:00.txt , 12:02:00 - 15:02:00.txt . Короче чтобы данные записывались не раздельно, а в один и тот же файл на промежутке 12:01:00 - 15:01:00.txt

A: Я бы первым делом так не делал, а искал бы готовые логгеры.
Но если вы настроены серьезно такое писать руками, но в таких случаях надо нормализовать время. Например
string GetLogFilename(DateTime dt)
{
    var newDateTime = new DateTime(dt.Year, dt.Month, dt.Day, (dt.Hour / 3) * 3, 0, 0, 0, dt.Kind);
    return newDateTime.ToString("yyyy_MM_dd_HH") + ".log";
}

Проверить это можно так
for (int i = 0; i < 30; i++)
{
    Console.WriteLine($"{DateTime.Now.AddHours(i).ToString("yyyy_MM_dd_HH")} - {GetLogFilename(DateTime.Now.AddHours(i))}");
}

Вывод
2021_02_24_13 - 2021_02_24_12.log
2021_02_24_14 - 2021_02_24_12.log
2021_02_24_15 - 2021_02_24_15.log
2021_02_24_16 - 2021_02_24_15.log
2021_02_24_17 - 2021_02_24_15.log
2021_02_24_18 - 2021_02_24_18.log
2021_02_24_19 - 2021_02_24_18.log
2021_02_24_20 - 2021_02_24_18.log
2021_02_24_21 - 2021_02_24_21.log
2021_02_24_22 - 2021_02_24_21.log
2021_02_24_23 - 2021_02_24_21.log
2021_02_25_00 - 2021_02_25_00.log
2021_02_25_01 - 2021_02_25_00.log
2021_02_25_02 - 2021_02_25_00.log
2021_02_25_03 - 2021_02_25_03.log
2021_02_25_04 - 2021_02_25_03.log
2021_02_25_05 - 2021_02_25_03.log
2021_02_25_06 - 2021_02_25_06.log
2021_02_25_07 - 2021_02_25_06.log
2021_02_25_08 - 2021_02_25_06.log
2021_02_25_09 - 2021_02_25_09.log
2021_02_25_10 - 2021_02_25_09.log
2021_02_25_11 - 2021_02_25_09.log
2021_02_25_12 - 2021_02_25_12.log
2021_02_25_13 - 2021_02_25_12.log
2021_02_25_14 - 2021_02_25_12.log
2021_02_25_15 - 2021_02_25_15.log
2021_02_25_16 - 2021_02_25_15.log
2021_02_25_17 - 2021_02_25_15.log
2021_02_25_18 - 2021_02_25_18.log


text:
Q: Passing props on a button? Is it possible? I have this button going this this link and I need to pass props to the link component, specifically currentUserProfile and selectedUserProfile, how can I do this?
<Button
    content='Private messages'
    color='green'
    as={Link}
    to={`/messages/${currentUserProfile.id}/${selectedUserProfile.id}`}
/>

this is the route
<Route
    path='/messages/:currentUser/:currentProfile'
    component={PrivateMessages}
/>

A: you can do something like this
function Button(props) {
  const { content, color } = props
  return (
    <div>
      {props.children}
    </div>
  )
}

then the place where you calling you component you can do something like
function SomeComponent(){
 return(
  <Button content='Private messages' color='green'>
     <Link to=`/messages/${currentUserProfile.id}/${selectedUserProfile.id}`>Link Here </Link>
  <Button>)
}


text:
Q: Client side Data Annotation validation on a button click using Jquery I have a model which has Required attributes in it. Is it possible to do data validation on a button click which is not of type submit. I did refer to this article and this one but it did not solve the issue.
Here's my model code.
 [Required]
 [Display(Name = "Number of beds")]
 public int Beds { get; set; }
 [Required]
 [Display(Name = "Number of Inpatient Beds")]
 public int InpatientBeds { get; set; }

My View
@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{

                @Html.LabelFor(m => m.Beds)
                @Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.Beds)

                @Html.LabelFor(m => m.InpatientBeds)
                @Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.InpatientBeds)

            <button type=button  class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>

        <button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"> Update Status</button>

}

And my script
$('#btnCalculateScore').on('click', function (evt) {

evt.preventDefault();

if ($('#form1').valid()) {
    //Do Something.
}
}

The validations do not work and the control enters the if loop even though the fields are empty? Is there something I am missing? Also does this approach also give out the validation messages which normally happen on a submit button event?
EDIT :

*

*I added a normal Update Status button with type submit and the validations work there fine.

*I added the id to my form to ensure it does not matter if the View contains another forms.

A: I had the same issue and this seemed to resolve it for me.
@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))

On seeing the page source, this code does not attach the id Form1 to your form. Hence your validation will not happen as the form with id form1 is not found.
Instead,assuming your operation is a post and you are saving the data in say Action Method Save and controller Bed you can edit the form to
@using (Html.BeginForm("Save", "Bed", FormMethod.Post, new { id = "form1",@class = "form-horizontal"}))

This will attach the id parameter to your form(you can check using ViewPageSource) and it should work. There might be a better solution to this, but this worked properly for me without issues.


text:
Q: (PyMongo) "nosqlbooster for mongodb" can connect mongoDB server by ip address, I want pyMongo do the same thing, and how "nosqlbooster for mongodb" can connect mongoDB server by ip address, can pyMongo do the same thing??
and how
I want to use pyMongo  to connect mongoDB by ip address
my .py code isn't working (ps. x for cover the actuall ip address)
import pymongo

client = pymongo.MongoClient("mongodb://196.168.xxx.xxx:27017/")

mydb_Name="cloud_db"

mydb = client[mydb_Name]

print("now exsisting DB are:  ",client.list_database_names())

dblist = client.list_database_names()
if mydb_Name in dblist:
  print("Your DB: {0}exsist!!!!".format(mydb_Name))

#the "cloud_db" already exsist in picture I showed,
# #so should list up all DB the ip address has

the NoSQLBooster picture,
https://ibb.co/MfTJXk0
I connect successfully just by the same IP address196.168.xxx.xxx
but using the pymongo code with the same IP address just could't do it, can expert tell me the reson or how to solve, thanks


text:
Q: How to pass a parameters to this jquery? i dont have a clue how i should rewrite this jquery so i can pass parameters into it. i want to pass an id into the function so i place it like, $(".dialog" + id).
i am goin to trigger it with a
$(document).ready(function() {
  $(".btnCheck").live("click", function(evt) {
    evt.preventDefault();
    $(".dialog").dialog({
      height: 700,
      width: 600,
      closeOnEscape: true,
      title: 'prev'
    }).dialog("open");
  });
});

A: assuming that what you want is the ID of "btnCheck.
$(document).ready(function() {
        $(".btnCheck").live("click", function(evt) {
            evt.preventDefault();

            $(".dialog" + $(this).attr("id")).dialog({ height: 700, width: 600, closeOnEscape: true, title: 'prev' }).dialog("open");
        });
    });

A: Assuming:
<input type="button" class="btnCheck" id="btn1" value="Click Me">
...

  ...

you can do:
$(function() {
  $(":button.btnCheck").live("click", function(e) {
    $("#dialog-" + this.id).dialog({...});
    e.preventDefault();
  });
});

You'll note that instead of using a dynamic class name, I gave the div a class of dialog. To get a specific one, since you will only ever want one (at a time), an ID is a better choice (imho).
this within this event handler refers to the button that was clicked ie the source of the event.

A: You need to associate your buttons with you dialogs somehow.
If you give the buttons a class of button and the dialogs a class dialog. You can then get all this into an array and loop through them the first button in the array will activate the dialog which has an id of dialog1.


text:
Q: Kohana (ORM) - how to find record from 2 tables class Model_Category extends ORM
{
    protected $_has_many = array(
        'film' => array('through' => 'films_categories')
    );
}

class Model_Film extends ORM
{
    protected $_has_many = array(
        'categories' => array(
            'through' => 'films_categories'
        ),
}

films
-id (pk)
-title
-description

categories
-id (pk)
-name

films_categories
-film_id
-category_id

This is how my tables looks and here is what I need to do:
$films->ORM::factory('film');
$films
    ->where('title', '=', $my_title)
    ->and_where('any of categories name', '=', $category_name)
    ->find_all();

I need to find record that has $my_category='any of categories from category table'. Any simple way to do this?

A: So you're trying to get a movie by its title and category?
I'd leave ORM for this query alone, since you won't benefit from it more then from query builder:
$films = DB::select()
    ->from('films')
    ->where('title', '=', $my_title)
    ->and_where($category_name, 'IN', DB::select()->from('categories')->execute()->as_array('id', 'name'))
    ->execute();

A: I found an answer. It's little different, because I wanted to find movie by its category name (or by many category names). I found easier to find movie by its category_id. If someone would find it helpfull here it is:
$category_id = 13;

$films = ORM::factory('film')
            ->select('category_id')
            ->join('films_categories')
            ->on('films_categories.film_id', '=', 'film.id')
            ->where('category_id', '=', $category_id)
            ->find_all();

foreach($films as $f)
    echo $f->title . " " . $f->category_id . "<br/>";

I dont know how it exactly works, but it is. I invented this by accident.
And if someone could tell me why this line is needed:
->select('category_id')

or
->select('*')

without this line it gives and error:
Kohana_Exception [ 0 ]: The category_id property does not exist in the Model_Film class

why join() doesn't join whole tables without select('*') ?

A: If you still want to filter out films by category name this should work:
$films = ORM::factory('film')
    ->join('films_categories')->on('films_categories.film_id', '=', 'film.id')
    ->join(array('categories', 'category'))->on('category.id', '=', 'films_categories.category_id')
    ->where('film.title', '=', $film_title)
    ->where('category.name', '=', $category_name)
    ->find_all();

And I guess you need
->select('category_id')

in your query, cause you don't specify column table in your where statement. Like this:
->where('films_categories.category_id', '=', $category_id)


text:
Q: pandas: set a column as horizontal axis I have the following row dataset that is containing disparate dates.
         Id       Date  Quantity
0  122222ST 2020-10-19      -1.0
1  122222ST 2020-10-22     75.0
2  122222ST 2020-10-22    1100.0
3    100128 2020-10-20       5.0

that I want to turn into a time serie for each Id such that every dates are here, if an Id has multiple for a date, they add up, and if there is none, it shows a 0. a minimal reproducible example would like this:
Date        122222ST 100128

2020-10-19  -1.0      0
2020-10-20   0        5
2020-10-21   0        0
2020-10-22   1175     0

I have been able to do this so far:
#read data
df = pd.read_csv('historical_data2.csv', sep=";")

#remove unwanted column
df = df.drop('NetAmount',axis=1)

#set date to datetime
df['Date'] = pd.to_datetime(df['Date'])

#get unique Ids and sum quantities per date
df = df.groupby(['Id', 'Date']).agg({'Quantity':'sum'}).reset_index()

#adding all missing dates
df = df.groupby(pd.Grouper(key='Date', freq='D'))

From this point on I am stuck because I cannot find a way to set Id values as the horizontal index. I have seen this example Python Pandas: How to set Dataframe Column value as X-axis labels but it regards plotting which I am interested in. Any clue?

A: You can do it with a pivot_table:
import pandas as pd
import numpy as np

data={"Id":["122222ST",'122222ST','122222ST','100128'],
        "Date":['2020-10-19','2020-10-22','2020-10-22','2020-10-20'],
        "Quantity": [-1,75,1100,50]}

df = pd.DataFrame(data)
df["Date"]=pd.to_datetime(df["Date"], format="%Y-%m-%d")
new_df= pd.pivot_table(df, values='Quantity', index=['Date'],
                    columns=['Id'], aggfunc=np.sum,fill_value=0)

#for missing days (e.g 2020-10-21)
df_Date=pd.date_range(start=new_df.index.min(), end=new_df.index.max(), freq='d')
new_df=new_df.reindex(df_Date,fill_value=0)

print(new_df)

result:
Id          100128  122222ST
2020-10-19       0        -1
2020-10-20      50         0
2020-10-21       0         0
2020-10-22       0      1175

A: The operation to make the values of a column your new columns is called pivot. You have the additional complication that you want to sum quantities if they happen on the same day. This must be done before the pivot operation.
Your solution
df = df.groupby(['Id', 'Date']).agg({'Quantity':'sum'}).reset_index()

should give the same result but
In [11]: df.groupby(['Id', 'Date']).sum().reset_index()
Out[11]:
         Id        Date  Quantity
0    100128  2020-10-20       5.0
1  122222ST  2020-10-19      -1.0
2  122222ST  2020-10-22    1175.0

is a bit shorter
Then you can just apply pivot to the result and use fillna to set the not specified values to 0:
In [10]: df.groupby(['Id', 'Date']).sum().reset_index().pivot(index='Date', columns='Id').fillna(0)
Out[10]:
           Quantity
Id           100128 122222ST
Date
2020-10-19      0.0     -1.0
2020-10-20      5.0      0.0
2020-10-22      0.0   1175.0


text:
Q: Get user data from stackoverflow using meteor I'm trying to develop a meteor application and in that i want to get the data of a user from stackoverlow.
Suppose, My username is
https://stackoverflow.com/users/1934044/user1934044
When user enters this link in my textbox i want to get the info about this user
For this, Do we need to register an application in stack apps or we can directly get the data from stackexchange api.
I'm not using the stackexchange login system(OAUTH) in my app.
If we can directly get the data, how to do it
Can someont point me to the tutorial

A: You can get User Details by user ID with following methods endpoint :

*

*/users/{ids}

For more details, Refer below Stack Exchange Document
https://api.stackexchange.com/docs/users-by-ids
Or
I have written Java Wrapper over Stack Exchange API.
You can try it out. https://github.com/sanjivsingh/stackoverflow-java-sdk
Sample code :
StackExchangeApiQueryFactory queryFactory  = StackExchangeApiQueryFactory.newInstance();
System.out.println("get user by Id");
PagedList<User> users = queryFactory.newUserApiQuery()
        .withUserIds(1934044).listUserByIds();

Coming back to your question :

*

*You need not register application for that.

*This method will work without any applicationKey and accessToken

A: You can use the Meteor Http package for this to call the api and get the data as json object.
Eg:
On server,
return Meteor.methods({

    getUserData: function (user_id) {
        var url =   "give the api url"+user_id;
        this.unblock();
        return Meteor.http.get(url);
    }

});


text:
Q: Monthly statistics based on raster file name I have a raster of a national park in Norway showing the temperature every day between the 1st of November 1999 and the 31st March 2015. I have created booleon images showing which pixels are above zero and which are below zero. I now want to go through the folder and sum up how many times each pixel has a temperature above zero each month. The file format is rr_YYYY_MM_DD.tif I tried adapting a script I found here (https://geonet.esri.com/thread/70044) to do this based on the file name, but I get the error message
"[function] + Utils.flattenLists(in_rasters_or_constants))"
when I try to run it.
The code is below.
import arcpy
arcpy.CheckOutExtension("Spatial")
arcpy.env.workspace = r"G:\Hardangervidda\Suitable pixels\Precipitation_3mm"
outWks = r"G:\Hardangervidda\Suitable pixels\monthly_stats"
for year in range(1999,2015):  # 1999 through 2015
    for month in range(13):      # 1 to 12
        # wildcard - "rr_YYYY_MM*.tif" (format month 1 -> "01")
        wild = "rr_{0}_{1:02d}*.tif".format(year,month)
        rasList = arcpy.ListRasters(wild) # list all rasters for a month
        outRas = arcpy.sa.CellStatistics(rasList,"SUM") # monthly mean
        outPath = outWks + "/" + "m{0}m{1:02d}".format(year,month)
        outRas.save(outPath)

A: I've just run
for month in range(13):
print month

and the output starts in 0 up to 12, then your ListRaster contains no raster. It's empty. I believe that's why the CellStatistics function crashes. If you change that to
for month in range(1,13):

will run ok.

A: Your wildcard many not be working as expected.
Instead of
wild = "rr_{0}_{1:02d}*.tif".format(year,month)

try this:
wild = "rr_{0}_{1:02d}_??.tif".format(year,month)


text:
Q: .NET Remoting callback Is it possible to transmit a callback via remoting? I'd like to do something along the lines of myRemoteObject.PerformStuff( x => Console.WriteLine(x) );
If not, how would I implement a equivalent functionality?
Edit: I'm aware Remoting got superseded by WCF, but I'm still interested in this specific case. (Out of curiosity though, how's the issue in WCF?)

A: Important to add that you need to register duplex channels, not just a server or a client.
Otherwise the callback will not work.
E.g. TcpChannel/HttpChannel/IpcChannel and NOT TcpServerChannel/TcpClientChannel and so on.
For firewalled solutions make sure that the callback port is opened on the 'client' for both TCP and HTTP channels (IPC does not use ports).

A: Remoting provides support for events. The client code can simply subscribe to an event that's exposed by the server class. (There are a large list of caveats here).
Also, you can pass a callback interface to a remote class, providing your implementation of the interface is a MarshalByRef object.
interface IMyCallback
{
      void OnSomethingHappened(string information);
}

class MyCallbackImplementation : MarshalByRefObject, IMyCallback
{
    public void OnSomethingHappened(string information)
    {
        // ...
    }

}

class MyServerImplementation : MarshalByRefObject
{
     List<IMyCallback> _callbacks = new List<IMyCallback>();

     public void RegisterCallback(IMyCallback _callback)
     {
           _callbacks.Add(_callback);
     }

     public void InvokeCalbacks(string information)
     {
         foreach(IMyCallback callback in _callbacks)
         {
              _callback.OnSomethingHappened(information);
         }
     }

}

A: In WCF you use callback operations. If you can use WCF or remoting, choose WCF. Remoting is classed as legacy.


text:
Q: Hide/show div based on search input I have worked out some javascript to use my search bar in order to filter/hide things that don't match the search input. I've got it working about 95% I would say but I have one problem to fix.
So my page displays furniture groups and their containing pieces of furniture. The group name/number and description exists as a heading div and below that there is a table created with the actual pieces of furniture. My current javascript works as long as I'm typing 'sofa' or 'chair' which would be in the table row. However, If I type the name of a furniture group, it just shows the name/number/description and images, but hides the table. The group names/descriptions are in this block:
@foreach ($orderFormData->pgroups as $pgroup)

{{ $pgroup->group_name
}} - {{ $pgroup->group_code }}

{!!
html_entity_decode($pgroup->group_desc) !!}

So, I need to try and slightly refactor this to add the functionality so that if my input matches the group name or description, it still shows the whole table for that div.
An idea I had was to add something like this

Under my first line of html below, right under the foreach loop. But I don't know if that would be the right idea or how to use that exactly the way it should.
HTML:
@foreach ($orderFormData->pgroups as $pgroup)

{{ $pgroup->group_name }} - {{ $pgroup->group_code }}

{!! html_entity_decode($pgroup->group_desc) !!}

                    @foreach ($pgroup->image_names as $image_name)

{{ substr($image_name, strpos( $image_name, ',') + 1)  }}

                    @endforeach

                        Frame
                        Description
                        Cover/Color
                        Cover/Color
                        Quantity
                        Price

                    @foreach ($pgroup->pskus as $psku)
                    <?php $tempdata['sku-' . $i] = $psku ?>

quantity) && $psku->quantity > 0) {{ highlight }} @endif">
                        {{ $psku->frame_fmt }}
                        {!! html_entity_decode($psku->frame_desc) !!}
                        {{ $psku->cover1_code }}/{{ $psku->color1_code }} {{ $psku->color1_desc }}
                        {{ $psku->cover2_code }}/{{ $psku->color2_code }} {{ $psku->color2_desc }}

                            ${{ $psku->price }}

                    <?php $i++; ?>
                    @endforeach

@endforeach

JS:

A: You could search the groups first and if the name/description matches, show the whole group and all it's rows. Otherwise do the usual procedure.


text:
Q: Remove text between () and [] I have a very long string of text with () and [] in it. I'm trying to remove the characters between the parentheses and brackets but I cannot figure out how.
The list is similar to this:
x = "This is a sentence. (once a day) [twice a day]"

This list isn't what I'm working with but is very similar and a lot shorter.

A: You can split, filter, and join the string again. If your brackets are well defined the following code should do.
import re
x = "".join(re.split("\(|\)|\[|\]", x)[::2])

A: Run this script, it works even with nested brackets.
Uses basic logical tests.
def a(test_str):
    ret = ''
    skip1c = 0
    skip2c = 0
    for i in test_str:
        if i == '[':
            skip1c += 1
        elif i == '(':
            skip2c += 1
        elif i == ']' and skip1c > 0:
            skip1c -= 1
        elif i == ')'and skip2c > 0:
            skip2c -= 1
        elif skip1c == 0 and skip2c == 0:
            ret += i
    return ret

x = "ewq[a [(b] ([c))]] This is a sentence. (once a day) [twice a day]"
x = a(x)
print x
print repr(x)

Just incase you don't run it,
Here's the output:
>>>
ewq This is a sentence.
'ewq This is a sentence.  '

A: You can try this. Can remove the bracket and the content exist inside it.
 import re
    x = "This is a sentence. (once a day) [twice a day]"
    x = re.sub("\(.*?\)|\[.*?\]","",x)
    print(x)

Expected ouput :
This is a sentence.

A: For anyone who appreciates the simplicity of the accepted answer by jvallver, and is looking for more readability from their code:
>>> import re
>>> x = 'This is a sentence. (once a day) [twice a day]'
>>> opening_braces = '\(\['
>>> closing_braces = '\)\]'
>>> non_greedy_wildcard = '.*?'
>>> re.sub(f'[{opening_braces}]{non_greedy_wildcard}[{closing_braces}]', '', x)
'This is a sentence.  '

Most of the explanation for why this regex works is included in the code. Your future self will thank you for the 3 additional lines.
(Replace the f-string with the equivalent string concatenation for Python2 compatibility)

A: Here's a solution similar to @pradyunsg's answer (it works with arbitrary nested brackets):
def remove_text_inside_brackets(text, brackets="()[]"):
    count = [0] * (len(brackets) // 2) # count open/close brackets
    saved_chars = []
    for character in text:
        for i, b in enumerate(brackets):
            if character == b: # found bracket
                kind, is_close = divmod(i, 2)
                count[kind] += (-1)**is_close # `+1`: open, `-1`: close
                if count[kind] < 0: # unbalanced bracket
                    count[kind] = 0  # keep it
                else:  # found bracket to remove
                    break
        else: # character is not a [balanced] bracket
            if not any(count): # outside brackets
                saved_chars.append(character)
    return ''.join(saved_chars)

print(repr(remove_text_inside_brackets(
    "This is a sentence. (once a day) [twice a day]")))
# -> 'This is a sentence.  '

A: You can use re.sub function.
>>> import re
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)
'This is a sentence. () []'

If you want to remove the [] and the () you can use this code:
>>> import re
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("[\(\[].*?[\)\]]", "", x)
'This is a sentence.  '

Important: This code will not work with nested symbols
Explanation
The first regex groups ( or [ into group 1 (by surrounding it with parentheses) and ) or ] into group 2, matching these groups and all characters that come in between them. After matching, the matched portion is substituted with groups 1 and 2, leaving the final string with nothing inside the brackets. The second regex is self explanatory from this -> match everything and substitute with the empty string.
-- modified from comment by Ajay Thomas

A: This should work for parentheses. Regular expressions will "consume" the text it has matched so it won't work for nested parentheses.
import re
regex = re.compile(".*?\((.*?)\)")
result = re.findall(regex, mystring)

or this would find one set of parentheses, simply loop to find more:
start = mystring.find("(")
end = mystring.find(")")
if start != -1 and end != -1:
  result = mystring[start+1:end]

A: The RegEx \(.*?\)|\[.*?\] removes bracket content by finding pairs, first it remove paranthesis and then square brackets. I also works fine for the nested brackets as it acts in sequence. Ofcourse, it would break in case of bad brackets scenario.

    _brackets = re.compile("\(.*?\)|\[.*?\]")
    _spaces = re.compile("\s+")

    _b = _brackets.sub(" ", "microRNAs (miR) play a role in cancer ([1], [2])")
    _s = _spaces.sub(" ", _b.strip())
    print(_s)

    # OUTPUT: microRNAs play a role in cancer


text: Q: Local spectrum of a non-stationary gaussian process The Wiener–Khinchin theorem states that, for stationary processes, the covariance is the Fourier dual of the spectral density. I'm wondering if this statement is true for non-stationary processes if, say, the process only changes slowly. Within some range in which the process is mostly stationary, does the spectral density relate to the covariance?


text:
Q: Как правильно в nodejs (express-mongoose) передавать данные в поле select Только недавно начал изучать node js. Помогите решить такую задачу:
Есть к примеру таблицы валюта и кошельки, для кошелька указано поле с типов "Валюта".
Нужно что бы при редактировании кошелька, в поле валюта можно было выбрать данные только с таблицы "Валюта". Как это делать в общем, я понимаю (найти все валюты Currency.find({},...) и передать в ejs). Проблема в том что таких таблиц и полей много, поэтому хотелось бы знать как это правильно делается?
Вот как сейчас сделано у меня, но мне кажется что здесь сам подход не правильный, плюс я не знаю как в Middleware - selectInputs передать переменную с нужными мне настройками под каждую страницу "addPurse":
Таблица валюты:
var mongoose = require('mongoose');

var schemaCurrency = new mongoose.Schema({
    name: String,
    code: String,
    course: Number
});

module.exports = mongoose.model("Currency", schemaCurrency);

Таблица кошельки:
var mongoose = require('mongoose');

var schemaPurse = new mongoose.Schema({
    name: String,
    currency: {
        id: {
            type: mongoose.Schema.Types.Object,
            ref: "Currency"
        },
        name: String
    },
    comment: String
});

module.exports = mongoose.model("Purse", schemaPurse);

При переходе на страницу с добавлением кошелька:
router.get('/purses/add', selectInputs, function(req,res,next){
...
});

Middleware - selectInputs
module.exports = function(req, res, next){
    var currentPage = require('./config.json')["addPurse"];

    if(!currentPage){return}

    var inputs = currentPage.inputs;

    inputs.forEach(function(input){
        var model = require(input.model);
        model.find({}, function(err, allData){
            if(err){
                next(err);
            } else {
                res.locals[input.name] = allData;
            }
        });
    });

    next();

}

./config.json
{
  "addPurse":{
    "inputs": [
      {"name":"currencies", "model":"../../models/currency"}
    ]
  }
}

поле "Валюта" в add.ejs
        <div class="form-group">
            <select class="form-control" name="currency" required>
                <% currencies.forEach(function(currency){ %>
                    <option value="<%= currency._id %>"><%= currency.name %></option>
                <% }) %>
            </select>
        </div>


text:
Q: Android Studio not working. Sync failed download services.gradle.org/distributions/gradle-4.6-all.zip Ive recently formated my computer and tried to install Android Studio to continue my work.
However its not working properly. First it showed lots of erros on the wizard that could not download the SDKs. I download them manually and now i can open the IDE.
However now it just do not sync with a new app (just as example) like shown on this picture.

I dont even see Android option on Tool menu.
Anybody got a clue?


text:
Q: netaddr network ID of subnets I'd like to use netaddr to find out starting addresses of subnets (network IDs) for a given address.
Example input: 192.168.1.130/26
Example output: 192.168.1.0 192.168.1.64 192.168.1.128 192.168.1.192
So far I've tried using this code:
from netaddr import *

ip = IPNetwork('192.168.1.130/26')
subnets = list(ip.subnet(26))
print(subnets)
[IPNetwork('192.168.1.128/26')]

It shows the correct network ID, but only for that SPECIFIC address, not all the subnet's network IDs.
Can I somehow alter this code to show me all four network IDs in this case (it should be able to work with any IP/mask)
Thank you in advance.

A: >>> from netaddr import *
>>>
>>> ip = IPNetwork('192.168.1.130/26')
>>> supernet = ip.supernet(24)[0]
>>> print list(supernet.subnet(26))
[IPNetwork('192.168.1.0/26'), IPNetwork('192.168.1.64/26'), IPNetwork('192.168.1.128/26'), IPNetwork('192.168.1.192/26')]


text:
Q: ¿Como puedo dejar los mismos tamaños de diferentes gráficos en ggplot? Mi problema se presenta cuando corro los códigos, estos generan diferentes tamaños para cada gráfico.
Mi objetivo es dejar el mismo tamaño para cada gráfico en la "parte de colores" o eje x sin afectar los nombres del eje Y, con el fin de presentarlos.
Adjunto 2 imágenes diferentes:

Adjunto Código:
ggplot(grafico_obstaculo1, aes(obstaculo1,porcentaje_obstaculo,fill=areas_obstaculo))+
    geom_bar(stat = "identity", col='black')+
    #scale_y_continuous(labels = percent_format())+
    labs(title = "Obstáculos para la Innovación",
         x = "",
         y = "")+
    labs(fill = "")+
    coord_cartesian(ylim = percent(c(0, 1)*100))+
    #coord_cartesian(ylim = c(0,100))+
    # lo que sigue es para cambiar colores
    scale_fill_manual(values=c("Alta"="#008CCF",
                               "Media"="#EF7918",
                               "Baja"="#009B72",
                               "Nula"="#943A8E"))+
    geom_text(aes(label=percent(porcentaje_obstaculo/100)),position = position_stack(vjust = 0.5),vjust=1,size=4,color="black") +
    geom_area()+
    geom_hline(yintercept = as.numeric(obstaculo_innovacion1[1,1]), color="red",size=0.7) +
    guides(fill = guide_legend(reverse=TRUE))+
    theme(legend.position = "bottom")+
    coord_flip()

Muchas gracias.

A: El problema es que las etiquetas del eje x en el segundo gráfico, son más largas que las del primero, por lo cual, se está "gastando" más espacio para poder mostrarlas. Un ejemplo:
library("ggplot2")

df <- data.frame(label=c('Etiqueta corta', 'Esta es una etiqueta bastante mas larga'),
                 y=c(100, 500))

ggplot(df, aes(x=label, y=y)) +
  geom_col() +
  coord_flip()

Lo que se puede hace en este caso, es agregar saltos de línea en alguno de los espacios de la etiqueta más larga y dividir de esta forma la etiqueta en múltiples líneas. Sin embargo resulta mucho más cómodo usar str_wrap() del paquete stringr, ya que se puede aplicar a todas las etiquetas y establecer un ancho tentativo, usaremos scale_x_discrete() para configurar esto:
library("stringr")
ggplot(df, aes(x=label, y=y)) +
  geom_col() +
  coord_flip() +
  scale_x_discrete(labels = function(x) str_wrap(x, 10))


text:
Q: Half/quarter of the native resolution on a MacBook with Retina display I have a MacBook Pro notebook with native resolution of 2560x1600 which makes all my desktop details unreadable. I tried increasing DPI, but icons remain small, so I decided to decrease display resolution. I thought that resolution of 1280x800 would work the best, as 4 pixels of the native resolution would become one pixel in the lower resolution. But 1280x800 is not available to set:
$ xrandr -q
Screen 0: minimum 320 x 200, current 2560 x 2538, maximum 32767 x 32767
eDP1 connected 1440x900+0+1638 (normal left inverted right x axis y axis) 286mm x 179mm
   2560x1600      60.0 +
   2048x1536      60.0
   1920x1440      60.0
   1856x1392      60.0
   1792x1344      60.0
   1920x1200      60.0
   1920x1080      59.9
   1600x1200      60.0
   1680x1050      60.0     59.9
   1600x1024      60.2
   1400x1050      60.0
   1280x1024      60.0
   1440x900       59.9*
   1280x960       60.0
   1360x768       59.8     60.0
   1152x864       60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
DP1 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm
   2560x1440      60.0*+
   1280x720       59.9

So I set resolution of 1440x900 and the desktop is blurry.
I tried setting the native resolution with xrandr  --output eDP1 --scale .5x.5 but the effect s not any better.
How to set 1280x800 resolution which is 1/4 size of the native resolution of 2560x1600 to make my screen look better?
UPDATE:
It's strange: when I boot to MacOS and try changing retina display resolution to scaled it also offers 1440x900, but the resulting picture is very good.

A: Have a look at this.
http://ubuntuforums.org/showthread.php?t=1112186
But in my eyes the result is not better than running 1440x900.


text:
Q: How to order columns results in another column (SQL Server) I have this table
RowCnt  Lvl a_TargetID  b_TargetID a_LOG a_RF a_GNB a_SVC  a_1st  a_2nd  a_3rd  a_4th
1000    0   100         102        95    83   98    30     NULL   NULL   NULL   NULL
1000    0   100         103        67    84   28    99     NULL   NULL   NULL   NULL
1000    0   100         104        74    88   94    57     NULL   NULL   NULL   NULL
1500    3   1           33         75    26   93    85     NULL   NULL   NULL   NULL
1000    0   100         34         98    55   34    33     NULL   NULL   NULL   NULL
1000    0   100         35         47    45   45    46     NULL   NULL   NULL   NULL

The key columns in my table are RowCnt , Lvl , a_TargetID , b_TargetID
I want to put the name of the column as the order of their value in the      a_1st  a_2nd  a_3rd  a_4th
so the final results will be like this
RowCnt  Lvl a_TargetID  b_TargetID a_LOG a_RF a_GNB a_SVC  a_1st  a_2nd  a_3rd  a_4th
1000    0   100         102        95    83   98    30     a_GNB   a_LOG   a_RF   a_SVC
1000    0   100         103        67    84   28    99     a_SVC   a_RF   a_LOG   a_GNB
1000    0   100         104        74    88   94    57     a_GNB   a_RF   a_LOG   a_SVC
1500    3   1           33         75    26   93    85     a_GNB   a_SVC   a_LOG   a_RF
1000    0   100         34         98    55   34    33     a_LOG   a_RF   a_GNB   a_SVC
1000    0   100         35         47    45   45    46     a_LOG   a_SVC   a_RF   a_GNB

I can do this but it seems very wrong
UPDATE Targets
SET a_1st = CASE WHEN a_LOG >= a_RF and a_LOG >= a_GNB and a_LOG >= a_SVC THEN 'a_LOG'
WHEN a_RF >= a_LOG and a_RF >= a_GNB and a_RF >= a_SVC THEN 'a_RF'
WHEN a_GNB>= a_LOG and a_GNB >= a_RF and a_GNB >= a_SVC THEN 'a_GNB'
WHEN a_SVC>= a_LOG and a_SVC >= a_RF and a_SVC >= a_GNB THEN 'a_SVC' END

,a_2nd = I could not figure it out in an easy way !!
,a_3rd = I could not figure it out in an easy way !!
,a_4th = I could not figure it out in an easy way !!

I wonder if someone has a better method to do that

A: You can UNPIVOT and then PIVOT your data within a CROSS APPLY
with cte as (
Select *
 From  YourTable
 Cross Apply (
               Select d1 = max(case when RN=1 then item end)
                     ,d2 = max(case when RN=2 then item end)
                     ,d3 = max(case when RN=3 then item end)
                     ,d4 = max(case when RN=4 then item end)
                 From (
                       Select *
                             ,RN = row_number() over(order by value desc)
                        From ( values ('a_Log',a_Log)
                                     ,('a_RF' ,a_RF)
                                     ,('a_GNB',a_GNB)
                                     ,('a_Svc',a_Svc)
                             ) b(item,value) )B1
                      ) B2
)
Update cte
  set  a_1st = d1
      ,a_2nd = d2
      ,a_3rd = d3
      ,a_4th = d4

Results


text:
Q: Repeat some sequences in a Dataset in Pytorch I have this dataloader inspired in this example:
import torch
from torch.utils.data import Dataset, DataLoader

class CustomTextDataset(Dataset):
    def __init__(self, X, y):
        self.X = X
        self.y = y

    def __len__(self):
        return len(self.y)

    def __getitem__(self, idx):
        data = self.X[idx]
        label = self.y[idx]
        return data, label

# define data and class labels
X = [1, 2, 3, 4, 5]
y = [0, 0, 1, 0, 1]

# define data set object
TD = CustomTextDataset(X, y)
# define dataloader
ddl = DataLoader(TD, batch_size=2)

for sample, target in ddl:
    print(sample)

In each batch, in this case of size 2, the print outputs 1, 2; then 3, 4; and then 5. But how can I get the first sample to be 1, 2; then 2, 3; then 3, 4; and last 4, 5? (That is, I repeat the last element).
Can it be generalized to use in the next batch the last n elements of the previous batch and as label not the position of idx but idx+m? Thx.

A: I don't think this is possible using a pytorch DataLoader. However you could create a custom function in the CustomTextDataset that retrieves a custom batch? Something like:
def get_custom_batch(self, k, n=1, batch_size=2):
    tmp_data = tuple([self[k - n + ii] for ii in range(batch_size)])
    X = torch.cat([x[0][None, ...] for x in tmp_data], dim=0)
    y = torch.cat([x[1][None, ...] for x in tmp_data], dim=0)
    return (X, y)


text:
Q: Routing to Controller with Razor Pages I have the following form in my _partial.cshtml:
<form class="form-inline text-center" asp-controller="Search" asp-action="Index">
 @Html.TextBoxFor(m => new Search().SearchTerm, new { @class = "form-control search-term-box", placeholder = "Search keyword" })
       Near
        @Html.TextBoxFor(m => new Search().Location, new { @class = "form-control search-term-box mr-2", placeholder = "Los Angeles, CA" })
   <button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
   </form>

My SearchController.cs:
        [BindProperty]
        public Search SearchModel { get; set; }

        [HttpPost]
        public IActionResult Index(Search term, Search location = null)
        {
            SearchModel = new Search()
            {
                SearchTerm = term.ToString(),
                Location = location.ToString()
            };

            //(Razor) Search Page with no page model
            //Bind SearchModel to page
            return View("Search");
        }

In ASP.Net MVC, I can do something like this and it would work fine, but how do I get this to work with with ASP.Net Core Razor Pages? Clicking the submit button does nothing. If it matters in my Startup.cs, I have services.AddMvc(o => o.EnabledEndpointRouting = false); under ConfigureServices method and app.UseMvc(); under Configure method. I am new to Razor Pages, so if there is a better convention of achieving the same please advice.
Edit: I have found the solution, I added a routing attribute to my search controller. Although its a suitable solution, I essentially applied the MVC convention to my project which is made up of Razor Pages. If anyone can provide a solution that applies to Razor Pages, answers are welcome.

A: By default razor pages need are located under root folder and its default naming convention is '/Pages'. you can find that in startup.cs file . Change the folder name to your desired project folder name as 'xyz' and then try to navigate your page as controllername/index.cshtml . Dont forget to add extension as .cshtml


text:
Q: How to save page state in Community Builder? How to save page state in Community Builder?
I need to navigate from Page A(Component A) to Page B(Component B) (and vice versa) and save page field values.
Or better solution will be navigate between two components on one community page?


text:
Q: Program for watching log files with ruby on rails Do you know a good program for mac OS. For clear and easy viewing logs in your ruby on rails application.
I know I can be in the terminal
tail-f log / development.log

or
less + F-R log / development.log

Anyone knows a program not on the ...
mysql logs are the most important

A: You can find a whole mess of them at The Ruby Toolbox.

A: Rubymine has a dedicated server log console when you run your app from within Rubymine.


text:
Q: How to do lazy loading with wpf DataGrid Control when scrollviewer reached at bottom? <ScrollViewer Name="svDataGrid" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" ScrollChanged="ScrollViewer_ScrollChanged" >
        <DataGrid VerticalScrollBarVisibility="Disabled"   Background="Transparent" Visibility="Collapsed" Name="dgList" Grid.Row="1" IsSynchronizedWithCurrentItem="True"
                     AutoGenerateColumns="False" AlternatingRowBackground="Azure"
                     CanUserAddRows="False" CanUserDeleteRows="False"
                     CanUserSortColumns="True" CanUserReorderColumns="False"
                     CanUserResizeColumns="True" CanUserResizeRows="False" IsReadOnly="True" MouseDoubleClick="dgList_MouseDoubleClick"  PreviewKeyDown="dgList_PreviewKeyDown">

        </DataGrid>
        </ScrollViewer>

A: Your code will probably not accomplish what you want (at least thats my guess, since you don't state what you really want).
A DataGrid does contain it's own Scrollbars, and by putting the DataGrid into a ScrollViewer, you'll tell the DataGrid to go maximum size, no need for scrolling (the ScrollViewer will take care of that). So the grid will load and render all it's contents.
It would be advisable to get rid of the ScrollViewer, so you can use the proper scrolling technique for the DataGrid itself. Then you probably want to look for DataGrid Virtualization (but I'm not sure what you really want to achieve, so it might be something different).

A: I can't think of any reason to use a ScrollViewer with a DataGrid, as @Sam says, the DataGrid has its own Scrollbars.  If your reason is because you want to catch the ScrollChanged event, you can do so by using the attached property on the DataGrid:
<DataGrid ScrollViewer.ScrollChanged="ScrollViewer_ScrollChanged"  ...>
</DataGrid>