text:
Q: How to get the summation of iterated FormArray I'm having a function where it gathers values from specific input, this input is a part of FormArray within FormGroup (nested), the function is like this
addSales(){

 this.itemsArray.controls.findIndex(i => {

    this.totalPrice =parseFloat(i.get('price').value)

    console.log(this.totalPrice)

}
  )}

when adding multiple values like : 10,20,30 I get them printed like this
10
20
30

All what I need is returning the sum of these values, which is 60, would you please advise me how to do it

A: From a philosophical perspective, there's a few things I'd recommend changing about the code:

*

*follow a functional paradigm (no side effects)

*use reduce instead of findIndex for generating a new value from iterating over an array (see reduce docs)
Right now the addSales function is performing two roles: (1) iterating through itemsArray and (2) updating this.totalPrice for each item in itemsArray. It makes the code harder to test because there's a lot going on.
Instead, I'd recommend doing the following:
addSales(): number {
  return this.itemsArray.controls.reduce((sum, i) => {
    sum += parseFloat(i.get('price').value)
    return sum;
  }, 0);
}

handleInputChange() {
  this.totalPrice = this.addSales();
}

Once handleInputChange is bound to your input change in the template, you will be able to more easily see what the code is doing (thereby debugging it easily).

A: += instead of = after this.totalPrice


