text:
Q: What are the factors that significantly affect the life span of a DC motor? I'm currently planning to run a DC motor continuously on solar power. So I would like to know which things I should be very careful about for optimum lifespan of the motor. I found the following two, and would like to know what other factors do:

*

*Voltage

*Current Source

A: Good bearings and brushes, preferably self lubricating
voltage equates to speed of rotation - more volts, faster rotation
current equates to torque. More load, bigger current.
Explanation
Basically the speed at which the motor turns induces a back e.m.f. just under the value of the applied voltage. The actual speed depends upon the type of motor but for small DC motors a rough guide is about 1000 r.p.m. per volt
The current that flows through the motor is determined by the difference in these two voltages and the coil resistance.
Adding a load on the motor's shaft (torque) slows it down and increases the voltage drop across the windings as the back e.m.f. is reduced. This increases the current taken by the motor.

A: Voltage and current - Basically because you will run your motor continuously, you will want to run your motor at or below its nameplate rating.  Too high of a current means your motor will heat up too much (see below).  Higher current also increase the current density in your brushes which will shorten life.  Too high of voltage would mean your motor is rotating faster than typical and could reduce bearing life.  At higher speeds your brush pressure may not be optimized, either, so you could reduce brush life.
Temperature - Most standard motors are designed for a maximum ambient operating temperature of 40 °C.  This temperature takes into account the temperature rise that will result from running your motor at its rated temperature.  If your ambient temperature goes above 40 °C (or if you run your motor above its nameplate rating) your motor may getting hotter than it should.  If the motor gets too hot, it may affect the life of the insulation, the life of the bearings, or the life of the brushes.  If insulation temp is an issue, you can go to a higher class insulation (for example, from Class B to Class F or from Class F to Class H).  If bearing temp is an issue, you can look at getting higher temperature grease in your bearings.  The temp of your brushes can cause a change in the friction between brush and commutator.  You can get different grade brushes with different coefficients of friction that can help you with this.  Low temperatures can also affect life.  For example, your bearing grease has a lower temp limit as well and you can specify a low temp grease if necessary.
Moisture - If your motor is outdoors or needs to be washed down, then your motor should be sealed.  Basically you want to prevent corrosion on metal parts.  You can get sealed bearings, water-proof wire exits, o-rings between end bells and housings, etc. to prevent leaking.  High humidity can actually cause brushes to have a shorter life, too.
UV - Some plastics and rubbers will degrade in sunlight, so if the motor will see direct exposure to UV, you will want to make sure your materials are compatible.  This may affect lead wires, grommets, brush holders, etc.

A: This is a very broad subject, only partly touching on electrical engineering. I suggest finding a good mechanical engineering source on motor installations. First thing that popped up when I searched for a definition of 'axial load' was the Bodine manual.
Offhand, the first thing that will wear out a motor is asking its bearings to support loads they are not designed for. Avoid side to side forces on the shaft, and axial forces:

The next thing that will wear out a motor is over-temperature. Provide cooling if it needs it. At the very least, do not obstruct it's cooling vents!
Bearing seals can fail, lubricants can run dry. Brushes wear out, grit can get in the gears. So keep it clean and protected, and at the same time available for inspection.

A: Avoid starting and stopping. That definitely hurts motor life. That's why your AC won't turn and off quickly when you switch it on and off quickly. There is a minimum time in the controller to avoid that.


text:
Q: Как правильно вывести значение в градиенте? сейчас percentage не выводится

<div class="test" [ngStyle]="{{`linear-gradient(90deg, blue {{percentage}}%, red {{percentage}} )`}}">click

A: Как вариант использовать вместо [ngStyle] просто style, а внутри ковычек
{{'linear-gradient(90deg, blue ' + percentage + '%, red ' + percentage + '%)'}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flask - authenticate hashed password from SQLAlchemy when I use basic authenticate of user login with name and plaintext password, user is logged in correctly.
Password is correctly hashed during registration.
When I store hashed password and try to authenticate it, program gives error:
AttributeError: type object 'User' has no attribute 'query'
Could you please tell me, what is wrong? I suspect that checking function can't find hashed password from SQLAlchemy database. Thank you.
When I use :
query = s.query(User).filter(User.username.in_([POST_USERNAME]))

I get:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.password has an attribute 'split'
   engine = create_engine('sqlite:///tutorial.db', echo=True)

   app = Flask(__name__)
   app.config.from_object(__name__)
   app.config['SECRET_KEY'] = 'XXXXX'

   def hash_password(password):
        salt = uuid.uuid4().hex
        return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

    def check_password(hashed_password, user_password):
        password, salt = hashed_password.split(':')
        return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

   Base = declarative_base()
   class User(Base):

       __tablename__ = "users"

       id = Column(Integer, primary_key=True)
       username = Column(String(64))
       password = Column(String(120))
       email = Column(String(64))

       def __init__(self, username, password, email):
           self.username = username
           self.password = password
           self.email = email

       def check_password(hashed_password, user_password):
           password, salt = hashed_password.split(':')
           return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

    Base.metadata.create_all(engine)

    @app.route("/")
     def index():
         return render_template('index.html')

    @app.route('/login', methods=['POST'])
     def do_admin_login():
       POST_USERNAME = str(request.form['username'])
       POST_PASSWORD = str(request.form['password'])

       Session = sessionmaker(bind=engine)
       s = Session()
       user = User.query.filter_by(username=POST_USERNAME).first()
       if check_password(User.password, POST_PASSWORD) == True:
            session['logged_in'] = True
       else:
           flash('wrong password!')
       return index()

A: Query like this. s is your session.
user = s.query(User).filter_by(username=POST_USERNAME).first()

Then your if statement for check password is wrong. You're trying to use the model class instead of the user instance you just got. Should be:
if check_password(user.password, POST_PASSWORD) == True:

also some other pointers:  The module Flask-SQLAlchemy helps you use SQLAlchemy in Flask (defines your session globally).  Also consider using bcrypt for passwords. It is MUCH safer than SHA.


text:
Q: trying to use reflection in C# with static class Property Extension with Set & Get property vale So, I have my ParseFieldData void class and I am having some trouble calling my SetPropertyValue(" //What to return in here? "); I'm thinking it will take my FieldName and FieldValue but I am thinking this SetPropertyVaule only takes String with double quotes.
public class CampainProspectsController : ApiController
{
    [HttpPatch]
    public IHttpActionResult Patch([FromBody] JToken Value)
    {
        string toupdate = "";
        Prospects res = new Prospects();
        res.Error = "";
        res.Status = "";
        JArray ar = new JArray();

        var results = JsonConvert.DeserializeObject<UpdateableFieldList>(Value.ToString());

        toupdate = "first_name=" + results.fieldList.FirstOrDefault(e => e.FieldName == "first_name").FieldValue + "&last_name=" + results.fieldList.FirstOrDefault(e => e.FieldName == "last_name").FieldValue
                + "&email=" + results.fieldList.FirstOrDefault(e => e.FieldName == "email").FieldValue + "&phone=" + results.fieldList.FirstOrDefault(e => e.FieldName == "phone").FieldValue + "&id=" + results.fieldList.FirstOrDefault(e => e.FieldName == "id").FieldValue;

        var update = PardotUtilities.Update(toupdate, results.fieldList.FirstOrDefault(e => e.FieldName == "id").FieldValue);

        if (!update.Contains("ok"))
        {
            return BadRequest();
        }

        return Ok();

    }
    [HttpPost]
    public IHttpActionResult Post([FromBody] JToken Value)
    {
        string tocreate = "";

        Prospects res = new Prospects();
        res.Error = "";
        res.Status = "";

        var results = JsonConvert.DeserializeObject<Prospects>(Value.ToString());
        if (results != null)
        {
            // results
            results.id = Guid.NewGuid().ToString();
            tocreate = "first_name=" + results.first_name + "&last_name=" + results.last_name + "&email=" + results.email + "&phone=" + results.phone + "&id=" + results.id;
            var idstr = PardotUtilities.Create(tocreate);
            return Ok(idstr);
        }

        PardotUtilities.Upsert(tocreate, results.id);

        PardotUtilities.Query(tocreate, results.id);
        PardotUtilities.Delete(tocreate, results.id);
        // return Ok(update);

        return Ok();
    }
}
//public class

public class Prospects
{

    public String Status { get; set; }
    public String Error { get; set; }

    public string id { get; set; }
    public string email { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string password { get; set; }
    public string company { get; set; }
    public string website { get; set; }

    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<UpdateFields> fieldList { get; set; }

    public void ParseFieldData(List<UpdateableFieldList> fList)
    {
        Prospects newp = new Prospects();
        //Here is wher setPropertyValue needs to be set
        newp.SetPropertyValue();

    }
}
public static class PropertyExtension
{

    public static void SetPropertyValue(this object obj, string propName, object value)
    {
        obj.GetType().GetProperty(propName).SetValue(obj, value, null);
    }
    public static object GetPropertyValue(this object obj, string propName)
    {
        return obj.GetType().GetProperty(propName).GetValue(obj, null);
    }
}

public class UpdateableFieldList
{
    public List<UpdateFields> fieldList { get; set; }
}
public class UpdateFields
{
    public string FieldName { get; set; }
    public string FieldValue { get; set; }
}


text:
Q: How can I generate tags file with exuberant ctags in ubuntu's C/C++ include directories for using with gvim? I use GVim 7.4 with TDM-GCC 64 in Windows 7.
I know the include directories of this compiler,
and added the paths suitably to gvim's tags search path.
Everything is fine in Windows.
But I am new to ubuntu, I currently installed ubuntu 13.10 (Saucy),
but a bit confused about the compiler's include directories.
I found some of these directories are:
/usr/include
/usr/src
/usr/local/include
/usr/include
/usr/lib/gcc/i686-linux-gnu/4.8
/usr/lib/gcc/x86_64-linux-gnu/4.8/include

Finally I created a shell script as follows:
#!/bin/sh
cd /usr/include
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *
cd /usr/src
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *
cd /usr/local/include
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *
cd /usr/include
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *
cd /usr/lib/gcc/i686-linux-gnu/4.8
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *
cd /usr/lib/gcc/x86_64-linux-gnu/4.8/include
sudo ctags -R --c-kinds=+pxfvtcdeglmnsu --c++-kinds=+pxfvtcdeglmnsu --languages=C,C++ --langmap=C:.c.h --langmap=C++:.C.h.c.cpp.hpp.c++.cc.cp.cxx.h++.hh.hp.hxx --fields=+iaSm --extra=+qf -f tags *

But this script is generating a gigantic huge tags file,
consequently vim is getting slower while searching functions, variables, struct,
prototypes etc.
When I am pressing "< C-X > < C-O >" or Tab (I configured omni-completion to Tab),
vim is freezing for a while then suggesting the content I am looking for.
Finally I decided to discard the recursive (-R) option, but my question is:
1) What are the actual include directories in ubuntu?
2) Where should I use recursive and where not?
3) Many directories are not generally needed, such as '/usr/src/' or '/usr/src/nvidia-331.38'
which mostly contains Linux headers and NVIDIA driver functions.
What are these type of directories so that I can list it in my .vimrc as the last option?
I am looking for a solution to find everything (functions, variables, struct) without having to slow down vim.
Thanks in advance.