text:
Q: Importing data from Excel to SQL through webpage - Searching for phrases Very low-level programmer tasked with handling something I don't really understand, here.
My company has a webpage that takes a customer's Excel document, reads the data, and moves it to a SQL database. It isn't too sophisticated: it apparently looks for data in a particular cell (e.g., "The cell below the column named "OrderNumber") using Excel's Name Manager as a guide.
If IsDBNull(xlRS.Fields("OrderNumber").Value) OrElse IsNothing(xlRS.Fields("OrderNumber").Value) Then
    strPartNumber = ""
Else
    strPartNumber = Trim(xlRS.Fields("OrderNumber").Value)

However, each of the customers that will be using this page uses a slightly different Excel form. Although every one will have an "Order Number" column, its location on the form will vary from customer to customer. Most of them can't be persuaded to use our standardized template, so I need to find out if there's a better way to do this.
I'm not sure whether I'm putting this correctly, but using VB.net, is it possible to locate an Excel form cell by searching for a phrase (e.g., "Order"), instead of providing an exact location? If not, what could be used to get around that limitation?

A: You could you ADO.NET with the appropriate data provider if the data is in a tabular format.  I do this sort of thing all the time and it works really well but only if the data is a simple table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fixed attribute when instantiating a model as parameter I want to instantiate a complex model as a parameter in another model and initialize it within the initial equation section, like I am able to do with any Real parameter. For a simple Real parameter I would just write
parameter Real y(fixed = true);

indicating that y should be computed at initialization time by using initial equations (to be defined...). But I can't do that for a complex model, i.e.
parameter ComplexModel m(fixed = true);

does not compile. Consider for example the following flat model
model FlatModel
  parameter Real x = 4;
  parameter Real y(fixed = false);
  Real z;
  // ... + many other model elements
initial equation
  y*y = x;
  // ... + many other equations
equation
  z*z = 4*x;
end FlatModel;

Here the implicit solution y=2 is computed at initialization time whereas the solution z=4 is computed in a time dependent manner (at least in principle, possible optimizations notwithstanding...). But both represent basically the same quadratic relationship, so I want to encapsulate this equation into a separate model (note that not every such equation system is as simple as in this example):
model ComplexModel
  Real x(fixed = false);
  Real y(fixed = false);
equation
  y * y = x;
end ComplexModel;

and try to use it this way:
  model RefactoredFlatModel
    parameter Real x = 4;
    parameter Real y(fixed = false);
    Real z;
    parameter ComplexModel mStatic;
    ComplexModel mDynamic;
  initial equation
    mStatic.x = x;
    y = mStatic.y;
  equation
    mDynamic.x = 4*x;
    z = mDynamic.y;
  end RefactoredFlatModel;

But this doesn't seem to work (compiler reports overdertermined system). Checking the model flattened by the compiler shows why:
class FixedTests.RefactoredFlatModel
  parameter Real x = 4.0;
  parameter Real y(fixed = false);
  Real z;
  parameter Real mStatic.x(fixed = false);
  parameter Real mStatic.y(fixed = false);
  Real mDynamic.x(fixed = false);
  Real mDynamic.y(fixed = false);
initial equation
  mStatic.x = x;
  y = mStatic.y;
equation
  mStatic.y ^ 2.0 = mStatic.x;
  mDynamic.y ^ 2.0 = mDynamic.x;
  mDynamic.x = 4.0 * x;
  z = mDynamic.y;
end FixedTests.RefactoredFlatModel;

So mStatic.y ^ 2.0 = mStatic.x is put to the (time dependent) equation section instead of the initial equation section, where I wanted it to be. It is clear that the model is overdetermined because it tries to solve for mStatic.y in time although mStatic.y is a parameter and thus is time invariant.
Is there any way to tell the modelica compiler to turn equations into initial equations for parameter instances? Because otherwise it is not possible to define parameter instances of complex models implicitly.

A: As of Modelica Specification v3.4, this is invalid Modelica, since the prefix parameter must not be used with the specialized class model.
There are some proposals to improve this behavior (and meet your requirement), see https://github.com/modelica/ModelicaSpecification/issues/2311 and its source https://github.com/modelica/ModelicaStandardLibrary/issues/1860.

A: Edit (2019-02-30): Don't use this 'solution'. According to tbeu's answer it violates the language standard. OpenModelica allows it, but it shouldn't.

I have finally found a partial solution. If I declare ComplexModel by using conditionals in the initial equation and equation sections, I can make it work - somehow.
model ComplexModel
  parameter Boolean fixed = true;
  Real x(fixed = false);
  Real y(fixed = false);
initial equation
  if not fixed then
    y * y = x;
  end if;
equation
  if fixed then
    y * y = x;
  end if;
end ComplexModel;

By replacing in the model RefactoredFlatModel (from the question) the line
parameter ComplexModel mStatic;

by
parameter ComplexModel mStatic (fixed = false);

the resulting flat model finally becomes
class AdvancedMultiBody.FixedTests.RefactoredFlatModel
  parameter Real x = 4.0;
  parameter Real y(fixed = false);
  Real z;
  parameter Boolean mStatic.fixed = false;
  parameter Real mStatic.x(fixed = false);
  parameter Real mStatic.y(fixed = false);
  parameter Boolean mDynamic.fixed = true;
  Real mDynamic.x(fixed = false);
  Real mDynamic.y(fixed = false);
initial equation
  mStatic.y ^ 2.0 = mStatic.x;
  mStatic.x = x;
  y = mStatic.y;
equation
  mDynamic.y ^ 2.0 = mDynamic.x;
  mDynamic.x = 4.0 * x;
  z = mDynamic.y;
end AdvancedMultiBody.FixedTests.RefactoredFlatModel;

i.e. I have successfully juggled the equation for mStatic.y to the initial equation section in a way that can be controlled from the outside. The good thing is that the ComplexModel is now fully encapsulated and can be assigned the 'attribute' fixed = false, as demanded in my question.
The bad thing is that I have to write the underlying equation y*y=x twice inside ComplexModel. In case of more sophisticated equation systems this might be a source of error. And: I think the syntax could be abused If someone writes fixed=false for a non-parameter instance of ComplexModel (causes the time dependent equation to vanish which is quite different from what fixed=false means for atomic data types).
Somehow I wish there was a language feature that does all this automatically and consistently, but there doesn't seem to be.

A: The code you suggested in your question almost works. You only have to leave out the parameter prefix for mStatic and assign its variables in the regular equation section.
model RefactoredFlatModel
  parameter Real x=4;
  parameter Real y(fixed=false);
  Real z;
  ComplexModel mStatic;
  ComplexModel mDynamic;
initial equation
  y = mStatic.y;
equation
  // The assignment is needed to have enough equations, even though its static
  mStatic.x = x;

  mDynamic.x = 4*x;
  z = mDynamic.y;
end RefactoredFlatModel;

Parameters can be assigned in initial equations sections from regular variables as well. So you do not need the parameter prefix for the model mStatic.
However, the equations of mStatic must also be defined in the continuous time section, hence we have to move the equation mStatic.x = x to the equation section.


text:
Q: Integrate Twitter bootstrap with osCommerce I'm developing an online store using osCommerce (requirement) and need to integrate it with Twitter Bootstrap, specifically the bootstap.css/bootstap.responsive.css and the jQuery plugins.
I have already tried a bit, and everything just goes very wrong, styles all over the place, etc. osCommerce uses jQuery UI, so how could I possibly use Twitter bootstrap CSS + jQuery?
Or is there another way, so all the elements, buttons are themed like bootstrap?

A: There is a current effort at the moment that provides a Bootstrap implementation here:
https://github.com/gburton/osCommerce-2334-bootstrap
A demo site is live at:
http://template.me.uk/2334bs3/
The forum topic discussing the development here:
http://forums.oscommerce.com/topic/396152-bootstrap-3-in-2334-responsive-from-the-get-go/
There are plans to integrate this effort into the official release in the 2.3.3.x roadmap.

A: You can still use jQuery UI if you want or need.
This is a full jQuery UI theme looking like Twitter Bootstrap by Addy Osmani
 https://github.com/addyosmani/jquery-ui-bootstrap/
Demo: http://addyosmani.github.com/jquery-ui-bootstrap/


text:
Q: Add exceptions on firebase cloud functions triggers In a social app, I have a cloud function that updates a 'likes' counter whenever a post is liked, which is to say whenever the following reference is updated:
/likes/{postId}/{userid}
'countOfLikes' is written at the same level of the wildcard {userId} :
exports.countLikeChange = functions.database.ref('/likes/{postId}/{userid}').onWrite(event => {
    const collectionRef = event.data.ref.parent;
    var counterRef = collectionRef.child('countOfLikes');

    return collectionRef.once('value').then(messagesData => counterRef.set(messagesData.numChildren() - 1));
});

With my current code, when a user like a post, the function is triggered first to update countOfLike, which in turn trigger the same function to do the same action...
Is there a way to specify an exclusion so that the function will not be triggered if {userId} == 'countOfLikes' ?
I know that I could use onCreate instead of onWrite, but you must know that in my app, one user could also remove his 'like'.

A: There is no way to exclude a specific child from triggering a function.
If you find that need, it typically means you've combined types of data that should be kept separate.
For example, I would expect your like counts to be in a separate node altogether, e.g. /likeCounts/$postId. If you structure it like that, updating the count for a new like won't retrigger the function.


text:
Q: What is the fastest way to make this table? Context:
As a possible approach to Goldbach's Conjecture, we create two lists of least/greatest prime factors of the odd numbers. The lists are A090368 lpf and A076565 gpf. We get  symmetric triangles, which contain all even numbers as sums of two odd primes.
m = 13;
lpf[n_] := FactorInteger[2 n + 1][[1, 1]];
gpf[n_] := FactorInteger[2 n + 1][[-1, 1]];
A090368 = Array[lpf, m];
A076565 = Array[gpf, m];
Table[A090368[[1 ;; -n]] + Reverse[A090368[[1 ;; -n]]],
  {n, Length[A090368], 1, -1}];
Table[A076565[[1 ;; -n]] + Reverse[A076565[[1 ;; -n]]],
  {n, Length[A076565], 1, -1}];
{%% // MatrixForm, % // MatrixForm}

Question:
Is there a faster method to reverse and add the sublists? Perhaps through indexing?
Note: I have verified to $m=200$K by wrapping a Max around the table, taking the differences and then a union to find that all differences are $2.$

A: I don't understand what you try to do, but the tables can be generated faster as follows.
cf = Compile[{{a, _Integer}, {b, _Integer, 1}},
   a + b,
   CompilationTarget -> "WVM",
   RuntimeAttributes -> {Listable},
   Parallelization -> True,
   RuntimeOptions -> "Speed"
   ];

m = 2000;
pf[n_] := FactorInteger[2 n + 1][[{1, -1}, 1]];
{a, b} = Transpose[Array[pf, m]]; // AbsoluteTiming // First
A = cf[a, a]; // AbsoluteTiming // First
B = cf[b, b]; // AbsoluteTiming // First

0.006257
0.008116
0.003796

Compare the antidiagonals of A and B to the rows of A090368 and A076565, respectively.
m1 = 13;
tab = Grid[
  A[[1 ;; m1, 1 ;; m1]],
  Frame -> All,
  Background -> {
    None, None,
    Flatten[
     Outer[{##} -> ColorData[97][Plus[##] - 1] &, Range[m1],
      Range[m1]]]
    }]


text:
Q: Предупреждение AndroidStudio при указании xml-drawable значением фона в разметке android:drawable="@drawable/button" При создании android:drawable="@drawable/button появляется восклицательный знак в  красном кругу.

При нажатии на этот знак , переходит на buttton.xml
Что делаю не так?

A: Ошибок нет. Это означает, что студия не смогла показать превью изображения. Если выбрать изображение то там будет показано превью.
Ответ взят с англоязычной версии сайта


text:
Q: Gorm: pq duplicate key violates unique constraint I'm trying to learn go & Gorm currently so I apologize if i'm missing something obvious.
I have declared the following GORM Models
type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              string `gorm:"unique"`
    SteamID64            uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}

type DeepLink struct {
    gorm.Model
    ShortURL   string `gorm:"unique"`
    UserID     uint
    User       User
    LinkAction Action
    Payload    interface{} `gorm:"-"`
}

I want to be able to identify the User that created the deeplink - this may not be the best way to do this.
When on a new database, when creating a second user using
func (m *Models) CreateUserFromDiscord(discordID, discordNickname, discordProfilePicURL string) *User {
    u := &User{
        DiscordID:            discordID,
        DiscordNickname:      discordNickname,
        DiscordProfilePicURL: discordProfilePicURL,
    }

    m.db.Create(u)
    return u
}

I get an error saying pq: duplicate key value violates unique constraint "users_steam_id_key"
Creating the first user using this method and creating deeplinks for this User works fine, but creating a second user throws the error. Neither user has a SteamID set.
Im wondering if theres any way to fix this or better structure my models to solve this problem.
The database is created using Gorms AutoMigrate function. This happens on a new db
Thanks

A: In golang if you don't set value for String variable it means it's value is ""(empty string). Ref
Since you don't set SteamID then ""(empty string) set as value for first user.
Then when your trying to save second user SteamID column as ""(empty) then unique constraint violates because ""(empty string) is a not null value for database and gives you error.
Solution: Use *(pointer) for those fields in struct. If variable of *string/*int64 is not set then it's value nil. Also make optional columns nullable in DB.
type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              *string `gorm:"unique"`
    SteamID64            *uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}


text:
Q: Xcode doesn't recognize iPhone "Launch Images" I am using XCode 4.5. I noticed XCode fails to detect the "Launch Images" ONLY for iPhone and iPhone (3.5-inch), but for Retina (4 inch) and iPad they are okay.
My files list:
Default-568h@2x.png (OK)
Default-Portrait@2x~ipad.png (OK)
Default-Portrait~ipad.png (OK)
Default.png (Not shown in summary page)
Default@2x.png (Not shown in summary page)

Any reason or should I need a better name for these files?

A: You can try for iPhone:

*

*Default-iphone.png

*Default@2x-iphone.png


text:
Q: How do I update the projection of a choropleth map in plotly? I have a choropleth map with a projection type of albers usa. I want to dynamically zoom the map based on a state selection to just be focused around a single state on the map. I tried to use the lataxis and lonaxis properties, but I must be doing something wrong, as I can't get them to work at all. Here is what I tried:
self.states_plot.layout = dict(
  title = None,
  dragmode=False,
  paper_bgcolor='rgba(0, 0, 0, 0)',
  plot_bgcolor='rgba(0, 0, 0, 0)',
  geo=dict(
    showframe=False,
    showcoastlines=False,
    projection_type='equirectangular',
    scope='usa',
    projection= dict(
      type='albers usa',
      lonaxis=dict(
        range=[-125.756267, -116.439860]
      ),
      lataxis=dict(
        range=[49.357767, 45.495262]
      )
    ),
    bgcolor='rgba(0,0,0,0)',
    lonaxis=dict(
      range=[-125.756267, -116.439860]
    ),
    lataxis=dict(
      range=[49.357767, 45.495262]
    )
  ),
  margin= dict(
    l= 0,
    r= 0,
    b= 0,
    t= 0,
    pad= 0
  )
)

A: I figured this out. The problem was that I wasn't setting the geo.center.lat and geo.center.lon


text:
Q: Decimal field rounding in WTForms I have a form that contains a price decimal field, like so:
from flask.ext.wtf import Form
import wtforms
from wtforms.validators import DataRequired
from decimal import ROUND_HALF_UP

class AddListingBase(Form):
    title = wtforms.StringField(validators=[DataRequired()])
    details = wtforms.TextAreaField(validators=[DataRequired()])
    price = wtforms.DecimalField(places=2, rounding=ROUND_HALF_UP, validators=[DataRequired()])

When I submit the form, the decimal value is suppoosed to be rounded to 2 decimal places, but that never happens. I always get the value as it was specified (e.g. 99.853 is 99.853, not 99.85 as it should be).

A: As @mueslo has rightly inferred, this is because the default DecimalField implementation does not round off the form data it receives. It only rounds off the initial data (as in defaults, or model/saved data).
We can easily change this behavior with a modified DecimalField implementation, wherein we override the process_formdata method. Somewhat like so:
from wtforms import DecimalField

class BetterDecimalField(DecimalField):
    """
    Very similar to WTForms DecimalField, except with the option of rounding
    the data always.
    """
    def __init__(self, label=None, validators=None, places=2, rounding=None,
                 round_always=False, **kwargs):
        super(BetterDecimalField, self).__init__(
            label=label, validators=validators, places=places, rounding=
            rounding, **kwargs)
        self.round_always = round_always

    def process_formdata(self, valuelist):
        if valuelist:
            try:
                self.data = decimal.Decimal(valuelist[0])
                if self.round_always and hasattr(self.data, 'quantize'):
                    exp = decimal.Decimal('.1') ** self.places
                    if self.rounding is None:
                        quantized = self.data.quantize(exp)
                    else:
                        quantized = self.data.quantize(
                            exp, rounding=self.rounding)
                    self.data = quantized
            except (decimal.InvalidOperation, ValueError):
                self.data = None
                raise ValueError(self.gettext('Not a valid decimal value'))

Example usage:
rounding_field = BetterDecimalField(round_always=True)

Gist


text:
Q: Javascript promise recursion and chaining How should I write my recursive loop to correctly execute promises in order? I've tried with Promise.all(Array.map(function(){})); which does not suit my needs as those steps need to be ran in a sequence. I've tried with a custom promise for I've found here, but it also has problems.
The promise for:
var promiseFor = (function(condition, action, value) {
    var promise = new Promise(function(resolve, reject) {
        if(!condition(value)) {
            return;
        }
        return action(value).then(promiseFor.bind(null, condition, action));
    });
    return promise;
});

The problem with this for is that it seems to stop at the deepest recursive call, not returning to continue executing the loop to finish correctly.
For example: in PHP a code like this:
function loopThrough($source) {
    foreach($source as $value) {
        if($value == "single") {
            //do action
        } else if($value == "array") {
            loopThrough($value);
        }
    }
}

If i pass lets say a folder structure and "single" means file, it will print all files. But the promise for I'm using stops at the first dead end.
EDIT: Added bluebird to see if it could help with anything, still the same thing.
Here's the current loop code
var runSequence = (function(sequence, params) {
    return Promise.each(sequence, function(action) {
        console.log(action['Rusiavimas'] + ' - ' + action['Veiksmas']);
        if(params.ButtonIndex && params.ButtonIndex != action['ButtonIndex']) {
            return Promise.resolve();
        }

        if(action['Veiksmas'].charAt(0) == '@') {
            var act = action['Veiksmas'];
            var actName = act.substr(0, act.indexOf(':')).trim();
            var actArg = act.substr(act.indexOf(':')+1).trim();

            /* This one is the code that figures out what to do and
               also calls this function to execute a sub-sequence. */
            return executeAction(actName, actArg, params);
        } else {
            sendRequest('runQuery', action['Veiksmas']);
        }
    });
});