A: I would suggest /usr/include and /usr/local/include recursively as the most basic paths for headers.
On most Unix-like systems (including Linux and FreeBSD distributions), /usr/include is the most basic place to find C and C++ library headers.
Often, but not always, system administrators will install additional software in /usr/local and that usually (but not always) means that added libraries will be in /usr/local/lib and their C/C++ headers will be in /usr/local/include.
On some Unix-like systems, optional software is installed in /opt instead of /usr/local.
Generally on open-source Unix-like systems, /usr/src will contain the source and headers for the operating system, both kernel and "user land" (i.e. the commands a user might use from the command line).  Generally, unless you are developing an application that should be tightly integrated with the operating system or is actually part of the operating system, you will not need the headers which are in the /usr/src path (but are not in /usr/include).


text:
Q: Как в PostgreSQL добавить строку, если такой еще нет Нужно чтобы в таблицу добавлялось имя, если его нет среди существующих, в ином случае просто вернуть все имена,
IF EXISTS (SELECT * FROM names WHERE name = 'John') THEN
   SELECT * FROM names WHERE name = 'John'
ELSE
   INSERT INTO names ('John')

Пытаюсь запустить в PostgreSQL такой код и получаю ошибку:

A: Для начала надо добавить уникальный ключ для поля name
Чтобы PostgrSQL сам проверял наличие поля с таким значением и не позволял вставлять запись если запись уже есть.
В этом случае можно делать просто
INSERT INTO names ('John');

и обрабатывать ошибки при данном запросе.
Если ошибки обрабатывать не хочется или, вдруг, нет такой возможности, то можно изменить запрос
INSERT INTO names ('John') ON CONFLICT DO NOTHING;

Т.е. точно так же вставляется запись, но если она уже есть в таблице и возникает ошибка, то на эту ошибку сервер ничего не делает и продолжает работу дальше.
В качестве бонуса можно в случае конфликта например изменять какие-то другие поля в данной строке, которая уже есть в таблице
INSERT INTO names ('John') ON CONFLICT DO UPDATE <здесь изменение значения полей>;


text:
Q: Why buttons don't work when embedded in a SwiftUI Form? I'm building a SwitUI form. I need to draw some custom sliders. For that, I made a view (SliderView) that I include in the form several times. It took me some time to manage the Binding to get in the parent view the value of the Sliders, but I was able to do it :-)
The big mystery I'm not able to understand is why the buttons I placed in the child view, don't work when they are embedded in a Form. They work fine in a VStack. Here the code:
//  SliderView.swift

import SwiftUI

struct SliderView: View {
    var name: String
    var min: Double
    var max: Double
    var step: Double
    var defaultValue: Double

    let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 2
        formatter.minimumIntegerDigits = 1
        return formatter
    }()

    @Binding var selectedValue: Double
    var body: some View {
        HStack{
            Text("\(name)")
            Slider(value: $selectedValue, in: self.min...self.max, step: self.step)
            Button(action: {
                if (self.selectedValue - self.step) >= self.min{
                    self.selectedValue = self.selectedValue - self.step
                }
            }) {
                Image(systemName:"minus.circle")
            }
            Text("\(numberFormatter.string(from: NSNumber(value: selectedValue)) ?? "")")
                .padding(5)
                .onAppear {
                    self.selectedValue = self.defaultValue
                }
            Button(action: {
                if (self.selectedValue + self.step) <= self.max{
                    self.selectedValue = self.selectedValue + self.step
                }
            }) {
                Image(systemName:"plus.circle")
            }

        }

    }
}

struct SliderView_Previews: PreviewProvider {
    @State static var myValue: Double = 1
    static var previews: some View {
        SliderView(name: "CPU", min: 1, max: 10, step: 0.5, defaultValue: 1, selectedValue: $myValue)
    }
}

Now, part of the form that I'm building. The code compiles, the sliders work and the value of each of them can be seen in the parent view. However, the buttons to update the sliders step by step don't work (because they are embedded in the Form)
//
//  ContentView.swift

import SwiftUI

struct ContentView: View {
    @State var selectedCPU: Double = 1
    @State var selectedRAM: Double = 1
    @State var selectedDisk: Double = 50
    var body: some View {

        NavigationView{
            Form{
                Section{
                    SliderView(name: "CPU", min: 1, max: 16, step: 1, defaultValue: selectedCPU, selectedValue: $selectedCPU)
                    SliderView(name: "RAM", min: 0.5, max: 128, step: 0.5, defaultValue: selectedRAM, selectedValue: $selectedRAM)
                    SliderView(name: "SSD", min: 20, max: 500, step: 10, defaultValue: selectedDisk, selectedValue: $selectedDisk)
                }
                Section{
                    Text("CPU: \(selectedCPU)")
                    Text("RAM: \(selectedRAM)")
                    Text("SSD: \(selectedDisk)")
                }
            }
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Just replacing the "Form" with a "VStack" in the upper code, the buttons just work fine. Anyone can shed some light? I think is something regarding the different layers in the Form. When I try to click on the buttons the whole row with the slider seems to be clicked, but nothing happens.
I'm using Xcode 11 GM in MacOS 10.15 beta (19A558d)
Thanks in advance!

A: From what I've been able to tell, Form rows behave differently when they contain a View that accepts a tap gesture, such as a button.  When the row contains a Button, then when the user taps on that button, everything else in the same row also receives a tap gesture.  So in your example above, it's not that your buttons are not working, what is actually happening is that they are both receiving a tap gesture and executing their action, but because of the logic in your code effectively cancels the effect of the other, it appears as if they are not working.
To help demonstrate this point, here is some test code I wrote:
    @State var count1 = 0
    @State var count2 = 0

    func buttonTest() -> some View {
        HStack {
            Button(action: {
                self.count1 += 1
            }) {
                Text("Button 1: \(count1)")
            }
            Spacer()
            Button(action: {
                self.count2 += 1
            }) {
                Text("Button 2: \(count2)")
            }
        }
    }

    var body: some View {
        VStack {
            buttonTest()
            Form {
                Section(header: Text("Test")) {
                    buttonTest()
                }
            }
        }
    }

If you tap either button above the form, they work independently as expected, incrementing only their own count, but if you tap either button in the Form, or anywhere else in the row, then both buttons' actions execute and both counts increment.
I'm not sure why Apple do this, but I too am struggling to find a solution to this problem.
EDIT
Thanks to Shauket Sheikh, there is a solution, but it makes code re-use less elegant.
So when the Button is in a Form, you need to put the code into an .onTapGesture handler, but if the Button is outside a Form, you need the code in the action: handler.
I really hope this isn't Apple's long-term position on Forms: it's goes against the write once, use everywhere philosophy.

A: Try adding a buttonStyle modifier to the buttons in your Form. This worked for me:
Button(action: {}, label: {Text("Test")})
    .buttonStyle(PlainButtonStyle())


text:
Q: Implicit conversion of generic type T to JsValue in Play! Framework I have a problem with declaring of generic method in Play 2.6 application that converts JSON to instance of one of the case class models.
All models declared with helper objects and formatters:
import play.api.libs.json.{Json, OFormat}
case class Shot(id: Long, likes_count: Long)
object Shot {
  implicit val format: OFormat[Shot] = Json.format[Shot]
}

val s1: Shot = Json.toJson(f).as[Shot] // Works great

def testJsonGeneric[T](js: JsValue)(implicit ev: OFormat[T]): T = {
    js.as[T](ev)
}

val s2: Shot = testJsonGeneric(Json.toJson(f)) // could not find implicit value for parameter ev: play.api.libs.json.OFormat[T]. Compilation failed

The last line of code throws

could not find implicit value for parameter ev: play.api.libs.json.OFormat[T]

But if I call my generic method like this (with explicit formatter) it works just fine:
val s2: Shot = testJsonGeneric(Json.toJson(f))(Shot.format)

However, it looks like if I expect my JSON to return a list of objects I have to define an extra formatter for List[Shot] to pass explicitly to the method when default Play's json.as[List[Shot]] could easily allow me to do this with a single existing formatter like the one that already defined in the helper object.
So, is it even possible to provide formatters implicitly for generic type T in my case?
Thank you

A: You can definitely do this, you just have to change the declaration a bit.
Move the case class and companion declaration outside the method, and then explicitly import Shot._ to bring the implicit in scope:
import play.api.libs.json.{JsValue, Json, OFormat}

object Foo {
  case class Shot(id: Long, likes_count: Long)
  object Shot {
    implicit def format: OFormat[Shot] = Json.format[Shot]
  }

  def main(args: Array[String]): Unit = {
    import Shot._

    val f = Shot(1, 2)

    def testJsonGeneric[T](js: JsValue)(implicit ev: OFormat[T]): T = {
      js.as[T](ev)
    }

    val s2: Shot = testJsonGeneric(Json.toJson(f))
  }
}


text:
Q: Solution to rank positions in my LIST? Considering following code:
class Results
{
    public int playerId;
    public int score;
    public int section;
    public int position;
    public Results(int _playerId, int _score, int _section)
    {
        playerId = _playerId;
        score = _score;
        section = _section;
    }
}

public void RankMyResults()
{
    List<Results> myResultList = new List<Results>();

    myResultList.Add(new Results(1,232, 1));
    myResultList.Add(new Results(2,213, 1));
    // Add a lot of more results

    // Iteriate over the items to set the position
}

I want to set position 1 for the highest score in each section, position 2 for second highest and so on.
Also if two people have the same score the positions should look like this
Position  Score   PlayerId Section
1         135     23       1
1         135     43       1
3         131     45       1

As in this example it will skip position 2.
Is there a nice way to use LINQ to do this or for example using some Select, Sorting functionality from the List Object?
My own solution iterate over the list is not good at all!

A: I wrote these extension methods just a few days ago:
    #region RankBy

    public static IEnumerable<TResult> RankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.RankBy(keySelector, null, false, resultSelector);
    }

    public static IEnumerable<TResult> RankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.RankBy(keySelector, comparer, false, resultSelector);
    }

    public static IEnumerable<TResult> RankByDescending<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.RankBy(keySelector, comparer, true, resultSelector);
    }

    public static IEnumerable<TResult> RankByDescending<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.RankBy(keySelector, null, true, resultSelector);
    }

    private static IEnumerable<TResult> RankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        bool descending,
        Func<TSource, int, TResult> resultSelector)
    {
        comparer = comparer ?? Comparer<TKey>.Default;

        var grouped = source.GroupBy(keySelector);
        var ordered =
            descending
                ? grouped.OrderByDescending(g => g.Key, comparer)
                : grouped.OrderBy(g => g.Key, comparer);

        int totalRank = 1;
        foreach (var group in ordered)
        {
            int rank = totalRank;
            foreach (var item in group)
            {
                yield return resultSelector(item, rank);
                totalRank++;
            }
        }
    }

    #endregion

    #region DenseRankBy

    public static IEnumerable<TResult> DenseRankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.DenseRankBy(keySelector, null, false, resultSelector);
    }

    public static IEnumerable<TResult> DenseRankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.DenseRankBy(keySelector, comparer, false, resultSelector);
    }

    public static IEnumerable<TResult> DenseRankByDescending<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.DenseRankBy(keySelector, comparer, true, resultSelector);
    }

    public static IEnumerable<TResult> DenseRankByDescending<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, int, TResult> resultSelector)
    {
        return source.DenseRankBy(keySelector, null, true, resultSelector);
    }

    private static IEnumerable<TResult> DenseRankBy<TSource, TKey, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer,
        bool descending,
        Func<TSource, int, TResult> resultSelector)
    {
        comparer = comparer ?? Comparer<TKey>.Default;

        var grouped = source.GroupBy(keySelector);
        var ordered =
            descending
                ? grouped.OrderByDescending(g => g.Key, comparer)
                : grouped.OrderBy(g => g.Key, comparer);

        int rank = 1;
        foreach (var group in ordered)
        {
            foreach (var item in group)
            {
                yield return resultSelector(item, rank);
            }
            rank++;
        }
    }

    #endregion

You can use them as follows:
var rankedPlayers = players.RankByDescending(
                                p => p.Score,
                                (p, r) => new { Rank = r, Player = p });

The difference between RankBy and DenseRankBy is that RankBy creates "gaps" (e.g. 1,1,3,3,3,6...) whereas DenseRankBy does not (1,1,2,2,2,3...)

A: I modified those great methods above so that they preserve the original order. Ranking methods should not change the order of the elements, they should just rank them and return the elements in the original order of input collection.
private static IEnumerable<TResult> RankBy<TSource, TKey, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IComparer<TKey> comparer,
    bool descending,
    Func<TSource, int, TResult> resultSelector)
{
    var comp0 = comparer ?? Comparer<TKey>.Default;
    var comp = descending ? Comparer<TKey>.Create((x, y) => -comp0.Compare(x, y)) : comp0;

    var keys = source.Select(x => keySelector(x)).ToArray();
    var indexes = Enumerable.Range(0, keys.Length).ToArray();
    Array.Sort<TKey, int>(keys, indexes, comp);

    var groups = new int[keys.Length];
    int group = 0;
    int index = 0;
    for (int j = 1; j < keys.Length; ++j)
    {
        ++index;
        if (comp.Compare(keys[j], keys[j - 1]) != 0)
        {
            group += index;
            index = 0;
        }
        groups[indexes[j]] = group;
    }

    index = 0;
    foreach (var item in source)
    {
        yield return resultSelector(item, groups[index++] + 1);
    }
}

private static IEnumerable<TResult> DenseRankBy<TSource, TKey, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IComparer<TKey> comparer,
    bool descending,
    Func<TSource, int, TResult> resultSelector)
{
    var comp0 = comparer ?? Comparer<TKey>.Default;
    var comp = descending ? Comparer<TKey>.Create((x, y) => -comp0.Compare(x, y)) : comp0;

    var keys = source.Select(x => keySelector(x)).ToArray();
    var indexes = Enumerable.Range(0, keys.Length).ToArray();
    Array.Sort<TKey, int>(keys, indexes, comp);

    var groups = new int[keys.Length];
    int group = 0;
    for (int j = 1; j < keys.Length; ++j)
    {
        if (comp.Compare(keys[j], keys[j - 1]) != 0)
            ++group;
        groups[indexes[j]] = group;
    }

    int index = 0;
    foreach (var item in source)
    {
        yield return resultSelector(item, groups[index++] + 1);
    }
}


text:
Q: Modules 'base' and 'AdharVerificationDynamicFeature' contain entry 'assets/crashlytics-build.properties' with different content I am generating Signed Build Bundle. Instant App Module is launching perfectly in device but when I am generating Signed Build Bundle I got this error.
'Modules 'base' and 'AdharVerificationDynamicFeature' contain entry 'assets/crashlytics-build.properties' with different content'
In my assets folder 'crashlytics-build.properties' file is not showing.
Error logs :
What went wrong: Execution failed for task ':quickRide:packageQrReleaseBundle'.
java.util.concurrent.ExecutionException: com.android.tools.build.bundletool.exceptions.ValidationException: Modules 'base' and 'AdharVerificationDynamicFeature' contain entry 'assets/crashlytics-build.properties' with different content.

A: As a workaorund it should be safe to use
packagingOptions {
  exclude 'crashlytics-build.properties'
}


text:
Q: C# sync socket exception on receive method: System.Net.Sockets.SocketException Please see code below, it is not very stable in my windows service, after starting for a while, it throw the error:

System.Net.Sockets.SocketException: the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond

The error was catched on : readsize = listensocket2.Receive(buffer_receive);
The project is on a data communication center, the clients are GPRS DTU socket client.
Please help!!!
Part I:
    protected override void OnStart(string[] args)
    {
            IPEndPoint endpoint = new IPEndPoint(RemsSocket.myip, RemsSocket.webport);
            Socket listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listensocket.Bind(endpoint);
            listensocket.Listen(200);
            Thread th = new Thread(new ParameterizedThreadStart(RemsSocket.listen_send));
            th.IsBackground = true;
            th.Start(listensocket);
    }

Part II:
    public static void listen_send(object source)
    {
        while (true)
        {
            done.Reset();
            Socket listensocket = (Socket)source;
            listensocket.BeginAccept(new AsyncCallback(acceptcallback_send), listensocket);
            done.WaitOne();
        }
    }

    public static void acceptcallback_send(IAsyncResult ar)
    {
        done.Set();
        Socket socket = (Socket)ar.AsyncState;
        Socket listensocket2 = socket.EndAccept(ar);
        byte[] buffer_validate = new byte[buffersize];
        string hostcode = "";
        byte[] buffer_send = Hex.HexStringToByteArray(validate_code);
        listensocket2.Send(buffer_send, 0, buffer_send.Length, SocketFlags.None);
        listensocket2.Receive(buffer_validate);
        int readsize = buffer_validate.Length; //listensocket2.EndReceive(ar);
        if (readsize > 0)
        {
            bool success = FirstValidate(buffer_validate, ref hostcode);
            bool validate = BLL.ExtHostBLL.CanCommunicate(hostcode);
            if (success && validate)
            {
                LoopSendReceive(hostcode, listensocket2);
            }
        }
    }

Part III:
    public static void LoopSendReceive(string hostcode, Socket listensocket2)
    {
        listensocket2.Blocking = true;
        byte[] buffer_receive = new byte[buffersize];
        bool validate = BLL.ExtHostBLL.CanCommunicate(hostcode);
        while (validate)
        {
            Thread.Sleep(500);
            int readsize;
            bool success;
            IPEndPoint clientipe = (IPEndPoint)listensocket2.RemoteEndPoint;
            byte commandByte = Hex.HexStringToByteArray(command_8);
            listensocket2.Send(commandByte, 0, commandByte.Length, SocketFlags.None);
            listensocket2.ReceiveTimeout = 5000;
            int countSocketException = 0;
            readsize = listensocket2.Receive(buffer_receive);
            if (readsize != 0)
                {
                    clientipe = (IPEndPoint)listensocket2.RemoteEndPoint;
                    ClientDto client = hostList.FirstOrDefault(c => c.Ip == clientipe.Address.ToString());
                    ParseChannel.AlertStatus[] data;
                    ParseChannel channel = new ParseChannel();
                    success = channel.Parse(buffer_receive, client, out data);
                    if (!success)
                    {
                        continue;
                    }
                    SaveData(data, client);
                }
        }
    }


text:
Q: how to send push notification to the android device using FCM by java server? I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send
public static void pushFCMNotification(String userDeviceIdKey) throws     Exception{

    String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
    String FMCurl = API_URL_FCM;

    URL url = new URL(FMCurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization","key="+authKey);
    conn.setRequestProperty("Content-Type","application/json");

    JSONObject json = new JSONObject();
    json.put("to",userDeviceIdKey.trim());
    JSONObject info = new JSONObject();
    info.put("title", "Notificatoin Title");   // Notification title
    info.put("body", "Hello Test notification"); // Notification body
    json.put("notification", info);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(json.toString());
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + json);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    /*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(json.toString());
    wr.flush();
    conn.getInputStream();*/
    }

A: According to the oficial documentation:

Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.

source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key


text:
Q: What design pattern is good for applying attributes to a class that changes its behavior? I am trying to find the best way to structure my project. What I would like to do is have a "Structure", which is made of multiple "part". These parts also will have separate attributes, for example it could be spinning, hovering, vibrating, jumping, shaking, growing, accelerating.
So for example, I might have a "structure" called human that is made of 6 "parts". I am going to set each part to one of the available options, so in this case, 2 parts are going to be arms, 2 parts are going to be legs, one part is a torso, and one part is a head. Now, I want to be able to apply the attribute spinning to one of the parts, the arm. So now I should have a human with a spinning arm.
Additionally, I would like other people to be able to create their own cusom attributes, structures, and parts.
I would like to get an idea on how I should structure my code, and apply an attribute to a part. Additionally, what design pattern would be good for this?

A: The requirement is to have a single interface for a composition of various objects / components.
There are 2 suitable design patterns for this requirement.

*