I have 3 sequences, each consisting of 5 actions. First and second sequence has the next sequence as it's third action. Here's the result I get (numbers mean which sequence):
1 - @PirmasVeiksmas
1 - @AntrasVeiksmas
1 - @Veiksmas: list_two
2 - @PirmasVeiksmas
2 - @AntrasVeiksmas
2 - @Veiksmas: list_three
3 - @PirmasVeiksmas
3 - @AntrasVeiksmas
3 - @TreciasVeiksmas
3 - @KetvirtasVeiksmas
3 - @PenktasVeiksmas

As you can see it enters the next sequence and continues like it should, but once the third one is complete, it should resume the second sequence and finish up with the first one. But it stops as soon as it hits the first dead end in recursion.
EDIT2: Codepen example of what I have now and with visual representation of what's happening: Codepen link
Output should be:
fa1
second
sa1
third
ta1
ta2
ta3
sa3
fa3

A: Running a bunch of actions in a sequence can be done with .reduce() instead of .map().
Here's an example:

// Helper function that creates a Promise that resolves after a second
const delay = (value) => new Promise(resolve => setTimeout(() => resolve(value), 1000));

const arr = [1, 2, 3, 4, 5];

// concurrent resolution with `.map()` and `Promise.all()`
Promise.all(arr.map(delay))
  .then(console.log.bind(console)); // [1, 2, 3, 4, 5] after a second.

// sequential resolution with `.reduce()`

arr.reduce((promise, current) =>
             promise
               .then(() => delay(current))
               .then(console.log.bind(console)),
           Promise.resolve());
// second wait, 1, second wait, 2...

If I understood your requirements correctly, you don't exactly need Promise recursion, it's just the way you found to run Promises sequentially. .reduce() can help you with that more simply.
The reduction process turns [1,2,3,4,5] into:
Promise.resolve()
  .then(() => delay(1))
  .then(console.log.bind(console))
  .then(() => delay(2))
  .then(console.log.bind(console))
  .then(() => delay(3))
  .then(console.log.bind(console))
  .then(() => delay(4))
  .then(console.log.bind(console))
  .then(() => delay(5))
  .then(console.log.bind(console))

Take note that if you want to access all of the results, you need to do a bit more work. But I'll leave that as an exercise for the reader :)

A: So this fixes the problems with your codepen code so it gives the output you want.
var sequences = {
  first: ['fa1', 'second', 'fa3'],
  second: ['sa1', 'third', 'sa3'],
  third: ['ta1', 'ta2', 'ta3']
};

var loopThrough = (function(sequence) {
  return sequence.forEach(function(action) {
    return doAction(action);
  });
});

var doAction = (function(action) {
  var promise = new Promise(function(resolve, reject) {
    console.log(action);
    if(action == 'second' || action == 'third') {
      //recurse into sub-sequence
      return loopThrough(sequences[action]);
    } else {
      //do something here
    }
    resolve();
  });
  return promise;
});

loopThrough(sequences.first);


text:
Q: get Idictionnary from Ilist How to get a IDictionnay form a IList

A: You can use Linq to easily get a Dictionary from a List by using the ToDictionary extension method and supplying an expression to get the key - e.g.
internal class Program
{
    private static void Main(string[] args)
    {
        IList<Person> list = new List<Person> {new Person("Bob", 40), new Person("Jill", 35)};
        IDictionary<string, Person> dictionary = list.ToDictionary(x => x.Name);
    }
}

public class Person
{
    private readonly int _age;
    private readonly string _name;

    public Person(string name, int age)
    {
        _name = name;
        _age = age;
    }

    public int Age
    {
        get { return _age; }
    }

    public string Name
    {
        get { return _name; }
    }
}

Alternatively, as Jon pointed out, if you need to use a different value for the Dictionary entries, you can also specify a second expression to get the value - as follows:
IDictionary<string, int> dictionary2 = list.ToDictionary(x => x.Name, x => x.Age);

A: A List has one component to it, and a Dictionary has two components. You can't simply convert them.
If you want your Dictionary to be <int, object>, where int is the index of the information in your List...
Dictionary<int, object> dict = new Dictionary<int, object>();
myList.ForEach(i => dict.Add(myList.IndexOf(i), i)); // Linq magic!

Replace object with your List type, and make sure you are using System.Linq;.

Or use ToDictionary().


text:
Q: Python package installation from tarball results in 0.0.0 version I'm installing Python packages from the tar.gz source distributions from PyPi but sometimes those packages get installed with a version of "0.0.0".
Can anyone help me understand why that is the case and how to resolve this?
As a recent example I took datacube from https://pypi.org/project/datacube/#files (yes I could use the whl file here, but generically I'd prefer the tar.gz)

*

*Download datacube-1.8.3.tar.gz

*Extract and cd to datacube folder

*pip install -v .
When using a Python 3.8.6 it seemingly installs fine and the version is 1.8.3 as expected ("Successfully installed datacube-1.8.3")
When using Python 3.8.2 with a slightly different set of installed modules the resulting version is instead 0.0.0 ("Successfully installed datacube-0.0.0")
In both cases I'm using a virtualenv (20.0.34 / 20.0.18)
So where does the version exactly come from, how can I check and resolve that?
I already tried pip install --upgrade setuptools setuptools-scm toml poetry which were IMO the packages responsible for installing packages, but to no avail.
After an "accident" when experimenting I've also noticed, that the problem seemingly vanishes once I run the pip install command outside of the virtualenv which is even more mysterious as I created it with virtualenv --system-site-packages and pip freeze shows no difference


text:
Q: How is using portlets any better than just using server side includes? The idea behind portlets is that a website/page can be comprised of a number of applications that are developed individually. They are then fit together on a page by a portal much like a jig-saw puzzle. This allows functionality to be created independently and slotted together at a later date. This has many obvious benefits.
However. I cannot see how the portlet specification improves upon older ideas like server-side includes, from the point of view of a developer who needs to get something done, as opposed to publish a paper or make a keynote address.
The tone might be a bit negative, but my first foray into the world of portlets has left me thoroughly disenchanted.

A: From the point of view of the job of just 'including' some dynamic/static content on a web page, you're correct.
However there are a number of conveniences implemented, such as support for personalisation of the portlet (at the portlet/'include' level) and storing this info, a more rigid workflow for configuring what is displayed in the portlet and so on.
Plus obviously there's all the portlet arrangement code that you would have to write otherwise. Some portlet servers do a lot on the client side for arrangement (drag and drop of portlets etc).
You may find some of the discussion at the below URL helpful:
http://www.ibm.com/developerworks/ibm/library/i-portletintro/

A: For sure, the portals create the view essentially by doing lots of server side includes.
The portlet specs (JSR-168, 286) just define how to code a portlet so it fits into a portal. They only define things necesary for portlets to co-exist on the same portal page, things that are not a part of J2EE servlet or JSP definitions.
Without the specs, it would be hardly possible to use portlets from different development teams, or even different vendors on a single portal page.
Even a single J2EE application with a portal-styled UI can benefit from use of a portlet container - it can help to accomplish many typical UI-related tasks.
Consider e.g. these features defined by portal specs (just a very few):

*

*Portlet lifecycle, isolated from other portlets.

*Isolated URL spaces for each portlet

*Portlet modes and window states

*Portlet session scropes

*Personalization, portlet preferences. Users configure apperance of their's portal pages by positioning and setting individual portlets.

*Raising / comsuming of events (JSR-286)

*...

The specs are not a rocket science, and also they do not pose a paradigm in UI design or so - to me, the most revolutionary about portals was the idea of a user's desktop brought into web applications.


text:
Q: Printing PDF files using VBS I am new to coding with VBS. This is my unfinished code to print documents in a folder containing documents with 3 distinct headers, "DN" "INV" and "PO". I've been searching around for the code/method to print out PDF documents. I tried using the invokeverb "&print" function but it doesn't seem to work. Can someone please teach me how to print it out? Thank you very much :)
"DN" needs to printed out once, " INV" needs to be printed out 6 times, "PO" needs to be printed out 2 times.
P.S. Thank you @kajkrow for solving this same problem using VBA. Reposting as I found out I was using VBS. Previous question can be found here. *EDIT : attached link solves my problem in both VBA and VBS and uses InvokeVerbEx to print files.
'' To set the path to the current folder

set shApp = CreateObject("shell.application")

currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

set shFolder = shApp.NameSpace( currentPath )

'' To set the items in the current folder as "files"

set files = shFolder.Items()

''Start of code''

'msgbox("Starting Script")

for each files in files

        ' If name contains "DN" '
        if inStr(files, "DN") then
            'print out 1 time'
        end if
        ' if name contains "INV" '
        if inStr(files, "INV") then
            'print out 6 times'
        end if
        ' if name contains "PO" '
        if inStr(files, "PO") then
            'print out 2 times'
        end if
next
MsgBox("completed")

A: According to documentation (https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf) you could send a command to print a file, but there is no parameter for the number of copies.

You can display and print a PDF file with Acrobat and Adobe Reader
  from the command line. These commands are unsupported, but have worked
  for some developers. There is no documentation for these commands
  other than what is listed below.
Note: All examples below use Adobe
  Reader, but apply to Acrobat as well. If you are using Acrobat,
  substitute Acrobat.exe in place of AcroRd32.exe on the command line.
  AcroRd32.exe pathname — Start Adobe Reader and display the file. The
  full path must be provided. This command can accept the following
  options.

/n Start a separate instance of Acrobat or Adobe Reader, even if one is currently open.
/s Suppress the splash screen.
/o Suppress the open file dialog box.
/h Start Acrobat or Adobe Reader in a minimized window.

AcroRd32.exe /p pathname — Start Adobe Reader and display the Print dialog box.
AcroRd32.exe /t path "printername" "drivername" "portname" — Start Adobe Reader
and print a file while suppressing the Print dialog box. The path must be fully specified.
The four parameters of the /t option evaluate to path, printername, drivername, and portname (all
strings).
printername — The name of your printer.
drivername — Your printer driver's name, as it appears in your printer's properties.
portname — The printer's port. portname cannot contain any "/" characters; if it does, output is
routed to the default port for that printer

For multiple copies of each pdf, you could use a loop.
Something like this:
    set shApp = CreateObject("shell.application")

currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

set shFolder = shApp.NameSpace( currentPath )

set files = shFolder.Items()

set oWsh = CreateObject ("Wscript.Shell")
dn = 1
inv = 6
po = 2

for each files in files
    msgbox(files)

    if inStr(files, "DN") then
        for x = 1 to dn
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true

        next
    end if

    if inStr(files, "INV") then
        for x = 1 to inv
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true
        next
    end if

    if inStr(files, "PO") then
        for x = 1 to po
          oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true
        next
    end if