*Facade (https://dzone.com/refcardz/design-patterns?chapter=17)

*Composite Object (https://dzone.com/refcardz/design-patterns?chapter=15)

Facade pattern can be used when the way in which the internal components are assembled must be abstracted.
Composite object pattern can be used when the assembly of the components must be advertised.


text:
Q: Способы ограничения заливки гридов Floodfill Появилась проблема. С ограничением заливки.
Подскажите как реализовать способ ограничения распространения заливки .
Мне нужно что бы заполнялось только поле которое создаёт игрок.

У меня есть поле и игрок "G" игрок двигаясь по полю создаёт путь из "Er зелёных "объектов(путь отмечен красной стрелкой).В последствии это поле заливается "Er синими" объектами.
А алгоритм заливки .Игнорирует поля так как проверяется для каждого объекта в массиве путь.И проверяется с лева на право .

То есть рекурсивный поиск и заливка линейная floodfill.
 Крестиком отмечен  объект "стоп" . А если  ограничиваю распространение координаторами массива то поле просто не заполняется.
Есть идея переделать алгоритм  заполнения на нелинейный а всесторонний ( то есть каждый грид будет проверять соседей с четырёх сторон.)Но столкнулся с проблемой при ограждении поля для заливки , первый грид с которого стартует проверка ,для всех остальных ,нужно поместить в центр поля которое нужно залить.


text:
Q: Seperating the O.D.E $\frac{dv}{dt} = mg - \kappa v$ I am having some trouble seperating the following (autonomous) O.D.E.
$$\frac{dv}{dt} = mg - \kappa v$$
From what I understand, I have to get the $v$ to the left side while having the $\kappa$ on right side with $dt$. The solution is given by:
$$\begin{align}
\frac{dv}{dt} &= mg - \kappa v \\
\frac{dv}{\left(v-\frac{mg}{k}\right)} &= -\kappa dt
\end{align}$$
What I am having trouble understanding is how he (the prof.) managed to seperate the O.D.E like that. Can someone please show the steps?
Thanks!

A: $$
mg - \kappa v = -\kappa \left ( v - \frac {mg}\kappa\right )
$$

A: Alternatively, one may put the equation in a more convenient form for direct integration.  For example, write the equation as
$$\frac{d v}{d t} + \kappa v = m g$$
Multiply through by $e^{\kappa t}$ on both sides.  In this case, the LHS looks like a derivative of a product:
$$e^{\kappa t} \frac{d v}{dt} + e^{\kappa t} \kappa v = \frac{d}{dt} \left (e^{\kappa t} v \right ) = e^{\kappa t} m g$$
Integrating both sides:
$$e^{\kappa t} v(t) = \frac{m g}{\kappa} e^{\kappa t} + C$$
where $C$ is a constant of integration.  You may then solve for $v(t)$ easily from here.


text:
Q: Mod Rewrite to add query string to all static files for cache busting I am trying to append a query string to the end of all .js files, without actually making a code change. The purpose of this would be so static files get pulled from the server rather than the cache when they are changed so we don't have any stale static files.
So when my html says
<script type="text/javascript" src="file1.js">

I want it to actually pull
<script type="text/javascript" src="file1.js?v=1">

from the server. Is this possible?
So far I have:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)\.js$ /$1.js?v=1 [L,R]

But I don't think it's quite doing what I want it to...

A: This doesn't make sense: if the resource is cached with an expiry date, the browser will never make the request in the first place.
The much more straighforward way is to set up proper caching rules for the JS file as outlined here: How to prevent http file caching in Apache httpd (MAMP), adjusting the filesMatch directive to your liking.

A: This will double the number of requests for the files (all .js files in this case), but it should work otherwise.
I'm using a directory (effectively modifying the filename), rather than a query string because that is the preferred technique. [1][2]
First, redirect to a different folder name
ReWriteRule ^(.*\.js)$ /rev/000/$1 [L,R]

Replace the 000 part with your revision number (you should be able to automate this)
The L flag stops processing rewrites, and the R does an HTTP redirect, initiating a second request to your server using the new file name.
Then catch requests tagged using the new "folder" and point them back to the original file using a rewrite rule that does not invoke another request (your first rule will be passed over this time around)
ReWriteRule ^/rev/[0-9]+/(.*)$ $1

A: Ok I know the question is old, but while looking for something similar I found two clever Apache plugins:
mod_pagespeed:
This thing rewrites the html page that you are serving and replaces the referenced static resource links (CSS, JS, imgs) with modified ones. When static resource on disk changes, the plugin will generate a completely new url for it. There is some content based hash included I guess. And this busts the cache because the client will have to make a new request.
So caching time of the original html page should be rather short, but all related static resources can be cached for extremely long times.
mod_proxy_html:
This one also can edit html on the fly. But it is a lot simpler and only offers rewriting links, no minification and other fancy stuff like in mod_pagespeed. But sometimes this is all what you need, as this probably mean there is less risk that page will be broken by rewriting.


text:
Q: Rails 3 / Heroku infinite zombie dynos with simple app deploy - too busy to open console The fact that there are so few results Googling around on this makes me think I am doing something totally wrong, because it seems like this would be an incredibly common problem.  However I can't seem to find an easy solution and Heroku's docs suck in general, and their support takes >1 day to respond, so here I am.
I have an app that I am trying to deploy for the first time.  It is a very lite app, almost a shell app.  It works on dev and then crashes when I deploy to heroku with an unhelpful HTML error page:
    Application Error
    An error occurred in the application and your page could not be served.
Please try again in a few moments.
    If you are the application owner, check your logs for details.

Ok, better check the logs.  But Heroku logs tells me nothing:
Ovid:volatilityApp dlipa$ heroku logs
Ovid:volatilityApp dlipa$

Ovid:volatilityApp dlipa$ heroku logs -n 300
Ovid:volatilityApp dlipa$

OK, hmm..better log into the console to see what is going on.
Ovid:volatilityApp dlipa$ heroku console
Your application is too busy to open a console session.
Console sessions require an open dyno to use for execution.

Hmm that sucks, lets look at what is running.
Ovid:volatilityApp dlipa$ heroku ps
Process       State               Command
------------  ------------------  ------------------------------
web.1         crashed for 4m      thin -p $PORT -e $RACK_ENV -R $HER..

Makes sense..but why doesn't Heroku's dyno grid clear this out?  No info on topic on Heroku site.  Googling around leads to http://neilmiddleton.com/avoiding-zombie-dynos-with-heroku
Ok cool so I install the rack-timeout gem and add the initializer and push to heroku.  I watch it complete the 'bundle install'.  But still the same problem...
Ovid:volatilityApp dlipa$ heroku console
Your application is too busy to open a console session.
Console sessions require an open dyno to use for execution.

Argh this is really cryptic and starting to become frustrating.  Maybe I should just buy some more resources from Heroku...that should solve the problem, because then I will have more dynos to open the console..
Ovid:volatilityApp dlipa$ heroku dynos
volatility is running 1 dyno

Ovid:volatilityApp dlipa$ heroku dynos 2
volatility now running 2 dynos

But wait, Heroku loads as many web processes as I have dynos, and they all zombie out!  And I can't get into the console no matter how high I scale.
Ovid:volatilityApp dlipa$ heroku dynos 10
volatility now running 10 dynos
Ovid:volatilityApp dlipa$ heroku ps
heroku consoleProcess       State               Command
------------  ------------------  ------------------------------
web.1         crashed for 2m      thin -p $PORT -e $RACK_ENV -R $HER..
web.2         crashed for 1m      thin -p $PORT -e $RACK_ENV -R $HER..
web.3         crashed for 37s     thin -p $PORT -e $RACK_ENV -R $HER..
web.4         crashed for 36s     thin -p $PORT -e $RACK_ENV -R $HER..
web.5         crashed for 35s     thin -p $PORT -e $RACK_ENV -R $HER..
web.6         crashed for 35s     thin -p $PORT -e $RACK_ENV -R $HER..
web.7         crashed for 37s     thin -p $PORT -e $RACK_ENV -R $HER..
web.8         crashed for 33s     thin -p $PORT -e $RACK_ENV -R $HER..
web.9         crashed for 38s     thin -p $PORT -e $RACK_ENV -R $HER..
web.10        crashed for 34s     thin -p $PORT -e $RACK_ENV -R $HER..
Ovid:volatilityApp dlipa$ heroku console
Your application is too busy to open a console session.
Console sessions require an open dyno to use for execution.
Ovid:volatilityApp dlipa$

Is it me or is this poorly designed?  Why is there no information on this subject?  Am I doing something totally wrong?
Thanks for your help!
App running 3.0.5 rails, 1.9.2 ruby, postgresql.
--UPDATE IN RESPONSE TO BANTIC--
Ovid:volatilityApp dlipa$ heroku stack
  aspen-mri-1.8.6
  bamboo-ree-1.8.7
* bamboo-mri-1.9.2

Ovid:volatilityApp dlipa$ heroku ps
Process       State               Command
------------  ------------------  ------------------------------
web.1         crashed for 17s     thin -p $PORT -e $RACK_ENV -R $HER..
web.2         crashed for 1m      thin -p $PORT -e $RACK_ENV -R $HER..
web.3         crashed for 1m      thin -p $PORT -e $RACK_ENV -R $HER..

RubyGems Environment:
  - RUBYGEMS VERSION: 1.6.1
  - RUBY VERSION: 1.9.2 (2011-02-18 patchlevel 180) [x86_64-darwin10.6.0]
  - INSTALLATION DIRECTORY: /Users/dlipa/.rvm/gems/ruby-1.9.2-p180
  - RUBY EXECUTABLE: /Users/dlipa/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-10
  - GEM PATHS:
     - /Users/dlipa/.rvm/gems/ruby-1.9.2-p180
     - /Users/dlipa/.rvm/gems/ruby-1.9.2-p180@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://rubygems.org/", "http://gems.github.com"]
  - REMOTE SOURCES:
     - http://rubygems.org/
     - http://gems.github.com

Link to repo:
https://github.com/lightserve/volatilityApp

A: Are you running the same stack on heroku as locally? Heroku new apps defaulto mri ruby 187, afaik.  You might try migrating your heroku stack to 1.9.2. You can do that via:
heroku stack:migrate bamboo-mri-1.9.2

Next time you push to your heroku git repo, the stack will get migrated.
Can you give more information about what your app does? Is it spawning new processes or using threads?

A: I came to this thread because I had the same problem. In my case, the problem was an error in the "routes.rb" file.


text:
Q: How to write down the stationary law for CIR process via Gamma distribution? From the lecture is known:

The Cox-Ingersoll-Ross (CIR) process is the solution to the stochastic differential equation
$$
dX_t = (\theta_1 - \theta_2 X_t)dt + \theta_3 \sqrt{X_t} dW_t,  \quad X_0 = x_0 > 0,
$$
where $\theta_1$, $\theta_2$, $\theta_3 \in \mathcal{R}_+$.
The stationary distribution of the CIR process is a Gamma law with shape
parameter $2\frac{\theta_1}{\theta^2_3}$
and scale parameter $\frac{\theta_3^2} {2\theta_2}$.

Question:
Is it correct to write
\begin{equation}
X \sim Gamma\left(2\frac{\theta_1}{\theta^2_3}, \frac{\theta_3^2} {2\theta_2}\right)?
\end{equation}


text:
Q: Snowflake emoji is not showing correctly on browser I am trying to show the snowflake emoji, unicode U+2744, which when I do using CSS, is:
[emoji='snowflake']:after {
    content: '\2744';
}

However, it shows this emoji: ❄ - screenshot
If I copy the emoji from another source, it shows: ❄ - screenshot
Source for how this emoji should look on browser.
Which in my IDE looks like:
Why does it happen? How do I fix it?

A: I would suggest adding a background-image to your [emoji='snowflake']:after instead.
You can get a free to use snowflake icon here:
https://www.iconfinder.com/search/?q=snowflake&license=2&price=free


text:
Q: How to save the return value of a function attached to a tkinter Button? Background info
I am writing a set of tools to crack Vigenere cipher for a school project. There is a problem that I know I can solve if I could pass pointers like in C but I started this in Python and I don't want to rewrite everything. Code is on https://github.com/DarkFireGuy/cracking-vigenere if you want to see
The Problem
freq_analysis.py has a function _plot() that is used to plot and save the image. After pyplot has created the graph I check to see if the file has an extension. If it doesn't then I call simple_popup() from tools.py (small collection of nifty little functions). This call sends three pieces of information to a function that makes it easier for me to simplify tkinter use:

*

*A message to tell the user that the file name is bad and doesn't have an extension,

*Button labels to tell the user which one does what.

*Functions to tell each button what they're supposed to do.

If the user presses the button to enter a new name I would call simple_popup_input() (not written yet) to take the new input. But I cannot do that until I figure out how I would get the input into the fext (file extension). For now I am using exec to take user input and putting it into fext (txt on cml no fancy pants tkinter yet) but this fext is not the same fext from before. To fix all of this I need to be to write to the address at which fext is located. Google told me it wasn't possible in python so I have come to the council of smart people to see what I should do.
Solutions?

*

*Rewrite the whole thing in C

*Figure out how to get the memory address of fext

*(just came to me while writing this) write the new file extension to a temporary file and then read it after the simple_popup_input() call --- Don't want to do this because there has be a more elegant solution

*Don't know how it would work but to include two tuples which will contain arguments that get passed into func1 and func2. simple_popup header would become:
def simple_popup(message="Error", f1=lambda: True, f2=lambda: True, args1: tuple = (),
                 args2: tuple = (), option1: str = "Yes", option2: str = "No")

req_analysis.py problematic code snippet:
# Rename file if it does not contain an extension
output, fext = os.path.splitext(output)
if not fext:
    simple_popup(message="The file name you have chosen does not contain an extension",
                 f1=lambda: exec("fext = str(input(\"New extension: \"))"),
                 option1="Enter new name",
                 option2="Save without extension"
                     )
output = output+fext
print(output)

tools.py problematic code snippet:
def simple_popup(message="Error",
                 f1=lambda: True,
                 f2=lambda: True,
                 option1: str = "Yes",
                 option2: str = "No"):

    def func1():
        f1()
        popup.quit()

    def func2():
        f2()
        popup.quit()

    popup = tk.Tk()
    label = tk.Label(popup, text=message)
    button1 = tk.Button(popup, text=option1, command=func1)
    button2 = tk.Button(popup, text=option2, command=func2)

    for tmp in [label, button1, button2]:
        tmp.pack()

    popup.mainloop()

A: You are asking the wrong question. Your question should be "Is there a better way to do this?". There is. Use a messagebox.
import tkinter as tk
from tkinter import messagebox
import os

root = tk.Tk()

path = r'C:\Some\Path'
_, ext = os.path.splitext(path)

if not ext and not messagebox.askyesno('Missing Extension', 'Save without extension?'):
    #the user may provide a dot ~ strip it out and rely on our static dot
    path = f"{path}.{input('submit new extension: ').lstrip('.')}"

print(path)

root.mainloop()


text:
Q: Calculate the estimators of $E[X]$ and $Var[X]$ using the method of moments $(X_1,\dots, X_n)$ is a random sample extracted from a uniform distribution on the interval $$(\alpha-\beta, \alpha+\beta) \ \ \ \   \alpha \in \mathbb{R}, \beta \in \mathbb{R}^{+}$$

*

*Demonstrate that $E[X_1]$ depends only from $\alpha$ and $Var[X_1]$ depends only from $\beta$

*Calculate the estimators $T_1$ of $E[X_1](\alpha)$ and $T_2$ of $Var[X_1](\beta)$ using the method of moments

For 1. $X_1$ is a random variable of uniform distribution, so:
$$E[X_1]=\frac{\alpha-\beta+\alpha+\beta}{2}=\alpha$$
and
$$Var[X_1]=\frac{(\alpha+\beta-\alpha + \beta)^2}{12}=\frac{\beta^2}{3}$$
For 2. \begin{align}M_1'&=\overline{X}=T_1\\M_2'&=T_2+\overline{X}^2\end{align}
How can I continue the study of estimators?
Thanks!

A: First moment of the distribution is $μ_1=E[X]=α$ and the first moment of the sample is $m_1=\bar{X}$. So, set $$μ_1=m_1 \implies α=m_1$$ This is the first moment estimator for $α$. (Note: This method is confusing at the beginnning, because you think, ok so what? But think that $m_1$ is your sample mean and so it is known, it will be realized when you collect the sample and will give you a number.) Now, the second moment of the distribution is $$μ_2=E[X^2]=Var(X)+E[X]^2=\frac{β^2}{3}+α^2$$ and the second moment of the sample is $$m_2=\frac1n\sum_{i=1}^{n}X_i^2$$ Equating the second moments gives $$μ_2=m_2 \implies \frac{β^2}{3}+α^2=m_2$$ So, you obtained the system with two unknowns $α,β$ (I repeat that $m_1,m_2$ are known!) which you can solve \begin{cases}m_1=α\\m_2=\dfrac{β^2}{3}+α^2\end{cases}


text:
Q: How does Stack Exchange use MiniProfiler for recording profiles? I notice that at this post Are topics suggested on the homepage based on user history? @nick-craver said "we started recording profiles for random requests a while back".
I want to know more details about that, because I'm trying to use MiniProfiler for profiling every request and record them for analysis.
My application has some random performance issues, so I want to record every request and try to find out what happen when some requests go slow.
I'm want to record MiniProfiler results to a queue (in-memory, RabbitMQ, Redis, etc.) by implementing the StackExchange.Profiling.Storage.IStorage interface, log and analyse them. And I think the overhead of profiling every request should be acceptable. (I expect it would add less than 10 ms response time to every request and most requests will take at least 500 ms. I will run some performance test to ensure that.)


text:
Q: Compiling only edited files in linux terminal I am making a project in Linux OS with a lot of .cpp and .h files and the problem is that every time I want to compile and run the project I have to compile everything, otherwise it doesn't work. For example:

g++ main.cpp test.cpp test2.cpp test3.cpp test1.h test2.h test3.h -o
  main

Is there a way, when I only edit the main.cpp I do not have to re-compile everything like so

g++ main.cpp -o main

A: I recommend using makefiles for this job as they are phenomenal in building dependencies.
https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/makefile.html

A: If main.cpp uses code from test*.cpp, you can't just compile main.cpp. You can compile the individual files into object files using g++ -c test.cpp, and then link those files in with g++ main.cpp test.o test2.o test3.o -o main. If you learn to use make, you can automate this process to only recompile object files when needed.
Your header files should typically be #included in your source files, so you don't need to explicitly give them on the command line.

A: Incremental compilation is pretty standard and an engineering best practice. However, to achieve incremental compilation (at least in a sane and sustainable way that will actually save you time), you need to use a build system that can keep track of dependencies and determine which targets / inputs have changed since the last invocation of the build system and that can automatically invoke the compiler to compile and link only the targets that actually require updating.
For choice of build system, I recommend looking into Gradle (very popular in opensource projects) or Bazel (Google's  build system that was opensourced relatively recently, though it is less popular). Historically, Make (and systems to automate Makefile generation such as Autoconf and CMake) have been the common build systems, especially among C++ developers; however, these tools are declining in popularity and make for much more complicated build configurations as well as ease of shooting oneself in the foot compared to more modern build systems (for example, Gradle and Bazel have build configuration files that are portable across systems, whereas Makefiles make it relatively easy to inadvertently depend on OS-specific or compiler-specific details that render the build process non-portable. Make does have some very portable rules for avoiding portability issues, but great care must be used when designing makefiles to ensure that non-portable instructions are not used). For a more comprehensive list of C++ build systems, check out my C++ resources page.
As for how these build systems implement incremental builds under the hood; basically, they would compile each *.cpp file separately into its own *.o file and keep around the *.o file. Then each *.o file would be linked together to produce the final build output. Thus, only *.o files whose inputs are newer than the *.o file would be regenerated; similarly, only those libraries or executables whose *.o inputs are newer than the library or executable being generated would be recreated. In short, these build systems would do a fairly complex dependency analysis to figure out which files have changed / which targets to rebuild and would invoke g++ multiple times (not just once). This is why I highly recommend automating it with a build system rather than attempting to perform it by hand.


text:
Q: Body classes in child theme In the theme twentyfouteen, the full-width class is defined with the following code
if ( ( ! is_active_sidebar( 'sidebar-2' ) )
|| is_page_template( 'page-templates/full-width.php' )
 || is_page_template( 'page-templates/contributors.php' )
 || is_attachment() ) {
 $classes[] = 'full-width';
 }

from this function
function twentyfourteen_body_classes( $classes ) {
if ( is_multi_author() ) {
    $classes[] = 'group-blog';
}

if ( get_header_image() ) {
    $classes[] = 'header-image';
} else {
    $classes[] = 'masthead-fixed';
}

if ( is_archive() || is_search() || is_home() ) {
    $classes[] = 'list-view';
}

if ( ( ! is_active_sidebar( 'sidebar-2' ) )
    || is_page_template( 'page-templates/full-width.php' )
    || is_page_template( 'page-templates/contributors.php' )
    || is_attachment() ) {
    $classes[] = 'full-width';
}

if ( is_active_sidebar( 'sidebar-3' ) ) {
    $classes[] = 'footer-widgets';
}

if ( is_singular() && ! is_front_page() ) {
    $classes[] = 'singular';
}

if ( is_front_page() && 'slider' == get_theme_mod( 'featured_content_layout' ) ) {
    $classes[] = 'slider';
} elseif ( is_front_page() ) {
    $classes[] = 'grid';
}

return $classes;
}
add_filter( 'body_class', 'twentyfourteen_body_classes' );

I'm adding a selection of sidebars to the sidebar-content.php file. These sidebars must also have the same body class as sidebar-2. Is it correct for me to just use a different fuction name as to that of the twentyfourteen theme and to still hook on the body_class, keep the same class name (full-width), and change the above code in a child theme to
if ( ( ! is_active_sidebar( 'sidebar-2' ) &&  ! is_active_sidebar( $sidebar_option ) )
 || is_page_template( 'page-templates/full-width.php' )
 || is_page_template( 'page-templates/contributors.php' )
|| is_attachment() ) {
 $classes[] = 'full-width';
 }

I'm getting a lot of stuff that tells me how to ad a new body class and removing one, but nothing on how to change an existing body class of a parent theme in a child theme or if it is even possible

A: Thank you for all the insets with this question. Here is what I come up with working from 1fixdotio's answer above. I first had to unset the full-width body class and then register a new body class to incorporate my new sidebar. Here is the code
  // Remove body class and register new body class to accomodate the new custom-sidebar-per-page sidebars
function remove_a_body_class($classes) {
      foreach($classes as $key => $value) {
      if ($value == 'full-width') unset($classes[$key]);
      }
return $classes;
}

add_filter('body_class', 'remove_a_body_class', 20, 2);

function pietergoosen_add_new_body_class( $classes ) {
$options = get_post_custom($post->ID);
$sidebar_choice = $options['custom_sidebar_per_page'][0];
    if ( (! is_active_sidebar( 'sidebar-2' ) && ! is_active_sidebar( $sidebar_choice ) )
        || is_page_template( 'page-templates/full-width.php' )
        || is_page_template( 'page-templates/contributors.php' )
        || is_attachment() ) {
        $classes[] = 'custom-sidebar-per-page-width';
    }

    return $classes;
}
add_filter( 'body_class', 'pietergoosen_add_new_body_class' );

A: Let's say if you don't like the default page body class which comes with WP by default, you could do this in your filter function:
if ( ( ! is_active_sidebar( 'sidebar-2' ) &&  ! is_active_sidebar( $sidebar_option ) )
 || is_page_template( 'page-templates/full-width.php' )
 || is_page_template( 'page-templates/contributors.php' )
|| is_attachment() ) {
    if(($key = array_search( 'page', $classes)) !== false) {
        unset($classes[$key]); // Unset what you don't need
    }
    $classes[] = 'full-width'; // Add what you want
}

Or you could do this if you want to remove ALL body classes come with WP:
if ( ( ! is_active_sidebar( 'sidebar-2' ) &&  ! is_active_sidebar( $sidebar_option ) )
 || is_page_template( 'page-templates/full-width.php' )
 || is_page_template( 'page-templates/contributors.php' )
|| is_attachment() ) {
    $classes = array( 'full-width' ); // Don't use default array, set a new one
}

Hope I didn't get you wrong.


text:
Q: Looking for Mac Typing software that supports Spanish keyboard layouts - Recommendations? I've moved from Windows to the Mac a while ago, and in this "self-improvement" path, I've also realized that I need to learn to touch-type (I can do around 50-60 WPM with 3-and-a-half fingers, but I need more).
I'm a Spanish speaker so I need to learn on a Spanish keyboard. I've already seen the answer to a similar question here (Looking for a typing tutor app) but all the answers offered assume English keyboards
I'm looking for a more "guided" learning approach.

A: Maybe this is what you are looking for:


text:
Q: Knockout bind error, unable to bind viewModel inside iFrame I'm trying to bind a knockout template and just cannot break the problem down, there are a million thing that I've tried.
and I'm pretty lost at the moment for any ideas, I've been debugging it since days.
The same template is also fetched on some other page and it works fine.
I've tried printing the $data object and it shows that the data is available, however on that same template it does not bind
the values.
I get a Uncaught TypeError: Unable to process binding "with: function (){return selectedView }"
Message: Unable to process binding "template: function (){return {name:templateName,data:data} }"
basically a chain of error from there as the template is not binded.
here's some of the view code :
#page-hold{data: {role: 'page', theme: 'a'}}
  .container{ "data-bind" => "with: selectedView"}
    %div{ "data-bind" => "template : {name: templateName, data: data}" , data: {role: 'content'}}

%script{ "id" => "tpl_landing", "type" => "text/html"}

//html partials

Data object looks like this
{
  "views": [
    {
      "title": "landing",
      "templateName": "tpl_landing",
      "data": {
        "base": {
        /// data
        }

Latest Update: I've gained deeper insight of the problem and after debugging a bit more I've found out that the viewModel($data object) can be accessed inside the iframe but it does not bind or output anything on the page apart from the $data object, which gives me a JSON of all the data. Would like to know why the data is not getting binded when I can see it exists.
Anyone who can help me debug this?
Thank you

A: Knockout supports cross-window binding (sharing a view model between windows), but it doesn't directly support sharing templates between windows. (You could probably write a custom templateEngine, but that's pretty advanced.)
I came up with a binding that applies a template and binds the <iframe> that I think will do what you want.
ko.bindingHandlers.iframeTemplate = {
    update: function (element, valueAccessor) {
        var iframedoc = element.contentDocument,
            options = valueAccessor(),
            templateSource = ko.templateEngine.prototype.makeTemplateSource(ko.unwrap(options.template)),
            templateText = templateSource.text(),
            templateNodes = ko.utils.parseHtmlFragment(templateText, iframedoc),
            iframebody = iframedoc.body;

        ko.virtualElements.setDomNodeChildren(iframebody, templateNodes);
        ko.applyBindings(options.data, iframebody);
    }
};

Usage example: http://jsfiddle.net/mbest/udhm4qj4/


text:
Q: Error in installing OpenStack using devstack in centos7 Im trying to install OpenStack using Devstack in CentOS 7 ,Im using  the following documentation as the guide, but im encountering an error which is shown.This is the output while running ./stack.sh.Im running./clean.sh and ./unstack.sh before running ./stack.sh.
Obtaining file:///opt/stack/keystone
    Complete output from command python setup.py egg_info:
    ERROR:root:Error parsing
    Traceback (most recent call last):
      File "/usr/lib/python2.7/site-packages/pbr/core.py", line 96, in pbr
        attrs = util.cfg_to_args(path, dist.script_args)
      File "/usr/lib/python2.7/site-packages/pbr/util.py", line 259, in cfg_to_args
        pbr.hooks.setup_hook(config)
      File "/usr/lib/python2.7/site-packages/pbr/hooks/__init__.py", line 25, in setup_hook
        metadata_config.run()
      File "/usr/lib/python2.7/site-packages/pbr/hooks/base.py", line 27, in run
        self.hook()
      File "/usr/lib/python2.7/site-packages/pbr/hooks/metadata.py", line 26, in hook
        self.config['name'], self.config.get('version', None))
      File "/usr/lib/python2.7/site-packages/pbr/packaging.py", line 839, in get_version
        name=package_name))
    Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given to pbr.version.VersionInfo. Project name keystone was given, but was not able to be found.
    error in setup command: Error parsing /opt/stack/keystone/setup.cfg: Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given to pbr.version.VersionInfo. Project name keystone was given, but was not able to be found.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /opt/stack/keystone/
You are using pip version 9.0.3, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
+inc/python:pip_install:1                  exit_trap
+./stack.sh:exit_trap:515                  local r=1
++./stack.sh:exit_trap:516                  jobs -p
+./stack.sh:exit_trap:516                  jobs=
+./stack.sh:exit_trap:519                  [[ -n '' ]]
+./stack.sh:exit_trap:525                  '[' -f '' ']'
+./stack.sh:exit_trap:530                  kill_spinner
+./stack.sh:kill_spinner:425               '[' '!' -z '' ']'
+./stack.sh:exit_trap:532                  [[ 1 -ne 0 ]]
+./stack.sh:exit_trap:533                  echo 'Error on exit'
Error on exit
+./stack.sh:exit_trap:535                  type -p generate-subunit
+./stack.sh:exit_trap:536                  generate-subunit 1545131409 150 fail
+./stack.sh:exit_trap:538                  [[ -z /opt/stack/logs ]]
+./stack.sh:exit_trap:541                  /opt/stack/devstack/tools/worlddump.py -d /opt/stack/logs
World dumping... see /opt/stack/logs/worlddump-2018-12-18-111239.txt for details
+./stack.sh:exit_trap:550                  exit 1


text:
Q: Dependent DropDown Angular i`m creating dynamic dropdown box i have 2 dropdown each of my dropdown have a different data once i selected it it will channge the other data depending on what you select in the first dropdown how to achieve that?
i tried this code but it gaves me a undentified
.TS

this is what iwanted to put in my dropdown box once i click the SERVICEABLE it will populate all the maintenance,upgrage,repairable and once i click the UNSERVICEABLE it will change it to another data and list all unserviceable
[
  {
    "id": 1,
    "assetID": 9,
    "tranType": "MAINTENANCE",
    "assetConditionType": {
      "id": 9,
      "assetConditionType": "SERVICEABLE"
    }
  },
  {
    "id": 2,
    "assetID": 9,
    "tranType": "UPGRADE",
    "assetConditionType": {
      "id": 9,
      "assetConditionType": "SERVICEABLE"
    }
  },
  {
    "id": 3,
    "assetID": 9,
    "tranType": "REPAIRABLE",
    "assetConditionType": {
      "id": 9,
      "assetConditionType": "SERVICEABLE"
    }
  },
  {
    "id": 4,
    "assetID": 10,
    "tranType": "DISPOSAL",
    "assetConditionType": {
      "id": 10,
      "assetConditionType": "UNSERVICEABLE"
    }
  },
  {
    "id": 5,
    "assetID": 10,
    "tranType": "WRITTEN-OFF",
    "assetConditionType": {
      "id": 10,
      "assetConditionType": "UNSERVICEABLE"
    }
  },
  {
    "id": 6,
    "assetID": 10,
    "tranType": "RETIRED",
    "assetConditionType": {
      "id": 10,
      "assetConditionType": "UNSERVICEABLE"
    }
  }
]

assetDS: AssetCondtionDTO[];
  assetObj: any;

'selectedType(trigger: MatSelectChange) {
  this.assetObj = trigger.value;

  const selectedItem = this.assetDS.find((x) => x.tranType.assetID == trigger.value);
  if (selectedItem) this.serviceLogArray.get('tranType').patchValue(selectedItem.id);
  console.log(this.assetObj)
}
assetCondition(){
  this.serviceSVC.getAssetCondition(5,10).subscribe((res: AssetCondtionDTO) => {
    this.assetObj = res;
  })
}'

HTML

  <mat-select formControlName="assetCondition" style="width:200px;padding:10px"
           (selectionChange)="selectedType($event)">
      <mat-option ngFor="let items of assetObj" [value]="items.id">
          {{items.id}}
      </mat-option>
  </mat-select>

<mat-select formControlName="tranType" style="width:200px;padding:10px">
     <mat-option ngFor="let items of assetObj" [value]="items.tranType.assetID">
       {{items.tranType.tranType}}</mat-option></mat-select> 	 ```

A: Code portion of your question is unclear and we can't understand written logic but from your description, I provide you an example to filter a fake list base on another select form control:
Template:
<form [formGroup]="formGroup">

    <mat-select formControlName="assetCondition" style="width:200px;padding:10px"
             (selectionChange)="selectedType($event)">
        <mat-option *ngFor="let items of assetConditionTypes" [value]="items.id">
            {{items.assetConditionType}}
        </mat-option>
    </mat-select>

    <mat-select formControlName="tranType" style="width:200px;padding:10px">
         <mat-option *ngFor="let items of filteredAssets" [value]="items.assetID">
           {{items.tranType}}
          </mat-option>
         <mat-option *ngIf="filteredAssets.length===0">
           Pleas select type first!
          </mat-option>
    </mat-select>

</form>

TS:
formGroup: FormGroup = new FormGroup({
    assetCondition: new FormControl(''),
    tranType: new FormControl('')
  });

  selectedType(trigger: MatSelectChange) {
    this.filteredAssets = this.myAssets.filter((asset) => asset.assetConditionType.id == +trigger.value);
    console.log(this.filteredAssets);
  }

  assetConditionTypes = [
    {
    "id": 9,
    "assetConditionType": "SERVICEABLE"
    },
    {
      "id": 10,
      "assetConditionType": "UNSERVICEABLE"
    }
  ];

  filteredAssets: any[] = [];

  myAssets = [
    {
      "id": 1,
      "assetID": 9,
      "tranType": "MAINTENANCE",
      "assetConditionType": {
        "id": 9,
        "assetConditionType": "SERVICEABLE"
      }
    },
    {
      "id": 2,
      "assetID": 9,
      "tranType": "UPGRADE",
      "assetConditionType": {
        "id": 9,
        "assetConditionType": "SERVICEABLE"
      }
    },
    {
      "id": 3,
      "assetID": 9,
      "tranType": "REPAIRABLE",
      "assetConditionType": {
        "id": 9,
        "assetConditionType": "SERVICEABLE"
      }
    },
    {
      "id": 4,
      "assetID": 10,
      "tranType": "DISPOSAL",
      "assetConditionType": {
        "id": 10,
        "assetConditionType": "UNSERVICEABLE"
      }
    },
    {
      "id": 5,
      "assetID": 10,
      "tranType": "WRITTEN-OFF",
      "assetConditionType": {
        "id": 10,
        "assetConditionType": "UNSERVICEABLE"
      }
    },
    {
      "id": 6,
      "assetID": 10,
      "tranType": "RETIRED",
      "assetConditionType": {
        "id": 10,
        "assetConditionType": "UNSERVICEABLE"
      }
    }
  ];

A: First you need transform your data "grouping" in an object like
  [
    {
      "id": 9,
      "assetConditionType": "SERVICEABLE",
      "items": [
        {
          "id": 1,
          "assetID": 9,
          "tranType": "MAINTENANCE"
          "assetConditionType": {
            "id": 9,
            "assetConditionType": "SERVICEABLE"
          }
        },
        ...
      ]
    }
    ...
  ]

For this we use reduce. Reduce it's no so complex looks like. Imagine you has an array data
const dataTransformed=data.reduce((a,b)=>{
   return function(a,b)
},initial)

If like a loop
   let a=initial
   for (let i=0;i<data.length;i++)
   {
     b=data[i];
     a=function(a,b)
   }
   const dataTransformed=a

So you can use reduce and rxjs map operator in the way
getData(){
   return this.httpClient.get(..your url...).pipe(
      map((data: any[]) => {
        const groupData=data.reduce((a: any, b: any) => {
          const id = b.assetConditionType.id;
          const element = a.find((x: any) => x.id == id);

          if (element) element.items.push(b);
          else
          {
          a.push({
              id: id,
              assetConditionType: b.assetConditionType.assetConditionType,
              items: [b],
            });
          }
          return a;
        }, []);
        return groupData
      })
    );
  }

One time you has your data grouped, as you has a few data you can use some like
<mat-form-field appearance="fill">
  <mat-label>Asset</mat-label>
  <mat-select [(ngModel)]="value" (selectionChange)="value2=null">
    <mat-option *ngFor="let item of obs|async" [value]="item">
      {{item.assetConditionType}}
    </mat-option>
  </mat-select>
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Transation</mat-label>
  <mat-select [(ngModel)]="value2">
    <mat-option *ngFor="let item of value?.items" [value]="item">
      {{item.tranType}}
    </mat-option>
  </mat-select>
</mat-form-field>

See that "value" has the whole object grouped, so we can use value.items to give value to the options of the second dropdown
I use [(ngModel)] you can use ReactiveForms. If only are interesting in the "items" only use a FormControl to get the item.
Some like
form=new FormGroup({
   asset:new FormControl()
})

<form [formGroup]="form">
    <mat-form-field appearance="fill">
      ...
      <mat-select [(ngModel)]="value" (selectionChange)="value2=null">
                   [ngModelOptions]="{standalone:true}"
        <mat-option *ngFor="let item of obs|async" [value]="item">
          {{item.assetConditionType}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <mat-form-field appearance="fill">
      ...
      <mat-select formControlName="asset">
        <mat-option *ngFor="let item of value?.items" [value]="item">
          {{item.tranType}}
        </mat-option>
      </mat-select>
    </mat-form-field>
</form>

See that the "value" is not belong to the form (it's only a auxiliar variable). As not belong to the form you use [(ngModel)] and [ngModelOptions]="{standalone:true}"
NOTE: If you only want the "id" use in the second dropdown [value]="item.id"
a stackblitz
Update If we want the "two values", the "id" and the "assetID" we can take three aproach

*

*Store in the formControl an object with this two values
  form=new FormGroup({
    control:new FormControl()
  })

<form [formGroup]="form">
  <mat-form-field appearance="fill">
    <mat-label>Asset</mat-label>
    <mat-select
      [(ngModel)]="value"
      [ngModelOptions]="{standalone:true}"
      (selectionChange)="form.get('control')?.setValue(null)"
    >
      <mat-option *ngFor="let item of obs|async" [value]="item">
        {{item.assetConditionType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <mat-form-field appearance="fill">
    <mat-label>Transation</mat-label>
    <mat-select formControlName="control">
      <mat-option
        *ngFor="let item of value?.items"
        [value]="{id:item.id,assetID:item.assetID}"
      >
        {{item.tranType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</form>

*Use the event (changeEnd) to give value to the formControl
form2=new FormGroup({
    assetID:new FormControl<number|null>(null),
    id:new FormControl<number|null>(null),
  })
<form [formGroup]="form2">
  <mat-form-field appearance="fill">
    <mat-label>Asset</mat-label>
    <mat-select
      [(ngModel)]="value"
      [ngModelOptions]="{standalone:true}"
      (selectionChange)="form2.get('assetID')?.setValue(value.id);form2.get('id')?.setValue(null)"
    >
      <mat-option *ngFor="let item of obs|async" [value]="item">
        {{item.assetConditionType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <mat-form-field appearance="fill">
    <mat-label>Transation</mat-label>
    <mat-select formControlName="id">
      <mat-option
        *ngFor="let item of value?.items"
        [value]="item.id"
      >
        {{item.tranType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</form>

*Or use two auxiliar variables: one with all the options and another one with the selected option
  options: any[] = [];
  selectedOptions: any[];

  form3=new FormGroup({
    assetID:new FormControl<number|null>(null),
    id:new FormControl<number|null>(null),
  })
  ngOnInit() {
    this.dataService.getData().subscribe((res: any[]) => {
      this.options = res;
    });
  }

  getOptions(value: any) {
    this.selectedOptions = this.options.find((x) => x.id == value).items;
  }

<form [formGroup]="form3">
  <mat-form-field appearance="fill">
    <mat-label>Asset</mat-label>
    <mat-select
      formControlName="assetID"
      (selectionChange)="getOptions($event.value)"
    >
      <mat-option *ngFor="let item of options" [value]="item.id">
        {{item.assetConditionType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <mat-form-field appearance="fill">
    <mat-label>Transation</mat-label>
    <mat-select formControlName="id">
      <mat-option
        *ngFor="let item of selectedOptions"
        [value]="item.id"
      >
        {{item.tranType}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</form>

see a new stackblitz


text:
Q: Django ForeignKey getting results I've tried following other questions but I'm still having some problems.
I have 2 models:
class Media(models.Model):
    name = models.CharField(max_length=100)
    media = models.CharField(max_length=10, choices=MEDIA_TYPE)

class Review(models.Model):
    message = models.CharField(max_length=10)
    submitter = models.ForeignKey(User)
    media = models.ForeignKey(Media, related_name='rev_media')

I want to go do something like
blaw = Media.objects.all()
for a in blaw:
    print (all the reviews to have to do with this one media object)

A: rev_media, your related_name, should give you all the reviews that have it as a foreign key:
blaw = Media.objects.all()
for a in blaw:
    print media.rev_media.all()

A: Since you have a related_name, you can use a.rev_media.all() to get the list of associated objects.
Now, you can do:
media_qs = Media.objects.all()
for media in media_qs:
    reviews = media.rev_media.all() #basically, this is the queryset of all the associated reviews for this media object.
    if reviews.exists():

        print ", ".join([review.message for review in reviews])


text:
Q: PHP MySQL - select where id not equal to two one of 2 ids So I'm trying to pick 2 rows randomly but the id isn't allowed to be equal to x or equal to y.
That's what I tried so far:
  $statment = $db -> "SELECT * FROM player ORDER BY RAND() LIMIT 2 WHERE
              NOT(id = ?) OR WHERE NOT(id=?)";
  $statement->execute(array($player1, $player2));

But getting:

Parse error: syntax error, unexpected '"SELECT * FROM player ORDER BY' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE)

A: You need AND to make sure it is not equal <> to both:
WHERE id <> ? AND id <> ?

Or check if it is not IN a list:
WHERE id NOT IN(?, ?)

And I'm not sure about the order of the SQL statement, try:
SELECT * FROM player WHERE id <> ? AND id <> ?
         ORDER BY RAND() LIMIT 2

Also, you're missing something like maybe prepare:
$statement = $db->prepare("SELECT * FROM player WHERE id <> ? AND id <> ?
                                   ORDER BY RAND() LIMIT 2");

A: Use NOT IN. You're also missing the call to prepare().
$statment = $db ->prepare("SELECT * FROM player
                    WHERE id NOT IN (?, ?)
                    ORDER BY RAND()
                    LIMIT 2");

Also, the order of clauses in a SELECT statement is:
SELECT
FROM
JOIN
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT


text:
Q: Bulk inserts fail while switching partitions I have a partitioned table. parttiion key is SiteID.
I load data from different sites concurrently. I first truncate a partition (tried both partition truncation and partition switching) and then load data to that partition.
This is doneby SSIS.
Sometimes while loading data,another session truncates a different partition belonging to the same table.
The partition truncation raises the followingerror:

An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record
  is available.  Source: "Microsoft SQL Server Native Client 11.0"
  Hresult: 0x80004005  Description: "Insert bulk failed due to a schema
  change of the target table.".

Is there any way to prevent that issue?


text:
Q: Ubuntu authentication via active directory I have a bunch of Ubuntu machines and an active directory on Windows server 2012. I would like to setup a centralize authentication from my active directory. Basically, When the user tries to login a Linux computer. The authentication credentials are sent my windows server 2012 for the check. If the user credential is correct, active directory accepts the authentication an user can login Linux computer. Otherwise, the user cannot get access. The goal is to have all user in the same place so that It would be easy to block users in the same place instead of going on every single computer. There are tools like PAM, Kerberos, ... But I don't know to the right direction to take now.
I have never done this but I think it is possible and It could make life easier.
Please give me some tutorial or just idea on how to find a solution.
Thanks


text:
Q: Magento - Sort products by "Attribute Set" In Magento's category list page, it is possible to sort products by Attribute Set?
Thanks a lot.

A: Whether it be in the front-end or for the Admin section, your requirement of sorting products based on Attribute Set List will go for custom development, as Magento does not provide this sort of thing by default.
You need to understand that the Attribute Set concept was provided for only the creation of Catalog Products, so that the Administrator can segregate / group the attribute(s), as needed for its store.
So if you understand the basic logic here, then you will find that for grouping each products, the concept of category is useful & not the Attribute Set List.
Hope it helps.


text:
Q: How to use the start command in a batch file? I have a batch file that starts an app with a lot of command-line parameters:
"C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.exe" /port:1672 /path:"C:\Code.Net\My App\Iteration 6\REL_6.8.806_PerfEnhanceV\Fusion\Code\CC.Fusion\CC.Fusion.Services" /vpath:"/FusionServices"

The problem is that when I run the batch file, the DOS window stays up until the command completes and I would like it to go away.  So I tried using the start command, but placing it in front, like this:
start "C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.exe" /port:1672 /path:"C:\Code.Net\My App\Iteration 6\REL_6.8.806_PerfEnhanceV\Fusion\Code\CC.Fusion\CC.Fusion.Services" /vpath:"/FusionServices"

But I get an error stating that Invalid switch - "/port:1672"
I have also tried escaping the double quotes, but I was not successful.
How do I fix that?

A: An extra pair of rabbits' ears should do the trick.
start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

A: I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B and /C options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1


text:
Q: How to pass error from TypeConverter to ModelState errors I have implemented a TypeConverter to deserialize a type from string in query.
The type contains Guid and Guid in string could be invalid, so I want to pass error to ModelState.
I try to throw new ArgumentException("my message"), and it's working, but the error message from the exception is not passed to ModelError.ErrorMessage. Is there any way to pass the error message into ModelError.ErrorMessage or can I only get the message from ModelError.Exception.Message?

A: Ok I see what you're trying to do.
Since the builtin ModelBinder will capture the inner exception of FormatException, in order to set the ModelError.ErrorMessage, we could throw(or re-throw) an new exception of FormatException. For example,

public class MyConverter : TypeConverter
{
    ...

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
        {
            try{
                ...
                return new MyClass(x);
            }
            catch(Exception e){
                throw new FormatException("Ouch: sth happens");  // throw a FormatException
            }
        }
        return base.ConvertFrom(context, culture, value);
    }
    ...

For more details, see source code:


text:
Q: linq to xml how to move one element from one xml to another i am facing one problem
i have two xml files.
Plugins.xml
<SolutionProfile xmlns="http://schemas.microsoft.com/pag/cab-profile">
      <Modules>
        <ModuleInfo AssemblyFile="PluginXXX.dll" />
      </Modules>
    </SolutionProfile>

ProfileCatalog.xml
<SolutionProfile xmlns="http://schemas.microsoft.com/pag/cab-profile/2.0">

    <Modules>
      <ModuleInfo AssemblyFile="Module.dll" />
    </Modules>

    <Dependencies>
      <Dependency Name="Services" />
    </Dependencies>
    <Modules>
      <ModuleInfo AssemblyFile="PluginABC.dll" >
    </Modules>

</SolutionProfile>

i wants to move PluginXXX.dll from Plugins.xml to ProfileCatalog.xml.
the code i used is as
public static void PluginLoaded(string pluginName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;

            XDocument pluginDoc = XDocument.Load("Plugins.xml");
            XDocument profileCatalogDoc = XDocument.Load("ProfileCatalog.xml");

            XmlWriter pluginDocXmlWriter = XmlWriter.Create("Plugins.xml", settings);
            XmlWriter profileCatalogDocXmlWriter = XmlWriter.Create("ProfileCatalog.xml", settings);

            XNamespace ns = "http://schemas.microsoft.com/pag/cab-profile";

            var res = from plugin in pluginDoc.Descendants(ns + "ModuleInfo")
                      where plugin.Attribute("AssemblyFile").Value == pluginName
                      select plugin;

            // save the plugin to remove
            XElement pluginToMove = res.FirstOrDefault();

            //remove from xml
            res.FirstOrDefault().Remove();

            // save xml back
            pluginDoc.Save(pluginDocXmlWriter);

            XNamespace pns = "http://schemas.microsoft.com/pag/cab-profile/2.0";

            var pRes = ((from pcPlugin in profileCatalogDoc.Descendants(pns + "Modules")
                         select pcPlugin).Skip(1).Take(1)).FirstOrDefault();

            pRes.Add(pluginToMove);

            profileCatalogDoc.Save(profileCatalogDocXmlWriter);
            //TODO : move the plugin name from Plugins.xml to ProfileCatalog.xml

            profileCatalogDocXmlWriter.Close();
            pluginDocXmlWriter.Close();
        }

NOTE there is xmlns difference between both files.
when i move the node from Plugins.xml to ProfileCatalog.xml it adds the element as
<ModuleInfo AssemblyFile="PluginXXX.dll" xmlns="http://schemas.microsoft.com/pag/cab-profile" />

I want to remove this xmlns before adding to this file.
kindly give me a solution.

A: Solution
while creating a new node to move in ProfileCatalog.xml
i replaced
 pRes.Add(pluginToMove);

with
pRes.Add(new XElement(pns+ "ModuleInfo", new XAttribute("AssemblyFile", pluginToMove.Attribute("AssemblyFile").Value)));


text:
Q: Copy a range of cells after meeting criteria I need to do a copy of a range of cell after meeting the conditions as follows:
whenever Cells(15,15) of sheet1 is equals to cells(14,j). Firstcell will be equals to cells(14,j). Same concepts for secondcell.
After that I will need to do a copy of the cells between Firstcell and Secondcell. This is when I start to see the runtime error 91.
Assume that I have defined lastCol. My code:
Dim firstcell as range, secondcell as range

If Sheets("Sheet1").Cells(15, 10) <> "" And Sheets("Sheet1").Cells(15, 15) <> "" Then

    For j = 10 To lastCol

        If Sheets("Sheet1").Cells(15, 15).Text = Sheets("Sheet1").Cells(14, j).Text Then

            firstcell = Sheets("Sheet1").Cells(15, j)

        End If

        If Sheets("Sheet1").Cells(15, 13).Text = Sheets("Sheet1").Cells(14, j).Text Then

            secondcell = Sheets("Sheet1").Cells(15, j)

        End If

    Range(firstcell, secondcell ).copy

    Next j

End If

A: Answer determined from comments:
Dim firstcell as range, secondcell as range

If Sheets("Sheet1").Cells(15, 10) <> "" And Sheets("Sheet1").Cells(15, 15) <> "" Then
    For j = 10 To lastCol
        If Sheets("Sheet1").Cells(15, 15).Text = Sheets("Sheet1").Cells(14, j).Text Then
            set firstcell = Sheets("Sheet1").Cells(15, j)
        End If

        If Sheets("Sheet1").Cells(15, 13).Text = Sheets("Sheet1").Cells(14, j).Text Then
            set secondcell = Sheets("Sheet1").Cells(15, j)
        End If
    Next j
    Range(firstcell, secondcell ).copy
End If


text:
Q: Locating flash chip for dumping firmware I'm trying to dip my toes into reversing and thought that dumping and inspecting the firmware running on this controller/pcb would be fun learning, however I'm having trouble locating the flash chip. Any advice where to start?
Back story: this is a IR device to regulate different air conditioners via sms. I've sampled the IR codes and are running it on a esp8266 but the results sometimes vary when sending the codes, hence why I would like to inspect the firmware.


text:
Q: Dynamically rendering unknown quantity of different components in angular I have to build an app that dynamically renders a set of components using angular 4. The app should get a config from an API call and render the correct components according to config and pass data to each component.
The quantity, type and order of components to render is known only at run time.
I need to decide between:

*

*ngFor that contains many ngIf for every type of "dynamic" component.

*Using dynamic component loader to inject the components (is it possible if number of components is not known at build time?)

Which is the best approach?
Thanks!