next
MsgBox("completed")

Note: tested only with XPS Document writer


text:
Q: How to use IHttpClientFactory in class library I am trying to convert some code from net core api to class library.
I am stuck how to use HttpClientfactory.
Normally the httpclientfactory can be configured in program.cs or Startup like
services.AddHttpClient("abc", xxx config).

How to do configurations in class library for Httpclientfactory.

A: In your library add an extension method for IServiceCollection to "enable" it in the main project.
In the library:
public static class ServiceCollectionExt
{
    public static void AddYourStaff(this IServiceCollection services)
    {
        services.AddHttpClient("xxx", client =>
        {
            //your staff here
        });
        services.AddSingleton<ISomethingElse, SomethingElse>();
    }
}

Then in your Startup just call it:
services.AddYourStaff();

UPDATE: As the author described, he's working on the plugin based application. In that case you need some kind of convention, for instance:

*

*each plugin library must have a static class called Registration with the method Invoke(IServiceCollection sc, IConfiguration config)

*Then in your Startup you can iterate through all plugin libraries and call their Registration.Invoke(sc, config) using reflection:

foreach(var pluginAssembly in plugins)
{
    pluginAssembly
        .GetType("Registration")
        .GetMethod("Invoke")
        .Invoke(null, new object[] {services, Configuration});
}

A: You could try as below:
public class HttpClientUtil
    {
        private static IServiceProvider serviceProvider { get; set; }

        public static void Initial(IServiceProvider Provider)
        {
            if (Provider == null)
            {
                IHostBuilder builder = Host.CreateDefaultBuilder();
                builder.ConfigureServices(services =>
                {
                    services.AddHttpClient("client_1", config =>
                    {
                        config.BaseAddress = new Uri("http://client_1.com");
                        config.DefaultRequestHeaders.Add("header_1", "header_1");
                    });
                    services.AddHttpClient("client_2", config =>
                    {
                        config.BaseAddress = new Uri("http://client_2.com");
                        config.DefaultRequestHeaders.Add("header_2", "header_2");
                    });
                });
                serviceProvider = builder.Build().Services;
            }
            else
            {
                serviceProvider = Provider;
            }
        }

        public static IHttpClientFactory GetHttpClientFactory()
        {
            if(serviceProvider==null)
            {
                Initial(serviceProvider);
            }
            return (IHttpClientFactory)serviceProvider.GetServices<IHttpClientFactory>();
        }

    }

you could get the instance of httpclinetfactory through the interface


text:
Q: Why does Stack Exchange ask for a reload on successful automatic login? I'm looking for an answer considering both technical limitations and user experience.
Does it need a reload from a technical standpoint?

A: According to balpha's answer  at Why does it says "welcome back -user- click here to 'refresh page'" it is not a technical issue, rather it's because you may already be reading a post. If that was the case, an automatic refresh would be annoying.

A:
Does it need a reload from a technical standpoint?

Kevin explains why it's this way now.
If they wanted to make it so that a reload was not required, they would have to change a lot of data that's currently static based on the cookie to dynamic (AJAX/javascript/jquery/whatever) loading.
So it's possible to change the system so that a reload is not necessary.
However, it causes a substantial penalty in page loading time.  Right now a lot of page data is static, but if everything were dynamically loaded you'd have to wait some time for the javascript to load and run, communicate with the authentication servers, and then communicate with the original server again prior to letting the browser render the page.
You could do a hybrid, where it loads the static content, then replaces it once it's received new info, but that may result in the same symptom - the page appears to reload while you're reading/scrolling/etc.
So yes, it's possible, but it's not practical from a performance standpoint.

A: Sort of, yes.
Global login uses HTML5 localStorage (under the stackauth.com domain) to work around cookies not being available*.  As a consequence, this means that we can't recognize a user at page render time; we have to wait for a non-trivial amount of javascript to load and execute.
Once global login has finished, we've got the user information... but the user could already be interacting with the page; a hard refresh would be really unpleasant.  We actually tried this in the very early days of the global log system; if you've got a really speedy connection** it's ok, but any sort of latency results in a UX that makes you want to punch your screen.
The one exception to this rule, where we do in fact automatically navigate away, is when a user is on the login page.  Presumably all the user wants to do is login there, so global login completing is a strong signal to navigate away from the page.
*We can't attach a cookie on askubuntu.com from stackoverflow.com, nor can we access stackoverflow.com's cookies from askubuntu.com; as an example.  This is the crux of the issue.  We used localStorage instead of third-party cookies (which would impose the same constraints, but be simpler to implement) because Safari has really dodgy support for third-party cookies.
**Remember, a solid 1/2 of our user base is on a different continent than our data center.  We work hard to make our code fast, but we can't do much about the speed of light.


text:
Q: How to mount a filesystem in a read-only environment? I have the problem that my machine turned the root filesystem into readonly mode and remounting it as writeable won't work:
# mount -o remount,rw /dev/sda1 /
mount: block device /dev/sda1 is write-protected, mounting read-only

I want to copy some data away from that system and I attached a USB drive and tried to mount it:
# mount -t ext3 /dev/sdb1 /mnt
mount: /dev/sdb1 already mounted or /mnt busy

/mnt is an empty directory, so mounting there should usually work, but it seems that having this directory on a readonly filesystem doesn't make it possible to mount something there.
I think there is no activity going on for /mnt, since the following command doesn't return any output:
# lsof | grep "/mnt" | grep -v grep

There is no other partition mounted as the readonly root filesystem at the moment. Is it possible to still get the attached disk into the directory hierarchy somehow?

A: The first error message is telling me that you'll need to reboot - there's something wrong with the disk device itself that the kernel can't resolve without a reboot. If you're booted from SAN, look carefully at your boot LUN and make sure there's nothing wonky with it, or the zoning for the SAN, or the export of the LUN.

A: Set the mount point to anything that is not on the same partition as "/". For example, often the "/tmp" directory or some other directory is a separate partition. Then, it's as simple as creating a temporary mount point:
mkdir -p /tmp/mnt

and then
# mount -t ext3 /dev/sdb1 /tmp/mnt

AS long as /tmp is on a separate mountable partition, it completely bypasses any issues you're having with the root partition.

A: You probably have a stale mtab. Try mounting with the -n option.

A: Apart from /dev/sda1, if there is any separate partition available, say /boot, then create a directory under /boot and mount your usb drive there. What I suspect is /mnt is also part of /. If / is ro, then /mnt mount may not work.

A: Please format your memory in another filesystem
mkfs.xfs /dev/sdXX
mkfs.ext4 /dev/sdXX
or any other filesystem


text:
Q: Date internationalization in JavaScript with ICU formats Using the Intl extension in PHP, I can do custom date formats like this:
$fmt = new \IntlDateFormatter('fr-CA', null, null, null, \IntlDateFormatter::GREGORIAN, 'EEE d MMM yyyy à HH:mm');
echo $fmt->format(new \DateTime());

What is important is that I can pass in any string composed of characters from the ICU Date Field Symbol Table.
I already use Moment.js in my project but it doesn't seem like they are interested in working on ICU compatibility (even for version 3). As a last resort I can duplicate my formats file to include both ICU and Moment.js symbols for each format but ideally I'd like to avoid that.
I looked into the Intl.DateTimeFormat object of the ECMAScript Internationalization API and it doesn't seem to have such functionality so what options do I have in JavaScript?


text:
Q: 2 cogwheels with magnets on each cog to create infinite movement? I have no experience of physics or what so ever but I was thinking of 2 cogwheels with magnets on each cog to create infinite movement.
I have no idea on how to try this etc, but I would love to hear your thoughts of it.

So basically my idea was that they would never touch eachother so they don't generate heat so there's a little space between them.

A: Your system would lock up very quickly and cease further movement.
Plainly, the amount of energy and wheel motion gained by the attraction of the magnets must equal the amount of energy and wheel motion lost to repulsion. Furthermore, since the wheels turn they rob the system of even more energy, leaving you with a net loss of energy. Perpetual motion requires a net gain to be useful, and an equilibrium to happen at all.
There's a reason no one has invented perpetual motion yet. Mother Nature always balances her books.


text:
Q: TypeError: argument of type 'NoneType' is not iterable for list passed in as parameter to a function Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
I keep getting the error, and I don't understand why.
TypeError: argument of type 'NoneType' is not iterable
    if (nums[i] not in current):

This is my code:
def permute(self, nums: List[int]) -> List[List[int]]:
        output = []
        self.backtracking(nums, output, [],0, len(nums))
        return output

    def backtracking(self, nums, outputList, current, length, maxLength):
        if (length == maxLength):
            outputList.append(current)

        for i in nums:
            if (nums[i] not in current):
                self.backtracking(nums, outputList, current.append(nums[i]), length+1, maxLength)


text:
Q: 2 Quartz jobs updating same value in db concurrently causing inconsistent behaviour I had one quartz job doing some stuff and taking lot of time for one particular case and others are very quick. So I don't want to stop my job waiting when one slow case is running for very long time and other things are complete.  This job runs and checks doStuff flag. when doStuff==1 run do things and make value to 0. So that when next time job is triggered it should not run already done stuff.
So to solve above problem I created 2 jobs. A- quick performing job, B-slow moving job.
I have 2 quartz jobs A & B running concurrently and using one flag to decide whether to run job & do stuff or to run and exit without doing any stuff.
I have a flag doStuff and it has initial value as 0 . when it's value is 1 then both job should start doing stuff and when they finish they should update value back to 0. When value is 0 and job started then this job won't do it'a stuff.
The work both job A & B doing is exactly same but different parameters.
Ideally both job should run when flag is 1 and do stuff and update value to 0.
But when first job runs and completes before starting second job, it is updating value to 0 and  when second runs it reads value 0 and won't do any stuff.
The doStuff flag is DB column. I can add one more column for job B, but that's not a good design as we may get requirement of job C, job D and I can't add column for each requirement.
Is there any better way to handle this problem?
Note: I am new to Quartz framework.
Tried using new column for flag but not a good design. Tried locking but that also won't solve problem .
Below is how execute method of InterruptableJob looks like
public void execute(JobExecutionContext jobContext) throws JobExecutionException {
    JobDataMap jobDataMap = jobContext.getMergedJobDataMap();
    final long customerId = jobDataMap.getLong(CUSTOMER_ID_KEY);

    List < QAgentAssetSourceInfo > customerAgents = getValuesBasedOnDoStuff();

    // below code is in Runnable run method and will be started in new thread
    {
        failedAgents.putAll(agentMgmtHelper.get().doStuff(customerAgents, customer.getId(), null, batchSize));

        // we are done with stuff now make value to 0
        unsetDoStuff();
    });

}


text:
Q: Integration of $\int_0^{2\pi}(e^{\cos x}\cos x\sin x) \,dx$ Can anyone please help me with this integration:
$$\int_0^{2\pi}(e^{\cos x}\cos x\sin x)\,dx$$
I am getting the answer as $0$ by using simply the properties of definite integral
BUT the answer as told by my teacher is $2\pi$
Please help. Thanks!

A: Using $$\int_a^bf(x)dx=\int_a^bf(a+b-x)dx$$
If $\displaystyle  f(x)=e^{\cos x}\sin x\cos x,$
$\displaystyle f(2\pi+0-x)=e^{\cos(2\pi+0-x)}\sin(2\pi+0-x)\cos(2\pi+0-x)=e^{\cos x}\cos x(-\sin x)=-f(x)$

Also putting $\cos x=u,$
$$\int_0^{2\pi}e^{\cos x}\sin x\cos x=-\int_1^1e^u\cdot u\ du$$
The indefinite part can be managed using integration by part.
But as both the upper & the lower bounds are same, the result has to be zero

A: Here's another way of looking at it:
$$\begin{align}
\int_{0}^{2\pi}e^{\cos{x}}\cos{x}\sin{x}\,\mathrm{d}x
&=\int_{-\pi}^{\pi}e^{\cos{x}}\cos{x}\sin{x}\,\mathrm{d}x\\
&=\int_{-\pi}^{\pi}e^{\cos{x}}\frac{\sin{(2x)}}{2}\,\mathrm{d}x
\end{align}$$

A: If you make the simple substitution $u = \mathrm{e}^{\cos x}$ then you'll find that $\mathrm{d}u = -\mathrm{e}^{\cos x}\sin x~\mathrm{d}x$. Moreover, $\cos x = \ln u$. When $x=0$, $u=\mathrm{e}^{\cos 0} = \mathrm{e}$ and when $x=2\pi$, $u=\mathrm{e}^{\cos 2\pi} = \mathrm{e}$. Hence
$$\int_0^{2\pi} \mathrm{e}^{\cos x}\sin x~\cos x ~ \mathrm{d}x = \int_0^0 - \ln u~\mathrm{d}u=0$$
You don't need to evaluate the integral because the upper and lower limits are the same, so the integral will evaluate to zero. If you wanted to evaluate the integral you'd see that
$$\int \mathrm{e}^{\cos x}\sin x~\cos x~\mathrm{dx} = \int - \ln u~\mathrm{d}u = u(1-\ln u) + C = \mathrm{e}^{\cos x}(1-\cos x)+C$$


text:
Q: ID3 Algorithm in Python I am trying to plot a decision tree using ID3 in Python. I am really new to Python and couldn't understand the implementation of the following code. I need to know how I can apply this code to my data.
from math import log
import operator

def entropy(data):
    entries = len(data)
    labels = {}
    for feat in data:
        label = feat[-1]
        if label not in labels.keys():
            labels[label] = 0
            labels[label] += 1
            entropy = 0.0
    for key in labels:
        probability = float(labels[key])/entries
        entropy -= probability * log(probability,2)
    return entropy

def split(data, axis, val):
    newData = []
    for feat in data:
        if feat[axis] == val:
            reducedFeat = feat[:axis]
            reducedFeat.extend(feat[axis+1:])
            newData.append(reducedFeat)
    return newData

def choose(data):
    features = len(data[0]) - 1
    baseEntropy = entropy(data)
    bestInfoGain = 0.0;
    bestFeat = -1
    for i in range(features):
        featList = [ex[i] for ex in data]
        uniqueVals = set(featList)
        newEntropy = 0.0
        for value in uniqueVals:
            newData = split(data, i, value)
            probability = len(newData)/float(len(data))
            newEntropy += probability * entropy(newData)
        infoGain = baseEntropy - newEntropy
        if (infoGain > bestInfoGain):
            bestInfoGain = infoGain
            bestFeat = i
    return bestFeat

def majority(classList):
    classCount={}
    for vote in classList:
        if vote not in classCount.keys(): classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.iteritems(),     key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def tree(data,labels):
    classList = [ex[-1] for ex in data]
    if classList.count(classList[0]) == len(classList):
        return classList[0]
    if len(data[0]) == 1:
        return majority(classList)
    bestFeat = choose(data)
    bestFeatLabel = labels[bestFeat]
    theTree = {bestFeatLabel:{}}
    del(labels[bestFeat])
    featValues = [ex[bestFeat] for ex in data]
    uniqueVals = set(featValues)
    for value in uniqueVals:
        subLabels = labels[:]
        theTree[bestFeatLabel][value] = tree(split/(data, bestFeat, value),subLabels)
    return theTree

So what I did after this is the following:
infile=open("SData.csv","r")
data=infile.read()

tree(data)

The error which I got is "1 argument is missing" which is the label which I have to define and this is where I don't know what I have to put. I tried the variable for which I have to make the decision tree but it doesn't work:
tree(data,MinTemp)

Here I get an error "MinTemp is not defined".
Please help me out and let me know what I should do to have a look at the tree.
Following is the part of data and I want to generate a tree for MinTemp
MinTemp,Rainfall,Tempat9,RHat9,CAat9,WSat9
high,no,mild,normal,overcast,weak
high,no,mild,normal,cloudy,weak
high,no,mild,normal,cloudy,mild
high,yes,mild,high,cloudy,weak
high,yes,mild,high,cloudy,mild
medium,yes,mild,high,cloudy,mild
high,no,mild,high,overcast,weak
high,no,mild,normal,sunny,weak
high,no,hot,normal,sunny,weak
high,no,hot,normal,overcast,weak


text:
Q: Dynamic target for root or nested directory My makefile contains a target for node_modules directory, which depends on package.json file:
node_modules: package.json
    npm install && touch "$@"

My current project happens to have a "sub-package" with its own set of dependencies. I modify the target above to the following:
%/node_modules: %/package.json
    cd $(shell dirname "$<") && npm install && touch node_modules

Now, I can do make path/to/subpackage/node_modules and make runs the expected npm install command. However, I no longer seem to be able to do make node_modules - make exits with status code 0 and message Nothing to be done for 'node_modules'.
This indicates make will now only run the appropriate command for node_modules folders which exist within a subdirectory.
How can I change the target so that it supports both nested and root node_modules directories within the same target?
In other words, I would like to remove the duplicated target definition because the command to make the root's node_modules directory is the same as the command to make the nested path/to/node_modules directory.

As research, I tried to look at the GNU Make tutorial but could not find any relevant information - possibly because I simply do not know what to look for.

A: It isn't very elegant, but you could use a "canned recipe":
define MAKE_NODE_MODULES
npm install && touch node_modules
endef

node_modules: package.json
    $(MAKE_NODE_MODULES)

%/node_modules: %/package.json
    cd $* && $(MAKE_NODE_MODULES)


text:
Q: GA-Z170N-Gaming 5 what are normal CPU teperatures My CPU fan recently came loose and all the thermal paste is dry(the fan isnt really snapped or glued on anymore) So naturally, my CPU is heating up fairly quickly. While I do plan on replacing the CPU fan, in the mean time I decided to monitor it using a little program called Core Temp
What I want to know is what would average CPU temperatures be under full load? I mean, yes of course this is going to vary on many things, like how many apps are running and the drain on the CPU. It should be known I like to run this thing heavy (games, 3ds max, Google Chrome with lots of open tabs, Photoshop all at once). Before the CPU fan gave out this was fine and my machine was ok. I am running an Intel i5-6500 quad core on a GA-Z170N-Gaming 5 motherboard, with 24 gigs of ram an Nvidia GTX-970 for GPU.
After the CPU fan issue just running a video game and having 3ds Max open will put me upwards of 90 degrees with the maximum temperature value being at 98 or so before going critical or shutdown. Id like to know what the target or normal ranges would be once I get the CPU fan back to normal

A: Well I did some digging around and found this site which explains average temperatures for CPUs according to make and model.
"The majority of today's desktop processors should not exceed temperatures of 45-50°C when idle, or 80°C when under full load. Below is a chart listing many types of processors and their average temperatures under full load."
This is a very handy resource for anyone wanting to know average temperatures under a full load, or even just idle.
In my case, the Intel i5 says that 50°C - 62°C is the average temp under full load.
I hope this resource is helpful to anyone out there.
Thanks!


text:
Q: SFTP User with access to specific folder only - permission denied to create files So I am trying to create a user that only has access to a specific folder inside my public_html folder. I have successfully created the user and I am able to login. I had some troubles logging in, in the start, because the folder had to be owned by root, before the sftp user could sftp.
So I followed this guide: https://serverfault.com/questions/584986/bad-ownership-or-modes-for-chroot-directory-component - instructing me to change ownership of the folder to root.
After doing this, I can successfully login, however, once I login, I am unable to add files or do anything within this folder, since it is owned by root.
I tried creating a group, and adding the root user and the sftp user as members of this group, but that didn't work either.
My work around was to create another directory inside the sftp folder, using root user, and then afterwards changing ownership to the sftp user, but this seems too hacky to me and addtionally adds another folder to the tree structure which I am not a huge fan of.
Any ideas how to allow a sftp user write access to a folder, while root remains the owner?

A: There's a lot of chatter about this kind of thing across a few stack exchange sites.  But in case this is not a duplicate ...
In my CentOS 7 when you use ChrootDirectory to restrict a user to a directory, that directory has to be owned by root and it cannot allow write access to any other user either by permissions or FACLs.  You can set up a symbolic link but the sftp user will not be able to follow it if s/he's restricted to a directory.  So you have to do this.
Create a user
useradd ftp_user

set up password
passwd ftp_user

Set up permissions.  His home dir is going to be his jail.
chown root:root /home/ftp_user
chmod 0755 /home/ftp_user

Restrict the user to that jail now
vi /etc/ssh/sshd_config

Change this:
#Subsystem sftp /usr/lib/openssh/sftp-server

to
Subsystem sftp internal-sftp

Add
Match User ftp_user
    ChrootDirectory %h
    ForceCommand internal-sftp
    AllowTCPForwarding no
    X11Forwarding no

Save and exit vi.
Don't forget:
systemctl restart sshd

Now we trick them.  Let's say your client has a website that your going to let him keep playing with at /var/www/corny_website
Make sure he has permissions on that directory
setfacl -m u:ftp_user:rwx /var/www/corny_website
setfacl -d -m u:ftp_user:rwx /var/www/corny_website

Now you mount it instead of symlink to it.
mkdir /home/ftp_user/corny_website
mount --bind /var/www/corny_website /home/ftp_user/

Now when the user sftps. He won't get that broken pipe error, and he'll only be able to see /home/ftp_user and what's more, he'll only be able to upload to or download from /var/www/corny_website which he sees as /corny_website.


text:
Q: python selenium send_keys yields wrong character I've been running some tests on a remote ubuntu machine and i found a weird bug:
If i try to send any of these keys %/?^56 to an input, using send_keys, they don't get there.
5 creates a backspace
6 creates a Shift+Tab
^ creates a Tab
% creates a backspace
? creates a Enter

This only happens on Chrome + Selenium + Python 2.7
Selenium is 2.46.0
Chrome is 43.0.2357.81 Ubuntu 14.04 (64-bit)
ChromeDriver is 2.15.322488sud

Any hints where i could start investigating this?
EDIT: some code i've used to debug this
from selenium.webdriver.common.keys import Keys
import time
import string
allchars = string.letters + string.punctuation + string.digits
from selenium.webdriver import Firefox
from selenium.webdriver import Chrome
b1 = Firefox()
b2 = Chrome()
b1.get("http://google.ro")
b2.get("http://google.ro")
i1 = b1.find_element_by_id('lst-ib')
i2 = b2.find_element_by_id('lst-ib')
for l in allchars:
    i1.send_keys(l)
    i2.send_keys(l)
    time.sleep(1)
    if i1.get_attribute('value') != l:
        print "mismatch",b1,l
    if i2.get_attribute('value') != l:
        print "mismatch",b2,l
    i1.send_keys(Keys.BACKSPACE)
    i2.send_keys(Keys.BACKSPACE)

EDIT2: After upgrading the packages to the latest version available for ubuntu-x64, the problem persisted, but only for these characters %/?5. I'm going to post this to the bugtracker.


text:
Q: pig - filter on AND function not working This works: filter A by daily_partition == '20150228'
This doesn't work: filter A by daily_partition == '20150228' AND daily_partition == '20150227';
Any idea why "AND" is not being applied in filter?

A: As the name implies, AND evaluates to true when all the conditions are true. Meanwhile, OR evaluates to true when at least one of the conditions are true.

If daily_partition equals 20150228, it is impossible that it also equals 20150227.

Any idea why "AND" is not being applied in filter?

AND is being applied in your filter, that is why you don't get any values. What you need for your FILTER, as you said, is an OR. You want to get the dates that equal 20150227 OR 20150228.
You might want to read a bit more about Boolean albebra.

A: This is made to work by using "OR" function instead of "AND" .
I think the problem occurred because filter takes in the boolean input.
Any further explanation to this problem will be useful.
Thanks


text:
Q: Android Programming, ListView Images are gone during and after query in the SearchView I'm having trouble trying to re-display the ListView's original values with it's respective Icons after I try to query Search in the SearchView. The ListView firsts display the items with the icons but disappears when trying to search and after. A help is so much appreciated, Thank you.
MainActivity.java
package com.example.asus.sdssuanhandbookapplication;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    MySimpleAdapter adapter;
    ListView listView;
    String[] items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list_view_article);
        items = getResources().getStringArray(R.array.article_list);

        adapter = new MySimpleAdapter(this, items);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String text = listView.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, "" + text, Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);

        MenuItem searchItem = menu.findItem(R.id.item_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextChange(String newText) {
                ArrayList<String> templist = new ArrayList<>();

                for (String temp : items) {
                    if (temp.toLowerCase().contains(newText.toLowerCase())) {
                        templist.add(temp);
                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this,
                        android.R.layout.simple_list_item_1, templist);
                listView.setAdapter(adapter);

                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

}

MySimpleAdapter.java
package com.example.asus.sdssuanhandbookapplication;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by asus on 2/9/2017.
 */

public class MySimpleAdapter extends BaseAdapter {

    private final Activity context;
    private final String[] names;
    int[] imgs = {R.drawable.icn1,
            R.drawable.icn2,
            R.drawable.icn3,
            R.drawable.icn4,
            R.drawable.icn5,
            R.drawable.icn6,
            R.drawable.icn7,
            R.drawable.icn8,
            R.drawable.icn9,
            R.drawable.icn10,
            R.drawable.icn11,
            R.drawable.icn12,
            R.drawable.icn13,
            R.drawable.icn14,
            R.drawable.icn15,
            R.drawable.icn16,
            R.drawable.icn17,
            R.drawable.icn18,
            R.drawable.icn19,
            R.drawable.icn20,
            R.drawable.icn21,
            R.drawable.icn22
    };

    static class ViewHolder{
        public TextView text;
        public ImageView image;
    }

    public MySimpleAdapter(Activity context, String[] names) {
        this.context = context;
        this.names = names;
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return names[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = convertView;

        if (rowView == null){
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.row_layout, null);
            //Configure view holder
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) rowView.findViewById(R.id.articleTxt);
            viewHolder.image = (ImageView) rowView.findViewById(R.id.articleImage);
            rowView.setTag(viewHolder);

        }

        ViewHolder holder = (ViewHolder) rowView.getTag();
        String s = names[position];
        int icon = imgs[position];
        holder.text.setText(s);
        holder.text.setTextSize(13);
        holder.image.setImageResource(icon);

        return rowView;
    }
}

row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_margin="10dp"
        android:id="@+id/articleImage"
        android:src="@drawable/icn1"/>

    <TextView
        android:layout_marginTop="15dp"
        android:layout_marginRight="20dp"
        android:text="title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:id="@+id/articleTxt"/>

</LinearLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.asus.sdssuanhandbookapplication.MainActivity">

    <ListView
        android:id="@+id/list_view_article"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Here are the actual shots of the app process:
Here is the Original ListView display on App first Open
Then when trying to query on Search, and displays the same after which Icons were gone

A: first when the listView is created you are using MySimpleAdapter when the search occurs you are calling different ArrayAdapeter the id for images are inside that of MySimpleAdapter. you wont be able to use those images

A: change your code like this in main
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    MySimpleAdapter adapter;
    ListView listView;
    String[] items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list_view_article);
        items = getResources().getStringArray(R.array.article_list);

        adapter = new MySimpleAdapter(this, items, null);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String text = listView.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, "" + text, Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);

        MenuItem searchItem = menu.findItem(R.id.item_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextChange(String newText) {
                ArrayList<String> tempList = new ArrayList<>();
                int[] indexs = new int[items.lenght];
                int j = 0;
                for (int i = 0; i < items.length; i++) {

                    if (items[i].toLowerCase().contains(newText.toLowerCase())) {
                        // getting String data
                        tempList.add(items[i]);
                        // getting index for images
                        indexs[j] = i;
                        j++;

                    }
                }
                // MySimpleAdapter with 3 parameters
                adapter = new MySimpleAdapter(MainActivity.this, tempList.toArray(new String[tempList.size()]), indexs);
                listView.setAdapter(adapter);

                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

}

and in MySimpleAdapter
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MySimpleAdapter extends BaseAdapter {

    private final Activity context;
    private final String[] names;
    private final int[] indexs;

    int[] imgs = {R.drawable.icn1,
            R.drawable.icn2,
            R.drawable.icn3,
            R.drawable.icn4,
            R.drawable.icn5,
            R.drawable.icn6,
            R.drawable.icn7,
            R.drawable.icn8,
            R.drawable.icn9,
            R.drawable.icn10,
            R.drawable.icn11,
            R.drawable.icn12,
            R.drawable.icn13,
            R.drawable.icn14,
            R.drawable.icn15,
            R.drawable.icn16,
            R.drawable.icn17,
            R.drawable.icn18,
            R.drawable.icn19,
            R.drawable.icn20,
            R.drawable.icn21,
            R.drawable.icn22
    };

    static class ViewHolder {
        public TextView text;
        public ImageView image;
    }

    public MySimpleAdapter(Activity context, String[] names, int[] indexs) {
        this.context = context;
        this.names = names;
        this.indexs = indexs;
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return names[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = convertView;

        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.row_layout, null);
            //Configure view holder
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) rowView.findViewById(R.id.articleTxt);
            viewHolder.image = (ImageView) rowView.findViewById(R.id.articleImage);
            rowView.setTag(viewHolder);

        }

        ViewHolder holder = (ViewHolder) rowView.getTag();
        String s = names[position];
        int icon;
        if(indexs == null) {
           icon = imgs[position];
        }
        else{
           icon = imgs[indexs[position]];
        }
        holder.text.setText(s);
        holder.text.setTextSize(13);
        holder.image.setImageResource(icon);

        return rowView;
    }
}


text:
Q: How host dotCMS application? I am developing an application in dotCMS. I created a new URL and in that URL added some html pages.But this is on the dotCMS. How to host this application like any other HTML based web site.Please help me to resolve this.

A: You can either name your host with the new URL you created or just edit your host and give the newly created URL as an alias for the host.


text:
Q: mongodb set/update aggregated unwound fields I have a document from mongo database looking like this:
{
  "_id": "00000001",
  "category": "Weather",
  "city": "Salt Lake City",
  "date": {
    "$date": {
      "$numberLong": "1663236000000"
    }
  },
  "logs": {
    "2022-09-14 12:00:00": {
      "temp": 55,
      "humidity": 25
    },
    "2022-09-14 14:00:00": {
      "temp": 65,
      "humidity": 35
    }
  }
}

I am trying to query it and have it look like this:
{
  "_id": "00000001",
  "category": "Weather",
  "city": "Salt Lake City",
  "date": {
    "$date": {
      "$numberLong": "1663236000000"
    }
  },
  "2022-09-14 12:00:00": "55, 25",
  "2022-09-14 14:00:00": "65, 35"
}

Currently my application query looks like:
collection.aggregate(
    [{
            $match: {
                _id: {
                    $exists: true
                }
            }
        },
        {
            $unwind: "$logs"
        },
        {
            $addFields: {
                "series._id": "$_id",
                "series.category": "$category",
                "series.city": "$city",
                "series.date": "$date",
            }
        },
        {
            $replaceRoot: {
                newRoot: "$logs"
            },
        }
    ])

which results in:
{
  "_id": "00000001",
  "category": "Weather",
  "city": "Salt Lake City",
  "date": {
    "$date": {
      "$numberLong": "1663236000000"
    }
  },
  "2022-09-14 12:00:00": {
      "temp": 55,
      "humidity": 25
    },
  "2022-09-14 14:00:00": {
      "temp": 65,
      "humidity": 35
    }
}

My problem is that the logs will add a new field every n hours, so the field names will be dynamic. I need to set/update the values for the unwound fields from objects to a string representation. How can I set/update field values for fields generated through $unwind aggregation like the example?

A: When field names are dynamic, one option is to use $objectToArray:
db.collection.aggregate([
  {$match: {_id: {$exists: true}}},
  {$set: {logs: {$objectToArray: "$logs"}}},
  {$set: {logs: {
        $map: {
          input: "$logs",
          in: {
            k: "$$this.k",
            v: {$concat: [
                {$toString: "$$this.v.temp"},
                ", ",
                {$toString: "$$this.v.humidity"}
              ]
            }
          }
        }
      }
    }
  },
  {$set: {logs: {$arrayToObject: "$logs"}}}
])

See how it works on the playground example
BTW, $unwind is for arrays, not for objects, hence the comment by @CharchitKapoor.

A: Building off of @nimrod serok's answer, still needed to flatten the logs field in my case. Used mergeObjects to flatten the field into the root document, and then used unset to remove the original field. This probably isn't the best way to do this but it is working for me. Thanks
[{$match: {_id: {$exists: true}}},
        {$set: {logs: {$objectToArray: "$logs"}}},
        {$set: {logs: {
              $map: {
                input: "$logs",
                in: {
                  k: "$$this.k",
                  v: {$concat: [
                      {$toString: "$$this.v.temp"},
                      ", ",
                      {$toString: "$$this.v.humidity"}
                    ]
                  }
                }
              }
            }
          }
        },
        {$replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", {$arrayToObject: "$logs"}] } } },
        {$unset: "logs"}
      ]


text:
Q: How to position the footer links in magento1.9? I want to remove the links in footer (below company, connect with us block) & move the newsletter block above the footer block in magento1.9 from below image:

A: go to  app/design/frontend/[yourpackage]/[yourtheme]/page/html/footer.phtml and remove footer (below company, connect with us block).
you have created CMS block named 'footer_data' from admin panel. Then following will be code to call them in footer.phtml
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('footer_data')->toHtml();
?>

OR
you using rdw, theme go to Static Blocks and edit "Footer Links SM" and "Footer Links Company".
For newsletter  go to page app/design/frontend/rwd/default/template/newsletter/subscribe.phtml
and change it(remove html).
Using xml Go to app/design/frontend/rwd/default/layout/newsletter.xml and comment <default>.. tag.
i hope it will be helpful.

A: For company links to remove or edit by default in magento Rwd theme from backend admin panel we get a option of Footer Company links.
Inside CMS -> static block -> Footer Company links

A: Check In the app/design/frontend/rwd/default/page/html/footer.phtml
go to above file and check where you find cms block for this section and login in admin panel go to cms-block and find that particular cms block and change it.
 or in footer.phtml file just comment below cms block line
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('social-media')->toHtml(); ?>


text:
Q: Timeout, asp.net c#, account - admin I have admin page, i edit there my site, which work with sql. after 3-4 min the admin page logout and ask me again to enter the username and password. how can i change the minutes at the timeout ?
i have tried this at the web.config:
<authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="60"/>
</authentication>

and this:
<authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="7200"/>
</authentication>

and...this:
  <httpRuntime requestValidationMode="2.0" useFullyQualifiedRedirectUrl="true"

         executionTimeout="72000"
         appRequestQueueLimit="90000"
         shutdownTimeout="90000" />

and all the results are the same... after 3-4 min (even when i click there, not only when idle) - the system doin logout.

A: The timeout in the 'forms' tag should work - do you have multiple configs?

A: <authentication mode="Forms">
            <forms timeout="20" slidingExpiration="true"/>
        </authentication>

Add a sliding expiration - let me know if that solves your problem.  What browser are you using?  Could it be that your cookie is not being persisted?

A: the answer was - to generate the keys at the machin key through iis 7 manager, and then change the session time again, at the iis 7 manager.


text:
Q: EJB3. How JNDI lookup works I'm building little framework for data processing with EJB 3.
I have Entity Access Object tier which abstracts from data source. Now I need some kind of factory which will give me right bean to query entities.
Is it safe to pass looked up through JNDI local bean interfaces as parameters to another local beans? Will each method invocation from this local interface be addressed to the same bean or each call will be passed to different stateless beans as in @EJB occasion?

A: You don't have any guarantee that using JNDI you will give you the same EJB instance, so it's the same as with dependency injection using @EJB or @Inject. The only difference between @EJB and JNDI lookup is the SFSB. In this case, the container is required to provide you new SFSB instance every time you use JNDI lookup.
However, in my opinion, in EJB 3.x and dependency injection era, it's more easy to understand the @EJB/@Inject annotation. No need to pass any object references, just define your dependencies (EJB collaborators) in each EJB using @EJB.


text:
Q: Need help to extract year from date? I am using regular expression to match date format. and also extract year, month, date from date. but I am unable to get complete year value here . if I am enter 2013-02-29 than I am getting 20 in year instead of 2013. What I am trying here is :-
$(document).ready(function(){
    var dateVal = '2013-06-01';
    var rxDatePattern = /^(19|20)\d\d(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/;
    var dtArray = dateVal.match(rxDatePattern);

    dtYear = dtArray[1];
    dtMonth = dtArray[3];
    dtDay = dtArray[5];

    jQuery.each(dtArray, function(index, value) {
        console.log(index + ': ' + value);
    });
});

I am getting output :-
0: 2013-06-01

1: 20

2: -

3: 06

4: -

5: 01

here is fiddle : http://jsfiddle.net/roop1886/rYh8N/1/
Here is complete code where I am using above code :-
//varify date formate
jQuery.validator.addMethod(
    "siteDateValidator",
    function (value, element) {
        var currVal = value;
        if (currVal != '') {
            var rxDatePattern = /^(19|20)\d\d(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/;
            var dtArray = currVal.match(rxDatePattern);
            if (dtArray == null) {
                return false;
            }
            dtYear = (dtArray[1]);
            dtMonth = (dtArray[3]);
            dtDay = (dtArray[5]);

            if (dtMonth < 1 || dtMonth > 12) return false;
            else if (dtDay < 1 || dtDay > 31) return false;
            else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false;
            else if (dtMonth == 2) {
                var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
                    if (dtDay > 29 || (dtDay == 29 && !isleap)){
                        return false;
                    }
            }
        }
        return true;
    },
    "Please enter a valid date, date format should be(yyyy-mm-dd) and year should be greater than equal to 1900."
);

A: Why not use the build in javascript Date class?
var d = new Date("2013-02-29");
d.getFullYear(); // 2013

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Update:
You can detect if the given date was invalid by calling:
var valid = !isNaN(d.getTime()); // returns true if valid, false if invalid

A: Why don't use split()?
var dateVal = '2013-02-29';
var dtArray = dateVal.split("-");

dtYear = (dtArray[0]);
dtMonth = (dtArray[1]);
dtDay = (dtArray[2]);

alert(dtYear);
alert(dtMonth);
alert(dtDay);

A: What about something like this:
var dateVal  = '2013-06-01';
var parts    = dateVal.match(/(\d{4})-(\d{2})-(\d{2})/)
var testDate = new Date(parts[1], parts[2] - 1, parts[3])
var isFormatValid = parts[1] == testDate.getFullYear()     && // format check
                    parts[2] == testDate.getMonth   () + 1 &&
                    parts[3] == testDate.getDate    ()

var isBusinessValid = isFormatValid && parts[1] >= 1900; // business related

alert(dateVal + "\n" + testDate + "\n" + isFormatValid + "\n" + isBusinessValid)

In this case, you don't need to deal with full date support in your regex, just extract relevant parts, build a Date object and compare with entered input. Javascript will care about leap years and stuff for you.

A: Here is simple answer:
var rxDatePattern = /^(19[\d]{2}|20[\d]{2})(\-)(0[1-9]|1[012])(\-)(0[1-9]|[12][0-9]|3[01])$/;

A: Replace your regular expression you missed grouping for year part. it should be (?:19|20)\d\d) instead of (19|20)\d\d
/^((?:19|20)\d\d)(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/

Here is working fiddle :- http://jsfiddle.net/roop1886/rYh8N/2/

A: If you want to validate the date and format, you can use:
// Validate date in format yyyy-mm-dd
// Leading zeros on single digit months and days are optional
function validateDate(dateString) {
  var s = dateString.split('-');
  var d = new Date(s[0], --s[1], s[2]);
  return d && d.getFullYear() == s[0] && d.getDate() == s[2];
}

If you want to check that single digit months and days have a leading zero, go for it but I don't see the point.


text:
Q: Keras - Objective function for number in range [0-100] Lets say I've ground truth (output) of a number in range [0-100].
Is it possible to learn to predict a number that minimize the delta from the original number (gt) according the input ?
The objective types of Keras are here http://keras.io/objectives/

A: I think your best bet would be to use mean squared error (loss='mse'), which penalizes predictions based on the square of their difference from the ground truth.  You would also want to use linear activations (the default) for the last layer.
If you're especially concerned about keeping the predictions within the range [0, 100], you could create a modified objective function that penalizes predictions outside [0, 100] even more than quadratically, but that's probably not necessary and you could instead just clip the predictions using np.clip(predictions, 0, 100).


text:
Q: Create object from ps1 file I swear I've seen an example of how you could "import" the content of a .ps1 (yes, intentionally not a .psm1) file.  My goal is to encapsulate the content of a .ps1 file, with functions and maybe even variables declared outside of functions, in a $variable.  So, if I have the following:
# ps1 file
Function myFunc {

  [CmdletBinding()]
  Param(...)

  # Function stuff

}

I want to do something like this:
$newObject = New-Object (New-Module -ScriptBlock (%GET_CONTENT_FROM_PS1_FILE%))
$newObject.myFunc()
# etc.

Is this possible?

A: As beautifully exemplified in PetSerAl's comment, you're already on the right track:
PS> $newObject=New-Module -ScriptBlock (Get-Command .\Test.ps1).ScriptBlock -AsCustomObject
PS> $newObject.myFunc
Script              :

OverloadDefinitions : {System.Object myFunc();}
MemberType          : ScriptMethod
TypeNameOfValue     : System.Object
Value               : System.Object myFunc();
Name                : myFunc
IsInstance          : True

Yay! Problem is that this only exports the functions, not any variables.
What you could do, is add Export-ModuleMember to the ScriptBlock argument:
$ps1ScriptBlock    = Get-Content .\Test.ps1 -Raw
$exportCommand     = 'Export-ModuleMember -Function * -Variable *'
$moduleScriptBlock = [scriptblock]::Create(@($ps1ScriptBlock,$exportCommand) -join "`r`n")

$moduleObject = New-Module -ScriptBlock $moduleScriptBlock -AsCustomObject

Now, variable $myVar will be accessible as:
$moduleObject.myVar


text:
Q: Milliseconds out of sync I am developing a stopwatch application using Javascript/jQuery. The problem is that the milliseconds value is out of sync with REAL milliseconds. I am using function setInterval() with the interval of 1 millisecond, still it is causing this problem.
jsFiddle: http://jsfiddle.net/FLv3s/
Please help!

A: Use setInterval to trigger updates, but use the system time (via new Date()) for the actual time calculations.

A: To be honest, I tried nearly the same thing as you do now (Creating an accurate Metronome in Javascript only) - to make a long story short: To be absolutely accurate in terms of milliseconds (or lower) is sadly not (yet) possible with javascript only.
For more insight i recommend this question: Does JavaScript provide a high resolution timer?
or to be more precise this blog article: http://ejohn.org/blog/how-javascript-timers-work/
Best regards,
Dominik

A: Program execution in any language, not just JavaScript, is not realtime. It will take a tiny amount of time to actually run the code to increment your counter and update the view, and that throws the "timing" off.
Additionally, many browsers have a "minimum timeout" length, which varies between 4 and about 16 (the latter being the computer's own clock timer), which will really mess with your code.
Instead, you should use delta timing.
var startTime = new Date().getTime();
setInterval(function() {
    var elapsed = new Date().getTime()-startTime;
    // update view according to elapsed time
},25);

If you're worried about it looking choppy, consider using requestAnimationFrame instead, to update the timer exactly once per frame - this has the added benefit of not updating when the user switches tabs (but it will still be timing them) because if the tab is not active then there's no need to redraw stuff.

A: You can use the new performance object to get a more accurate time. Combine this with requestAnimationFrame instead of setInterval:
var startTime = performance.now(),
    currentTime,
    isRunning = true;

loop();

function loop(timeElapsed) {

    currentTime = performance.now();
    if (isRunning) requestAnimationFrame(loop);
}

Just subtract startTime from currentTime.
I left timeElapsed which contains time elapsed handed by rAF which you can may use also for something (or just ignore it).
One note though: not all browsers support this yet (and some may use prefix) so for mobile you need to use the standard system time object.


text:
Q: orientdb connect invalid password and username I have a problem on my linux mint. I installed OrientDB, create a database and successfully connect to this database with password and username root root. But after closing server.sh and reopening this server.sh i couldn't connect to this database, it write that Invalid password and username. Can u say what's problem?

I think that it's with permission, but i open console.sh as superuser, want to connect and write:
CONNECT REMOTE:LOCALHOST/SAD ROOT ROOT
write this error.
Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open local storage '/opt/orientdb/databases/sad' with mode=rw
Error: com.orientechnologies.orient.core.exception.OSerializationException: Cannot load database's configuration. The database seems to be corrupted.
Error: java.lang.NullPointerException: Name is null.

A: I found my mistake, when I installed oriendb i use superuser terminal which create folder with permission as root. Now I delete the folder and reinstall it from user terminal. it works.


text:
Q: Recv fails when using python sendall in iOS project I have a python server that is trying to send a binary file to a client on iOS but 90% of the time the file is incomplete. The receive call on the client fails after receiving about 80% of the file.
This is basically how it's setup.
Server
class ForkingTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
            f = open(TEST_FILE_NAME, 'rb')
            file_data = f.read()
            self.request.sendall(file_data)
            f.close()

class ForkingTCPServer(SocketServer.ForkingMixIn, SocketServer.TCPServer):
    pass

if __name__ == '__main__':
    try:
        server = ForkingTCPServer(('0.0.0.0', 9000), ForkingTCPRequestHandler)
    except socket.error as e:
        sys.exit(1)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        sys.exit(0)

This code works outside of our iOS project (entire file is received)
int receiveFile() {
    /* ... */

    /* Receive file */
    tempBuf = (char*) malloc(sizeof(char)*fileLen);
    totalRecv = 0;
    recvBytes = 0;

    while (totalRecv < fileLen) {
        recvBytes = recv(s, tempBuf+totalRecv, 1<<14, 0);
        if (recvBytes < 0) {
            free(tempBuf);
            close(s);
            return -1;
        }
        totalRecv += recvBytes;
    }

    close(s);
    return 0;
}

int connectToServerWithHostname(char *hostname, char *port) {
    /* ... */

    memset(&targetAddr, 0, sizeof(targetAddr));
    targetAddr.sin_family = AF_INET;
    targetAddr.sin_port = htons(atoi(port));
    bcopy(hostdetails->h_addr, (char *)&targetAddr.sin_addr, hostdetails->h_length);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (socket < 0) {
            return -1;
    }

    rc = connect(sock, (struct sockaddr *)&targetAddr, sizeof(targetAddr));
    if (rc < 0) {
            close(sock);
            return -1;
    }

    return sock;
}

int main(int argc, char **argv) {
    assert(!receiveFile());
    return 0;
}

But this equivalent code inside our iOS project fails (partial receive). Even though I'm connecting and receiving the same way as the code above.
while (totalRecv < ntohl(symProcPacket.totalDataLen)) {
    recvBytes = recv(s, tempBuf+totalRecv, DEFAULT_SENDRECVSIZE, DEFAULT_SENDRECV_FLAGS);
    if (recvBytes < 0) {
        debug("Error, could not receive file\n");
        free(tempBuf);
        errorType = kSymClientErrorReceiving;
        goto errorImporting;
    }
    totalRecv += recvBytes;
    printf("Received: %d/%d\n", totalRecv, ntohl(symProcPacket.totalDataLen));
}

Any ideas on why this is failing?
Are sockets different in an iOS project or something?


text:
Q: How can we detect People Name and his Designation/Role from a sentence using Deep learning? Let's say for a paragraph like:

Satya Nadella is Chief Executive Officer of Microsoft. Before being named CEO in February 2014, Nadella held leadership roles in both enterprise and consumer businesses across the company. Another tech giant company is HP and Dion J. Weisler is President, Chief Executive Officer, Director of the Company. Previously, he served as Executive Vice President of the Printing and Personal Systems Group of Hewlett-Packard Company from June 2013 to November 2015.

This will be as an input for deep learning model. And detected people and designation would be like:
[Satya Nadella, Chief Executive Officer]
[Dion J. Weisler, President]
Any idea how we solve this challenge and what should be the best deep learning algorithm for it?

A: Read this state of art review paper:
https://arxiv.org/pdf/1708.02709.pdf
and this article:
https://medium.com/dair-ai/deep-learning-for-nlp-an-overview-of-recent-trends-d0d8f40a776d
Your problem generally falls into the "simple relation" types and this paper will be highly relevant:
http://acl2014.org/acl2014/P14-2/pdf/P14-2105.pdf
To be more concrete your solutions may involve several layers of functionalities:
a. First is to sift all the sentences that have simple vs non-simple relationship.
b. Next for the simple relationship you should again sift out (based on whitelisting all known vocations (eg, "CEO", "farmer", "singer" etc) and throw away all other sentences.
c. For what remains, you will want to extract out all "xxx is CEO" or "CEO is yyy" sentences.
d. Last step may be to eliminate sentences with common words as "xxx" or "yyy" above, for eg, "CEO is very happy", or "The dog belong to CEO".   A name is usually anything "not-seen-before".


text:
Q: SSH allow windows AD groups(with Special charactors) I have join my linux to windows domain succesfully, and now everyone in the domain is able to log in to the server by using ssh.
But we only want to allow certain users from a group to log in.
Example of current two groups:
#it_admin

Domain Admin

A: You can do this in two ways. One is to let the SSH configuration filter, and the other is to use pam_access.
Using SSH configuration
To /etc/ssh/sshd_config, add a AllowGroups line:
AllowGroups Domain Admin

From the manpage:
AllowGroups
    This keyword can be followed by a list of group name patterns,
    separated by spaces.  If specified, login is allowed only for
    users whose primary group or supplementary group list matches one
    of the patterns.

Domain Admin here doesn't match Domain Admin the group name, but two separate groups Domain and Admin. You'll have to use something like Domain*Admin and *it_admin, since neither  (space) nor (#) are usually valid characters in Linux groups. To be on the safer side, use ? instead of *: Domain?Admin and ?it_admin, so that only one character is allowed by the wildcard. You can also add a pattern-based DenyGroups section. See the PATTERNS section in man ssh_config.
Using pam_access
Add lines to /etc/security/access.conf of the form:
- : ALL EXCEPT (Domain) (Admin) : ALL

There are plenty of comments in that file which document how to use it. man pam_access is quite bare, so most information would come from those comments. pam_access is more powerful in that it can control non-SSH logins as well (TTYs, GUI, etc.). This particular line, for example, should deny any user who does not have Domain or Admin as a group from logging in at all (unless other lines allow them).
Both approaches are pretty flexible, and I don't know the pros and cons, so no recommendations.


text:
Q: Как написать шаблон функции для вычисления размера массива C++ Не могу разобраться в том, как это реализовать, приведите, пожалуйста, код такого шаблона.

A: Ну, например...
template<typename T, size_t N>
size_t dim(T (&)[N]) { return N; }

int main()
{
    int x[4];
    double t[] = {1,2,3};

    cout << dim(x) << endl;
    cout << dim(t) << endl;
}

Шаблонная функция, которой передаем ссылку на массив (имя неиспользованного параметра я не стал и указывать). При инстанцировании она выводит значение N, каковое и возвращает...