text:
Q: Is it possible to use filter and filterPredicate both in angular material? I can only use either the function of filter or filterPredicate.
When I try to use it both function (filter + filterPredicate ) in one component.
filter function will generate a error:
"core.js:14597 ERROR SyntaxError: Unexpected token  in JSON at position 0"

It will works fine only if I use filter or filterPredicate.
Below is the Component and the Component.ts:
HTML:
      <mat-form-field class="search-form-field" floatLabel="never">
        <input matInput [(ngModel)]="searchKey" placeholder="Search" autocomplete="off" (keyup)="applyFilter()">
      </mat-form-field>

          <ng-container matColumnDef="dataYear">
              <mat-header-cell *matHeaderCellDef>
                  <mat-form-field class="searchIncolumn">
                    <mat-icon matPrefix>search</mat-icon>
                    <input matInput placeholder="Year" [formControl]="yearFilter" />
                </mat-form-field>
              </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.dataYear}} </mat-cell>
            </ng-container>

TS:
yearFilter = new FormControl();
displayedColumns: string[] = ['dataYear'];

NgOnit() {
  this.dataService.getData().subscribe(
    response => {
      this.listData = new MatTableDataSource(<any> response);
      this.listData.sort = this.sort;
      this.listData.paginator = this.paginator;
      this.listData.filterPredicate = this.tableFilter();
    }
    ,errorResponse => { console.log(errorResponse); }
      );
}

tableFilter(): (data: any, filter: string) => boolean {
  let filterFunction = function(data, filter): boolean {
    let searchTerms = JSON.parse(filter);
    return data.dataYear.toString().indexOf(searchTerms.dataYear) !== -1
          && data.dataMonth.indexOf(searchTerms.dataMonth) !== -1
          && data.sources.toLowerCase().indexOf(searchTerms.sources) !== -1
          && data.population.toString().indexOf(searchTerms.population) !== -1;
  }
  return filterFunction;

}

applyFilter() {
  this.listData.filter = this.searchKey.trim().toLowerCase();
}

A: FILTERPREDICATE OVERRIDES FILTER
filter: string
Filter term that should be used to filter out objects from the data array. To override how data objects match to this filter string, provide a custom function for filterPredicate.
filterPredicate: (data: T, filter: string) => boolean
Checks if a data object matches the data source's filter string. By default, each data object is converted to a string of its properties and returns true if the filter has at least one occurrence in that string. By default, the filter string has its whitespace trimmed and the match is case-insensitive. May be overridden for a custom implementation of filter matching.


text:
Q: I have created a Maven project in eclipse I have below jar files: sl4j-log4j12-1.7.25 but while executing i am getting the below error:
SLF4J: The requested version 1.6.99 by your slf4j binding is not compatible with [1.5.5, 1.5.6]
SLF4J: See here for further details.

Exception in thread "main" java.lang.NoSuchMethodError:
  org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Lorg/slf4j/helpers/FormattingTuple;
    at
  org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:346)

A: Make sure your slf4j-api version is the same as your slf4j-log version.
Your answer is in the link you provided!

slf4j-api version does not match that of the binding
An SLF4J binding designates an artifact such as slf4j-jdk14.jar or slf4j-> > log4j12.jar used to bind slf4j to an underlying logging framework, say, java.util.logging and respectively log4j.
  Mixing mixing different versions of slf4j-api.jar and SLF4J binding can cause problems. For example, if you are using slf4j-api-1.8.0-alpha2.jar, then you should also use slf4j-simple-1.8.0-alpha2.jar, using slf4j-simple-1.5.5.jar will not work.
NOTE From the client's perspective all versions of slf4j-api are compatible. Client code compiled with slf4j-api-N.jar will run perfectly fine with slf4j-api-M.jar for any N and M. You only need to ensure that the version of your binding matches that of the slf4j-api.jar. You do not have to worry about the version of slf4j-api.jar used by a given dependency in your project. You can always use any version of slf4j-api.jar, and as long as the version of slf4j-api.jar and its binding match, you should be fine.
  At initialization time, if SLF4J suspects that there may be a api vs. binding version mismatch problem, it will emit a warning about the suspected mismatch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linq to CSV DateTime format using C# I have a huge CSV file with columns like this.
col1;col2
2013-12-17 15.52.35;1,09
2013-12-17 16.52.35;2,09
2013-12-17 17.52.35;3,09
I am trying to print the first column but it wont due to a different date/time format. However it prints the column in format 2013-12-17 15:52:35.
public class LinqData
{
    [CsvColumn(FieldIndex = 1)]
    public DateTime col1 { get; set; }

    [CsvColumn(FieldIndex = 2)]
    public float col2 { get; set; }
}

public class LinqToCSV
{
    public static IEnumerable<LinqData> somefunction()
   {
       var inputFileDescription = new CsvFileDescription
        {
            SeparatorChar = ';',
            MaximumNbrExceptions = -1,
            FileCultureName = "sv-SE"
        };

        CsvContext cc = new CsvContext();

        IEnumerable<LinqData> CSVelements =
            cc.Read<LinqData>(@"C:\sample.csv", inputFileDescription);
        return CSVelements;
    }

   public LinqToCSV()
    {
        var inputFileDescription = new CsvFileDescription
        {
            SeparatorChar = ';',
            MaximumNbrExceptions = -1,
            FileCultureName = "sv-SE"
        };
        CsvContext cc = new CsvContext();

        IEnumerable<LinqData> CSVelements =
            cc.Read<LinqData>(@"C:\sample.csv", inputFileDescription);

        var CSVelementNames = from p in CSVelements
                              orderby p.col1
                              select new { p.col1, p.col2 };

        foreach (var item in CSVelementNames) { Console.WriteLine(item); }
    }
}

Thanks in advance for the kind help.

A: If you want output datetime value for specific culture you can use DateTime.ToString Method (IFormatProvider) like this
....
foreach (var item in CSVelementNames) {
    Console.WriteLine("DateTime:{0}, Value:{1}",
    item.col1.ToString(System.Globalization.CultureInfo.GetCultureInfo("sv-SE").DateTimeFormat),
    item.col2);
}
....

if you want output only date so you can use DateTime.ToShortDateString Method
foreach (var item in CSVelementNames) {
    Console.WriteLine("Date:{0}",
    item.col1.ToShortDateString());
}

Or use your custom format string like this
foreach (var item in CSVelementNames) {
    Console.WriteLine("Date:{0:yyyy-MM-dd HH.mm.ss}",item.col1);
}


text:
Q: React hash routing and sub routing I have currently route structure for example
#/home
#/dashboard
but how can I implement sub-route or child route such as
#/home/dashboard
<HashRouter>
              <main className="h-100">
                <Switch>
                  <Route exact path='/home' component={Login} />
                  <Route path='/dashboard' component={Dashboard} />
                </Switch>
              </main>
            </HashRouter>

A: You can simply change the route to sub routes, for example
<Route exact path='/home/subroute' component={Login} />


text:
Q: How do I do a nested group by query in SQL Server? I have the following query that I'm working on that involves producing a query involving a nested result of records but I'm not sure how to do a sub-query group by or if it's even possible at all.
create table places (
id int not null identity primary key,
country varchar(32) not null,
continent varchar(32) not null,
hits int not null
);

insert into places (country, continent, hits) values
('Canada', 'North America', 8),
('Canada', 'North America', 5),
('United States', 'North America', 2),
('Germany', 'Europe', 5),
('Germany', 'Europe', 9),
('Germany', 'Europe', 1),
('France', 'Europe', 3),
('Italy', 'Europe', 6),
('Italy', 'Europe', 9),
('China', 'Asia', 7),
('China', 'Asia', 8),
('Japan', 'Asia', 7);

select country, count(*) as Total from places
group by country with rollup
order by country asc;

This query produces the following result:
(null)                12
Canada                2
China                 2
France                1
Germany               3
Italy                 2
Japan                 1
United States         1

I would like the query to produce a result that looks like this:
(null)                12
Asia                  3
  China               2
  Japan               1
Europe                6
  France              1
  Germany             3
  Italy               2
North America         3
  Canada              2
  United States       1

Here is a SQL Fiddle link to play with this: http://sqlfiddle.com/#!18/9145b/2
Hopefully this is possible to do in SQL Server and any help would be appreciated!

A: You can use grouping sets for the aggregation.  Getting the right order is a bit tricky:
select coalesce(country, continent), count(*) as Total
from places
group by grouping sets ( (country), (continent), () )
order by (grouping(country) + grouping(continent)) desc, min(continent), grouping(continent);

Here is a db<>fiddle.

A: Use grouping sets
select coalesce ('  ' + country, continent, 'TOTAL') item,  count(*) as Total
from places
group by GROUPING sets((country, continent), (continent), ())
order by coalesce(continent, 'Z'), country asc;


text:
Q: Firestore - How to do a .set() on multi-level document I can't seem to find the answer to this in the Firestore documentation, but if I wanted to do something as simple as this, in my Angular 6 application:
firebase.firestore().collection(`fb_ad_accounts`).doc(`${adAccountId}/${id}`).set({
  name: name,
  id: id,
  date_created: new Date().getTime()
})

I get an error that says
Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Invalid document reference. Document references must have an even number of segments, but fb_ad_accounts/779737999495825/249155905774166 has 3

I'd like to build my data like this, but I can't figure out how to do a simple add() to a tree that looks like fb_ad_accounts/<account_id>/<ad_account_id>
Am I missing something obvious here?
Thanks in advance!

A: In Firestore, a document may contain only fields with values.  A document cannot contain another documents.
Documents may have subcollections organized underneath them (that each may have their own documents), but these subcollections are not technically contained in the document itself.
The error message essentially is reminding you of these facts, but in a somewhat mathematical way.
If you want a document to appear "nested" within another document, you'll have to choose the name of a subcollection where it will appear.  For example:
fb_ad_accounts/<account_id>/ads/<ad_account_id>

Note the "ads" subcollection appears underneath the  document.  Mathematically speaking, it's a valid path for a document because it has an even number of path components (4).


text:
Q: Is it possible/correct to describe electromagnetism using curved space(-time)? Comparing the simples form of the forces of both phenomena: the law of Newton for gravitation  $V\propto \frac{1}{r}$, and the Coulomb law for electrostatics $V\propto \frac{1}{r}$, one might think that if one can be extended relativistically to a curvature in space-time, that the other one would lend itself to a similar description. Is this so?
Thanks for any useful thoughts and/or suggestions!

A: I don't really follow the text underneath the title, but the answer to this
question is most certainly, yes.  (For example, we witness electromagnetic
waves traveling through curved space.)  Here is how electromagnetism is
described mathematically (I fear this answer is slightly beyond the level of the
questioner -- sorry -- but perhaps not of other readers):
Maxwell's equations are best expressed in terms of the field strength
tensor.  That tensor is the curvature of a connection on a circle bundle
(over spacetime).  The connection is the four-vector electromagnetic
potential, in physics terms.  In this set up, two of Maxwell's equations
are automatic (for example, saying that the magnetic field is locally the curl
of a 3-vector is saying that it is divergence-free).  The other two are
equations for the "divergence" of this tensor.  This way of phrasing
the problem makes sense in any metric, i.e. on curved spacetimes.

A: Everyone else here is right, but there is also an unmentioned complication to using curvature to explain electromagnetic forces:
We use curvature to explain gravity in an attempt to explain why intertial and gravitational masses are the same--why a bowling ball falls the same rate as a penny.  Einstein's answer was that it's because they're just travelling in 'straight' lines in the same spacetime, and aren't feeling any forces at all--they're just trying to move in the straightest line they can.
But with E&M, not all charges feel the same force in a given electric field--in fact, chargless particles feel no force at all!  So, if we're going to explain E&M using curvature, we're going to need to explain why different particles have different charges.

A: I'm not sure if this is exactly what you're getting at, but there have been attempts to derive electromagnetism as a consequence of general relativity. The most famous one is Kaluza-Klein theory, published in 1921. The theory is basically just general relativity in a 5-dimensional spacetime, where one of the dimensions is "curled up" (compact). It turns out that the additional equations of motion obtained from the compact dimension are equivalent to the Maxwell equations for electromagnetism (in the relativistic form Eric described).


text:
Q: Divide terms between two list I'm trying to work with two list, both of them with 2000 numbers in it.
I want to divide every term on the first list with the corresponding term in the second list, and save that division in a new list
For example:
    first = [1,2,3 ...]
    second = [4,5,6 ...]

    prob = [i/a for i,a in first,second]

I would like the result will be:
    prob = [1/4,2/5,3/6 ...]

But when I do this, I get the error ValueError: too many values to unpack
Any help?
Thanks.

A: You have to use zip:
prob = [i/a for i,a in zip(first,second)]

Also, unless you have python3.x, the division (/) operator will perform integer division. Therefore, if you want float values and you are using python2.x, you should convert one of the values to float as follows:
prob = [float(i)/a for i,a in zip(first,second)]

A: Not really an answer but in this case, using operator and map is probably a faster way:
In [16]:

from __future__ import division
import operator
In [17]:

first = [1,2,3]
second = [4,5,6]
map(operator.truediv, first, second)
Out[17]:
[0.25, 0.4, 0.5]
In [18]:

%timeit [float(i)/a for i,a in zip(first,second)]
100000 loops, best of 3: 6.08 µs per loop
In [19]:

%timeit map(operator.truediv, first, second)
100000 loops, best of 3: 3.34 µs per loop

numpy also provide yet another concise way to do it.
In [20]:

import numpy as np
arrf=np.array(first)
arrs=np.array(second)
arrf/arrs
Out[20]:
array([ 0.25,  0.4 ,  0.5 ])
In [21]:

%timeit arrf/arrs
100000 loops, best of 3: 5.07 µs per loop

It is not the fastest for such a small problem. But might win in big ones.


text:
Q: Highcharts. Is it possible to show data labels programmatically According to this my question I can show/hide datalabels by clicking on a point. But at this example dataLabels enabled show be set to true by default, otherwise I can't show them. Nothing happens when I click on a point.
point: {
    events: {
        click: function() {
            // on first click this.dataLabels is undefined...
            var e = !this.dataLabels || this.dataLabels.enabled ? false : true;
                this.update({
                    dataLabels: {
                        enabled: e
                    }
                });
            }
        }
    }

This code works fine only if I set
dataLabels: {
    enabled: true
}

Thanks for help.

A: Simply change condition to:
                    click: function(){
                        var e = !this.dataLabels || !this.dataLabels.enabled ? true : false;
                        this.update({
                            dataLabels:{
                                enabled: e
                            }
                        });
                    }

Demo: http://jsfiddle.net/7wLxwfq6/2/


text:
Q: AngularJS does not read table values I am trying to implement a table where you could edit information of a user. The information is retrieved from database and I want to update the database with new variables. The problem is when I press the editbutton and try to pass my new variables from form, it does not read it, but when I add the button inside the column it reads the variables.
For e.g. In the code currently it reads the trainee.TraineesID and passes it through to my controller, the others are undefined. If I add the button inside the input form, it retrieved the information and passes it to the controller.
Is there a way to retrieve all the information from the forms and pass it to controller?
The code is:

        {{trainee.Name}}
        <input type="text" name="Name" ng-init="nameInput=trainee.Name" ng-model="nameInput" placeholder="Name">
        {{trainee.Surname}}
        <input type="text" name="Surname" ng-model="surnameInput" ng-init="surnameInput=trainee.Surname" placeholder="Surname">
        Deployed
        Training
        On Bench
        <select name ="Status" ng-model="statusInput" placeholder="Select">
        <option value="1">Deployed</option>
        <option value="2">Training</option>
        <option value="3">Bench</option>
        </select>
        {{trainee.Email}}
        <input type="text" name="Email" ng-init="emailInput=trainee.Email" ng-model="emailInput" placeholder="Email">
        {{trainee.PhoneDetails}}
        <input type="text" name="Phone" ng-init="phoneInput=trainee.PhoneDetails" ng-model="phoneInput" placeholder="Phone">

A: Thank you very much Rob. The problem is solved by assigning the ng-module to the scope. I used ng-init="editTrainee.nameInput=trainee.Name" ng-model="editTrainee.nameInput"
" and to pass variables ng-click="editTrainee(trainee.TraineesID, editTrainee.nameInput)


text:
Q: How to show a temporary image(placeholder) till actual image loads from server , Angular2 I am currently learning angular2. I have situation where I need to load image from web server, which takes some time, till than the img tag is not rendered / size remains 0 px. which looks odd in layout when image loaded properly.
Is it possible to show a temporary image till actual image loads.
EDIT :: my img tag is now like this ::
<img [src]="getImageUrl(package.id,package.poster_path) || 'assets/img/no_image.png'" alt="" class="bookposterImg" />

But its not working. no_image is not shown till server image arrives.

A: Use If condition like this
<img class="logo" [src]="Server_image || Placeholder_imagw" alt="Anything">


text:
Q: Internet Explorer Nightly Build Where i can download nightly build for IE?
I searched google and found nothing.
Its really good if Microsoft offer nightly/standalone build.
Majority of good browsers like Firefox, Chrome, Safari offer nightly builds.
IE got a development build?

A: You are mistaken.
Chrome does not offer nightly builds, although they do have an open source project called Chromium that does offer nightly builds (Chrome is based on Chromium, but they are not identical).
Similarly, Safari does not offer nightly builds either, though again they have an open source project based on WebKit.
In fact, the only major browser that offers nightly builds is Firefox.  A number of minor browsers (usually based on gecko or webkit) also offer nightly builds, but aren't particularly important.
IE, Opera, Chrome, Safari, etc only offer developer snapshots at various stages of the development cycle.
So your assertion that because IE doesn't offer nightly builds it must be a bad browser is not a valid argument.
EDIT:
There is not yet any development build for IE11, nor would I expect one for at least a year.  Microsoft just released IE10 officially for Windows 7, and it's been out for Windows 8 since November.

A: There is no general availability of development builds of IE. Microsoft simply does not do that.
They do provide beta releases of IE prior to releasing a new version -- for both IE9 and IE10, there were a series of pre-releases prior to general release, but this process was carefully controlled by Microsoft -- there were only a handful of pre-releases; certainly not a nightly build.
The main reason for this is that IE is not open source. The developers of the open source browsers have a culture and an incentive to release more often, and nightly builds are a result of that. Microsoft's culture and release strategy is completely different.

A: There is Internet Explorer 11 (not officialy released, you can take it as nightly build) but right now it's only on Windows 8.1 Preview.


text:
Q: How set authenticate in InfluxDB? I'm having troubling with set authenticate in InfluxDB. First the follow tutorial told me to change the config file:
https://docs.influxdata.com/influxdb/v1.7/administration/authentication_and_authorization/#set-up-authentication
[http]
  enabled = true
  bind-address = ":8086"
  auth-enabled = true # ✨
  log-enabled = true
  write-tracing = false
  pprof-enabled = false
  https-enabled = false
  https-certificate = "/etc/ssl/influxdb.pem"

But when i change, and reload the server. I can't create users.
 CREATE USER paul WITH PASSWORD 'timeseries4days' WITH ALL PRIVILEGES
 ERR: unable to parse Basic Auth credentials
 Warning: It is possible this error is due to not setting a database.
 Please set a database with the command "use <database>".

So, when a use my database that i created:
 USE example
 ERR: unable to parse Basic Auth credentials

Now i don't know what i exactly do to set my authenticate to give only a user (In this case paul) the power to READ and WRITE my database example.

A: Now that Authentication is enabled, you'll need to authenticate yourself before you can do anything in the database.
The error unable to parse Basic Auth credentials is suggesting that you did not pass in any credentials.
If you're trying use the influx binary to create an user then you'll have to set the -username and -password options.
For instance:
influx -username "my_username" -password "my_password" \
        -execute "CREATE USER parul WITH PASSWORD 'timeseries4days'


text:
Q: Is it necessary to Dispose() when using a custom ServiceHostFactory? Is it necessary to Dispose() when using a custom ServiceHostFactory?
In my WCF .svc file I have defined a custom Factory as:
<%@ ServiceHost Factory="Service.ServiceHostFactory" %>
It appears that a Dispose() is not being called since the overridden CreateServiceHost() method is not being called at each execution of the application calling the service.  (Also, among other things, logging is not being performed after each call and the trace.xml file I generated says that it is in use by another process).
I do have the service decorated with
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
so I expect something else is going on that I'm not aware of.  In the client application where the instance to the service is created I am Dispose()'ing of the reference via a finally block but is it necessary to perform a similar operation in the Factory on the server side?
    Finally
        service.Dispose()
    End Try

Thanks

A: The service host factory returns a service host, not an instance of the service class. The factory is usually called only once per activation of the service, and the host it returns is used until the IIS application pool is recycled. The service instance is handled by an IInstanceProvider, not the service host (although as you're creating the host you can change the instance provider if you want to dispose the service instance - for more information about instance providers, see http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx and http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx).
So in short, you should not dispose the service (or is it the host?) which you're returning from the service host factory. If you want to handle service disposal, you should implement your own instance provider.


text:
Q: .htaccess is interfering with nested .htaccess/.htpasswd? I'm using Simple Mailing List (http://www.notonebit.com/projects/mailing-list). It's good mailing list, but no admin area. So you have to use .htaccess/.htpasswd to protect the /mail/admin folder.
However, my site has WordPress installed in the website's root folder. WordPress creates .htaccess for custom permalinks. And for some reason, this interferes with the .htaccess of my /mail/admin/.
When I delete the WordPress .htaccess file, my password protection works properly on /mail/admin. However, when the WordPress .htaccess is present and I load /mail/admin in browser, I'm never asked for a password and I see a WordPress 404 page that says "page not found..."
Here are my files... WordPress .htaccess (located in root folder):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Mailing List .htaccess (located in /mail/admin):
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/myUsername/public_html/mySndSite/mail/admin/.htpasswd
require valid-user

Any idea as to what is causing the conflict, and how I can resolve it? Been working at it for hours. Your help is much appreciated.
Thank You
EDIT: found a solution!
Found a solution on a Joomla blog. I don't know how, but this works... LOL :)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (/|\.htm|\.php|\.html|#.*|\?.*|/[^.]*)$  [NC]
RewriteRule ^(.*) /index.php [L]
</IfModule>

A: You could try explicitly setting a conditional that the request URI not match the url for the mail script. That should prevent the rewrite from kicking in when you view the mail admin page.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !mail
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

A: I think there must be something else going on here that we can't see. That Wordpress .htaccess code already prevents rewriting URLs when what you are trying to access is a file or a directory that exists on the server, which should be true in this case.
Are there any other .htaccess files involved anywhere, or any plugins installed in Wordpress that involve rewrites? Also, does /mail/admin/ work when you remove your .htaccess file that requires a password?
You could try, say, creating blank text files inside the /mail/admin/ directory and in a completely new folder in the root directory, and see if you can access those without any problems - might narrow down where the problem is.


text:
Q: Python: Call function at fixed rate The function do_something should be called at fixed rate (e.g. 10 seconds).
I found links such as What is the best way to repeatedly execute a function every x seconds in Python or Executing periodic actions in Python. Unfortently those implementing gave the same resoluts like i would have had
time.sleep(10)

at the end of the while-loop, which is not the behavior i am seeking for.
Hier is an example output:
2015-01-01 13:00:00
2015-01-01 13:00:10
2015-01-01 13:00:21
2015-01-01 13:00:31
2015-01-01 13:00:42

where the wish behavior should have been:
2015-01-01 13:00:00
2015-01-01 13:00:10
2015-01-01 13:00:20
2015-01-01 13:00:30
2015-01-01 13:00:40

At present this is my solution:
import time
import datetime

def do_something():
    print(datetime.now())

period = 10

while True:
    do_something()
    t = time.time()
    time_to_sleep = period - ( t % period )
    time.sleep( time_to_sleep )

Unfortently with this method and my raspberry pi 3 I am unable to achive a stable timestamps at a fixed rate. Here is an output example:
2015-01-01 13:00:00
2015-01-01 13:00:10
2015-01-01 13:00:23
2015-01-01 13:00:33
2015-01-01 13:00:40

Any ideas?
PS
This is a small program.


text:
Q: How to make  xxx.one.com point to yyy.two.com I'm currently in need to have xxx.one.com point to yyy.two.com.
That means that when someone will enter xxx.one.com they'll actually see the content of yyy.two.com (URL in the browser won't change and will remain yyy.two.com).
The domains are hosted on separate hosting company. yyy.two.com is on a cPanel and xxx.one.com is on an unknown hosting plan, though I can get its details.
yyy.two.com have the same IP of www.two.com and this cannot be changed (as the hosting company told me).
Any ideas on how do I tackle this issue?

A: This is not the DNS issue, because you cannot change the DNS resource records by yourself.
HTTP/1.1 requires all requests to send Host: header, and modern HTTP servers will understand the header and choose the right object regarding the content of the Host: header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23 for the details.


text:
Q: Getting access to the non-static field of type array without creating instance of it's class while writing some simple game I realised I 've got some trouble to face. I have two separate classes: SettingPanel and Ship. The array of type Class Tile cannot be static because i need two different instances of class SettingPanel. So i need two diffrent arrays aswell.
public Class Ship
{
   public Ship()
   {
       SettingPanel.method(?????)
   }
}

public Class SettingPanel
{
   Tile [][] map = new Tile[10][10];
   public SettingPanel(){}
   public static boolean method(Tile[][])
}

How can i put the argument(??????) while trying to perform a static method but i do not have an instance of a class SettingPanel and i do not want to. SIngleton? GetComponent()? I need some correct code here. It drives me crazy because it's solution seems to be as easy as abc... Help !


text:
Q: Cross-referencing between tex-files I have a main TeX-file named Thesis.tex that contains this:
\documentclass[11pt, a4paper, oneside]{Thesis}
\begin{document}
\input{./Chapters/MethodologyAndResearchStrategy}
\input{./Chapters/CreationOfTheNovelDesignPrinciples}
\end{document}

Within the file named MethodologyAndResearchStrategy.tex - I have a section that looks like this:
\section{Quantitative Data Analysis}
\label{sec:QuanDat}
Quantitative data means data, or evidence, based on numbers.

Then I have a reference to it that looks like this within a file named CreationOfTheNovelDesignPrinciples.tex:
As mentioned in (Section~\ref{sec:QuanDat})

This then produces "Section ??", which means that it is not finding the label that I have made. I have already tried adding
\usepackage{xr}
\externaldocument{MethodologyAndResearchStrategy}

in the chapter that I want the reference in, but to no avail. I get an error saying that one can only use such code in the preamble. Putting it there in the main Thesis.tex did not yield any results either for that matter. This is my first post, so if you need any other data to be able to assist, just let me know!
EDIT: So I finally found the problem, and it had nothing to do with TeX at all. I had been editing the wrong version of CreationOfTheNovelDesignPrinciples.tex which was uploaded to Dropbox with an older version of the paper.


text:
Q: Counter-example to the existence of left Bousfield localization of combinatorial model category Is there any known example of a combinatorial model category $C$ together with a set of map $S$ such that the left Bousefield localization of $C$ at $S$ does not exists ?
It is well known to exists when $C$ is left proper, and it seems that it also always exists as a left semi-model structure, but I don't known if there is any concrete example where it is known to not be a Quillen model structure.
PS: I technically already asked this question a year ago but it was mixed with other related questions and this part was not answered, so I thought it was best to ask it again as a separate question.

A: While preparing the paper Left Bousfield localization without left properness, I learned another example, due to Voevodsky. It's example 3.48 in his paper Simplicial radditive functors. This is an example of a model category that's not left proper, and a left Bousfield localization that does not exist as a model category. It does, however, exist as a semi-model category, as I prove in my paper.

A: A surprisingly effective way to construct counterexamples in model category theory is to just write down all the objects and morphisms involved and try to give the resulting (finite!) diagram the structure of a model category.
Here, we know that a counterexample must fail to be left proper, so start with a diagram$\require{AMScd}$
$$
\begin{CD}
    a @>\sim>> b\\
    @VVV  @VVV\\
    c @>>> d
\end{CD}
$$
in which $a \to b$ is a weak equivalence, $a \to c$ is a cofibration, but $c \to d$ is not a weak equivalence. Then $a \to c$ also cannot be a weak equivalence (otherwise $b \to d$ would be one too). Since $a \to c$ and $c \to d$ are not weak equivalences, they must be both cofibrations and fibrations and therefore the same is true of $a \to d$. Then $a \to d$ cannot be a weak equivalence (or it would be an isomorphism), so $b \to d$ is also not a weak equivalence, and therefore is a fibration too. In summary, all the maps are fibrations and $a \to c$, $b \to d$, $c \to d$ are cofibrations while $a \to b$ is a weak equivalence. One can check that this does in fact yield a model category structure (probably the easiest way is to verify that the (acyclic) cofibrations/fibrations are closed under composition and pushout/pullback, and that the factorization axioms hold).
Now, let's try to form the left Bousfield localization at the map $a \to c$, which is already a cofibration between cofibrant objects. All objects are fibrant in the original structure, and the local objects are the ones which have the same maps from $a$ and from $c$, which are the objects $c$ and $d$. The map $c \to d$ was not a weak equivalence originally, so it has to still not be one in the localization. However, making $a \to c$ a weak equivalence also makes $b \to d$ a weak equivalence because it is the pushout of the acyclic cofibration $a \to c$, which contradicts two-out-of-three.


text:
Q: sed, to delete some numbers of lines after match sed can delete some numbers of lines after match with match
sed -e /regexp/,+<number_of_lines>

but how delete in addition to this yet 10th line for example
UPDATE
Well not really the exact question.
Need to delete second, third, fourth and 6th lines after match and match itself

A: If you have GNU sed you can do sed '/regexp/,+10d' file to delete the 10 lines after (and including) the match. You can do sed '/regexp/,+4d;10d' file to delete the 4 line after (and including) the match plus the 10th line.


text:
Q: Wave function as a section of a complex line bundle to do QM in polar coordinates If you want to change the coordinates of a Wave function $\Psi$ in 2D QM from cartesian to polar coordinates in a naive way one encounters a problem, namely the (naively defined) radial momentum operator $P_r$ is no longer self adjoint:
$$(\Phi,P_r\Psi)=\int r\Phi ^*(-i)\partial _r\Psi drd\theta\neq(P_r\Phi,\Psi)$$
According to this lecture https://www.youtube.com/watch?v=C93KzJ7-Es4&t=1630s one can address this issue by interpreting the wave function $\Psi$ no longer as a function $f_\Psi:\mathbb{R^2}→ \mathbb{C}$ but as a section $\Psi:\mathbb{R^2}→E$ on a $\mathbb{C}$-line bundle $E$ over $\mathbb{R^2}$. It is claimed that $E$ is also an associated fibre bundle to the frame bundle $L\mathbb{R^2}$ over $\mathbb{R^2}$ which can be equipped with a connection $\omega$. Then the argumentation goes, we can understand a section $\Psi$ of an associated $\mathbb{C}$-line bundle as a function $F_\Psi:L\mathbb{R^2}→\mathbb{C}$ and on such a function we have a covariant derivative $\text{D}F_\Psi(X)=\text{d}F_\Psi(X^{hor})$. Now we can pull this back with a local section $s:U→L\mathbb{R^2}$ to the base space $\mathbb{R^2}$ and get a definition of a covariant derivative for the pulled back function $s^*F_\Psi:U→\mathbb{C}$ which is equivalent to the section $\Psi$ in the open region $U$. With $T$ as a vector field on $\mathbb{R^2}$ the covariant derivative reads:
$$\nabla_Ts^*F_\Psi:=\text{D}s^*F_\Psi(T)=\text{d}s^*F_\Psi+s^*\omega(T)s^*F_\Psi $$
Now we can find a connection $\omega$ with which the momentum operator $P_r$ defined in terms of a covariant derivative is again a self adjoint operator.
Now my problem with the argumentation: The frame bundle $L\mathbb{R^2}$ is trivial as one can easily find a global section of it. Every associated vector bundle of a trivial principal bundle is trivial too. But if $E$ is trivial a section $\Psi$ can be understood as a function $f_\Psi:\mathbb{R^2}→\mathbb{C}$, which is the starting point again. The covariant derivative of such functions is $\nabla_Tf_\Psi=df_\Psi(T)$ so that we get again a momentum operator which is not self adjoint. Basically my question now is: What is wrong in my derivation of a covariant derivative for the section $\Psi$? Because I don't think both of the formulas are valid and we just choose the one which produces the correct momentum operator.


text:
Q: Show HTML bookmark link with space from top of the page First of all, I'm struggling how to title my question. I know it can be better.
So In my simple HTML page, I have 3 bookmarks which I link them by  tags:
HTML5

I have a fixed header at the top of the page and I've set margin-top to the sections, so that they appear under the header.
header {
    width: 100%;
    height: 200px;
    position: fixed;
    top: 0px;
}
section {
    padding: 20px;
    margin-right: 200px;
    margin-top: 200px;
}

Now the problem is, when I clicke on the bookmark links, HTML tries to scroll to them and show them at the top of the page, which then will be masked by the header.
My question is, is there any way to tell the  tag to show the bookmark using some margins, so that it appears under the header?
JSFiddle sample

A: Thanks to this answer, I fixed the issue

/* add class="jumptarget" to all targets. */

I changed the answer in my favor and it solved the problem like a charm.
.jumptarget::before {
  content:"";
  display:block;
  height:220px; /* fixed header height*/
  margin:-50px 0 0; /* negative fixed header height */
}


text:
Q: What to do for answers that come after an accepted answer and still have the same solution? On a few of my questions, I see newer answers come after an accepted answer and yet add nothing useful. I wonder why do they even post such answers. Maybe they want to get more reputation? So what can we do to such answers?

A: If they answer the question but add nothing, leave them be. If you think they answer the question and add something to the existing answers, upvote them. If you think they are poor answers and do not answer the question or answer the question inadequately, downvote them and add a comment.


text:
Q: Can't run apps on Ubuntu - PATH I'm trying to install apps on Ubuntu and I can, but I can't run them. I install them using "pip3 install appname".
When I try to run them, nothing happens.
Everytime I install a python app, I get the error:
It says "The script streamlink (app name) is installed in '/home/bob/.local/bin' which is not on PATH."
I've tried editing "/etc/environment" and inserting "/home/bob/.local/bin" but nothing happens. I still can't run my python app.
Note: this is a fresh Ubuntu install.


text:
Q: Ant not recognizing JUnit jar in its lib directory? I'm using Cygwin under Windows XP, and I'm trying to get Ant to use JUnit without coding any classpath entries for it. The doc for JUnit says I can:

Put both junit.jar and ant-junit.jar in ANT_HOME/lib.

My handy-dandy copy of JUnit in Action says:

You may have noticed that you don't explicitly add the JUnit JAR to the classpath. Remember that when you installed Ant, you copied the JUnit JAR file to the ${ANT_HOME}/lib directory in order to use the junit Ant task. Because junit.jar is already on your classpath, you don't need to specify it in the javac task to compile your tests.

$ANT_HOME is set to the Ant installation directory. In the lib subdirectory, I see ant-junit.jar (installed with Ant) and junit-4.9.jar (copied by me). Seems okay, right? But the test compile step fails:
[javac] Compiling 1 source file to E:\tools\ctg\bin\test
[javac] E:\tools\ctg\src\test\TestAll.java:3: package org.junit does not exist
[javac] import org.junit.*;

Et cetera. I tried renaming junit-4.9.jar to junit.jar. No joy. I peeked in the jar file and saw that the package does exist inside of it. In fact, the compiles work fine if I explicitly include that very jar file in the Ant classpath.
Bleh. Any thoughts about what might be wrong? Thanks.
EDIT: By request, here's the javac target:
<path id="classpath">
   <pathelement location="${app-bin}"/>
   <pathelement location="${test-bin}"/>
   <!--pathelement location="${junit-bin}"/-->
</path>

<target name="compile-test" depends="compile-app">
   <javac srcdir="${test-src}"
          destdir="${test-bin}"
          source="${java}"
          target="${java}"
          debug="on"
          includeantruntime="false">
      <compilerarg value="-Xlint"/>
      <classpath refid="classpath"/>
   </javac>
</target>

Note that the JUnit binary is commented out. My goal is to delete it and have the compile work.

A: includeantruntime="false" tells ant to not include the libs in the lib directory for the compile.
You have to add the jar to a classpath, which you will give to the javac target. Or set the property to true.

A: Try removing the version number from the junit jar file name.
i.e. rename junit-4.9.jar to junit.jar


text:
Q: Python/Django: Which authorize.net library should I use? I need authorize.net integration for subscription payments, likely using CIM. The requirements are simple - recurring monthly payments, with a few different price points. Customer credit card info will be stored a authorize.net .
There are quite a few libraries and code snippets around, I'm looking for recommendations as to which work best.

*

*Satchmo seems more than I need, and it looks like it's complex.

*Django-Bursar seems like what I need, but it's listed as alpha.

*The adroll/authorize library also looks pretty good.

*The CIM XML APIs don't look too bad, I could connect directly with them.

And there are quite a few other code snippets.
What's the best choice right now, given my fairly simple requirements?

A: Edit: https://github.com/agiliq/merchant/blob/master/billing/gateways/authorize_net_gateway.py
looks pretty nice, haven't tried it yet.
Edit: [For the next project I have that uses authorize.net, I'm going to take a close look at: http://github.com/zen4ever/django-authorizenet It looks pretty nice.  I don't think that it has support for recurring payments though.]
In the past I have made little one-off implementations.
For simple post to the AIM payment gateway, you can use something like this:
URL = 'https://test.authorize.net/gateway/transact.dll'
API = {'x_login':'XXX',
'x_tran_key':'XXX', 'x_method':'CC', 'x_type':'AUTH_ONLY',
'x_delim_data':'TRUE', 'x_duplicate_window':'10', 'x_delim_char':'|',
'x_relay_response':'FALSE', 'x_version':'3.1'}

def call_auth(amount, card_num, exp_date, card_code, zip_code, request_ip=None):
    '''Call authorize.net and get a result dict back'''
    import urllib2, urllib
    payment_post = API
    payment_post['x_amount'] = amount
    payment_post['x_card_num'] = card_num
    payment_post['x_exp_date'] = exp_date
    payment_post['x_card_code'] = card_code
    payment_post['x_zip'] = zip_code
    payment_request = urllib2.Request(URL, urllib.urlencode(payment_post))
    r = urllib2.urlopen(payment_request).read()
    return r

def call_capture(trans_id): # r.split('|')[6] we get back from the first call, trans_id
    capture_post = API
    capture_post['x_type'] = 'PRIOR_AUTH_CAPTURE'
    capture_post['x_trans_id'] = trans_id
    capture_request = urllib2.Request(URL, urllib.urlencode(capture_post))
    r = urllib2.urlopen(capture_request).read()
    return r

To authorize, you do something like:
            r = authorize.call_auth(
                unicode(decimal_total),
                request.POST.get('card_num'),
                request.POST.get('exp_date'),
                request.POST.get('card_code'),
                request.POST.get('zip_code') if request.POST.get('zip_code') else address.zip_code,
            )
            if r.split('|')[0] == '1':
              # it's good, we have authorized the card...
            else:
              error = "%s Please try again." % (r.split('|')[3])

then, we can capture:
        r = authorize.call_capture(trans_id) # r.split('|')[6] in first response..
        if r.split('|')[0] == '1':
            # we captured it.
        else:
            error = r.split('|')[3]

There are more options, ways to request, nuances in the response to parse... I assume b/c A in AIM stands for advanced that all of the authorize.net options are available.
http://developer.authorize.net/guides/AIM/
I know that your question is what lib is best .. well, it might be easiest just to implement your own little bit of ad-hoc request and response for your specific requirements rather than trying to trove through an api on top of an api.

A: There is always Paython: https://github.com/abunsen/Paython
Currently supports 5+ payment gateways:

*

*Authorize.net

*First Data/Linkpoint

*Innovative Gateway (from intuit)

*PlugnPay

*Stripe

Here is an example:
from paython import CreditCard, AuthorizeNet

set up a card first:
credit_card = CreditCard(
      number = '4111111111111111',
      exp_mo = '02',
      exp_yr = '2012',
      first_name = 'John',
      last_name = 'Doe',
      cvv = '911',
      strict = False
  )

check if its valid:
if not credit_card.is_valid(): return 'houston, we have a problem' # checks card number + expiration date

Set up customer data to charge, not all fields are required:
customer_data = dict(
      address='123 Main St',
      address2='Apt 1',
      city='Pleasantville',
      state='IA',
      zipcode='54321',
      country='US',
      phone='654-369-9589',
      email='john@localwoodshop.com',
      ip='127.0.0.1')

authorize against gateway, options include debug output or test credentials:
  api = AuthorizeNet(username='test', password='testpassword', debug=True, test=True)
  gateway_response = api.auth(amount='0.05', credit_card=credit_card, billing_info=customer_data, shipping_info=None)

now you can settle:
  api = AuthorizeNet(username='test', password='testpassword', debug=True, test=True)
  gateway_response = api.settle(amount='0.05', trans_id='2156729380')

A: I recently wrote this API for Python and Authorize.net after failing to find one that supported all of Authorize.net's functionality.
https://github.com/vcatalano/py-authorize

A: Long story short, none of the existing solutions met my needs. They were either unmaintained, uncommented, untested, or lacked saved cards. So of course I built my own solution and open-sourced it:
AuthorizeSauce: https://github.com/jeffschenck/authorizesauce
It handles basic transactions (the AIM API), saved cards (the CIM API), and recurring payments (the ARB API). It is fully documented and has a full test suite.
I expect the original poster has long since moved on, but if it can help anyone else avoid some of the pain of payment processing, I'd be overjoyed.

A: For what it's worth we ended up using the adroll authorize library. Both Paython and django-authorizenet look interesting, will be checking those out.

A: I realize this is a bit late, but hopefully it helps others.
I recently came across Py-Authorize which has some great documentation, compared to the other packages available. You can install it via:
pip install Py-Authorize

It seems to install a dependency (colondar) which when installed via pip is outdated so you can get the latest (at the time of this writing) by doing the following:
pip install git+git://github.com/Pylons/colander.git@1.0b1

The docs are here: http://vcatalano.github.io/py-authorize/index.html
Works great in my experience, however for the project I am using it on I only needed AuthCapture and not ARB or anything...give it a try.  Best package I've found so far.


text:
Q: Fetch phone number for Android, IOS and Windows Phone I am working on a Xamarin forms project and want to fetch user's phone number from device.
Please anyone can guide me how can I fetch phone number for  Android, IOS and Windows Phone
Please suggest if any nuget package or third party library is available.
Thanks in advance

A: Try this
TelephonyManager mTelephonyMgr;

   mTelephonyMgr = (TelephonyManager)GetSystemService(TelephonyService);

   var Number = mTelephonyMgr.Line1Number;

Source: Xamarin Forum
Make sure to add the ReadPhoneState permission in your manifest

A:
how can I fetch phone number for Android, IOS and Windows Phone.

For Windows Phone, you could get SIM MSISDN & IMSI number in Windows Phone Application. Please notice that you should manually edit your application Package.appxmanifest as follows:
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
    xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
    xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="uap mp rescap">

......

<Capabilities>
    <rescap:Capability Name="cellularDeviceIdentity" />
</Capabilities>

You could use MobileBroadbandModem class to get all CurrentDeviceInformation. For more you could refer this case reply. Note you could not use code where in above case reply directly. You need to create DependencyService for UWP project in your Xamarin.Forms library.
For IOS, the short answer is "no way". You have to ask the user to enter it manually. There are private APIs to access the user's phone number, but then Apple will reject your app.

A: There is already plugin available for the same, You can use ContactsPlugin for Fetch Contact Number in Xamarin Forms,
Please check below link for the same.
https://github.com/jamesmontemagno/ContactsPlugin
Thanks


text:
Q: Hide/show radio buttons stop working on save Here's my case: I'm developing a little widget, and I was looking for a way to hide/show different DIVs on selecting a set of radio buttons. I found the proper code and adjusted it to my needs. The only problem is that the hide/show feature stops working after clicking on save while configuring the widget :S
Here's the JS:
jQuery(document).ready(function($) {
    $(document).ready(function() {
        $('input[type="radio"]').click(function(){
            if($(this).attr("value")=="link_to_image"){
                $(".radio-option").hide();
                $(".linked-image").show();
            }
            if($(this).attr("value")=="link_to_page"){
                $(".radio-option").hide();
                $(".linked-page").show();
            }
        });
    });
});

And the HTML:

    Link:

        <input type="radio" name="link_to" value="link_to_image">
        Link to image

        <input type="radio" name="link_to" value="link_to_page">
        Link to page

    Linked image:

        Content for linked_image DIV

    Linked page:

        Content for linked_page DIV

And the [JSFiddle] (http://jsfiddle.net/ccwsy5z4/)
Could you give me a hand with this, guys?

A: So finally I found out that the problem was that the JS stopped working after the AJAX started by clicking on the Save button.
And the solution for that was to recall the JS function after AJAX finished it job. To do that first I had to give a name to the JS function, called it after that, and then call it again after AJAX stopped. Like this:
jQuery(document).ready(function($) {

    function radioButtonShow() {

        if($(this).attr("value")=="link_to_image") {
            $(".radio-option").hide();
            $(".linked-image").show();
        }

        if($(this).attr("value")=="link_to_page") {
            $(".radio-option").hide();
            $(".linked-page").show();
        }

    };

    $('input[type="radio"]').click(radioButtonShow);

    $(document).ajaxStop(function() {

        $('input[type="radio"]').click(radioButtonShow);

    });

});

Hope this may be useful to somebody :)


text:
Q: the generated function of pulling a ball from a bin of balls with size that it is disturbuted by NP(2,p) let's say that I got a bin of balls, which its size is distributed negative binomially: NP(2,p). And let's say that each of the balls is numbered from 1 to x-1.
What is the generated function of Y: the number of the ball I will have after pulling one random ball from the bin. what's its expected value and varience?
Thanks.

A: I am assuming $X\sim NB(2,p)$ is the number of balls in the bin and then $Y$ is uniformly picked from the set $\{1,\ldots,X-1\}$ (which are the labels of the balls). Since this selection does not make sense if $X<2$, I am assuming that the convention for the negative binomial distribution $NB(r,p)$ is that its support starts at $r$.
Note from the density of $X$ that $$\mathbb{P}(X-1=k)=\binom{k}{k-1}(1-p)^2p^{k-1}=k(1-p)^2p^{k-1},\quad k\in\{1,2,\ldots\}.$$
Then you may compute, for $t<\log(1/p)$ (so that $pe^t<1$),
$$\begin{split}\mathbb{E}(e^{tY})
&=\sum_{k=1}^\infty \mathbb{E}(e^{tY}|X-1=k)\mathbb{P}(X-1=k)\\
&=\sum_{k=1}^\infty \sum_{n=1}^k e^{tn}\mathbb{P}(Y=n|X-1=k)\mathbb{P}(X-1=k)\\
&=\sum_{k=1}^\infty \sum_{n=1}^k e^{tn}\cdot \frac{1}{k}\cdot k(1-p)^2p^{k-1}\\
&=(1-p)^2\sum_{k=1}^\infty p^{k-1}\sum_{n=1}^k e^{tn}
=(1-p)^2\sum_{k=1}^\infty p^{k-1}\frac{e^{t(k+1)}-e^t}{e^t-1}.
\end{split}$$
Here we get two geometric series:
$$\begin{split}
\sum_{k=1}^\infty p^{k-1}e^{t(k+1)}=e^{2t}\sum_{k=1}^\infty (pe^t)^{k-1}&= \frac{e^{2t}}{1-pe^t},\\
\sum_{k=1}^\infty p^{k-1}&= \frac{1}{1-p}.
\end{split}$$
Therefore you finally get, for $t<\log(1/p)$,
$$\mathbb{E}(e^{tY})
=\frac{(1-p)^2}{e^t-1}\sum_{k=1}^\infty p^{k-1}(e^{t(k+1)}-e^t)
=\frac{(1-p)^2}{e^t-1}\left(\frac{e^{2t}}{1-pe^t}-\frac{e^t}{1-p}\right).
$$


text:
Q: On-device single-word voice recognition Does needing just a single word voice recognition reduce the complexity of the task enough to be able to fully perform voice recognition processing offline, on an iOS or Android smartphone? (E.g., could a reasonably accurate counter for the number of times that a single, pre-programmed word was spoken while the microphone is active be developed to work offline on a standard iOS or Android smartphone?).
I've found plenty of tools and examples capturing voice and sending it to an online service (e.g., the Google cloud voice-to-text), but does the single-word focus reduce the complexity enough for the recognition to be doable offline today? If so, do you have any libraries to suggest or where would you start?

A: Cloud services are good for various reasons relating to your question:

*

*It makes deployment of new versions of the algorithm (which happen much more frequently than most people realize) a lot easier

*It allows the developer to collect your data and use it in future algorithm development (or whatever they please)

*From a practical standpoint, most deployed models (at least the effective ones) can be quite large and take up quite a bit of space on a mobile device.

In addition to the above, I don't think that the singular word focus changes much, if anything. The model has to not just account for words, but also for the different ways those words can be said (volume, tone, accents, inflection, etc, etc).
So what you are asking can be done but there's also good reasons why it's on the cloud.


text: Q: Compare 2 values on 2 different webpages using RFT How can I compare values based on another page, either using data pool values or get values from another page, in Rational Functional Tester  using java?


text:
Q: Generalization of the Gelfand-Mazur theorem: A $\mathbb C$-algebra that is also a division ring The Gelfand-Mazur theorem states that if $\mathscr A$ is a $\mathbb C$-Banach algebra that is also a division ring, then $\mathscr A=\mathbb C$.

Proof. If $a$ is an element, then the spectrum of $a$ is nonempty. If $\lambda$ is in its spectrum, then $a-\lambda$ has no inverse. But by definition of division ring $a-\lambda=0$.

This proof clearly utilizes the norm since it is an application of the spectral theory.
However, what if $\mathscr A$ is just a $\mathbb C$-algebra that is also a division ring? Do we have this result or some other classification?

My attempt: If $\mathscr A$ is a $\mathbb C$ algebra, then $\mathscr A$ is also a $\mathbb R$ algebra. By Corollary IX.6.8(Frobenius) of Hunderford's Algebra, an (thanks to the comments, finite dimensional) division algebra over the field $\mathbb R$ of real numbers is isomorphic to one of $\mathbb R$, $\mathbb C$ and the division algebra of real quaternions. But $\mathbb R$ and $\mathbb H$ don't seem to be $\mathbb C$-algebras.

A: To summarize the comments:

*

*Frobenius' Theorem only applies to finite dimensional algebras. If $\mathscr A$ is a finite dimensional division algebra over $\mathbb C$, $\mathscr A\cong \mathbb C$ by arguments in the question.

*For infinite dimensional algebras, this no longer hold. In fact, $\mathbb C(x)$ is a division algebra over $\mathbb C$ that is not isomorphic to $\mathbb C$.

*This survey discusses some notable generalizations of the Gelfand-Mazur theorem. In particular, the following hold:

Theorem 1 (Real Version). Every real normed division algebra is isomorphic to the set of all real numbers $\mathbb R$, the complex numbers $\mathbb C$ or the quaternions $\mathbb H$.

Theorem 2 (Complex Version). Every complex normed division algebra is isometrically isomorphic to $\mathbb  C$.

Here a normed algebra is just a algebra with a norm (not necessarily complete) such that $\|a\cdot b\|\le\|a\|\|b\|$.


text:
Q: Delete key from configmap in Kubernetes Is there a nice way to delete a specific key from a Kubernetes configmap, using kubectl?
Right now I run:
$ kubectl edit configmap myconfigmap

and then I delete the entry but I would like a solution that can be run as a script.

A: This works but I wonder if there is a simpler way
$ kubectl patch configmap myconfigmap --type=json -p='[{"op": "remove", "path": "/data/mykey"}]'


text:
Q: Filter specific message value in logstash i am new to logstash.
I am trying to parse log value and applying filter on value using grok.
The log data is -
{"log":"11:20:15|INFO|config-app: Starting_thread\n","stream":"stdout","time":"2022-12-19T11:19:15.089894627Z"}
The logstash.conf is-
input {
   beats {
        port =>  5045
        host => "0.0.0.0"
    }
}
filter {
  json {
    source => "message"
    add_field => {
        "log1" => "%{log}"
    }
  }
  grok {
     match => { "%{log1}" => ['(%{TIME:time}\|%{LOGLEVEL:logLevel}\|%{USER:microservice_name}(:) %{GREEDYDATA:logMessage}'] }
  }
}
output {
    elasticsearch {
     hosts => "elasticsearch:9200"
     user => elastic
     password => yourstrongpasswordhere
     index => "pj"
     }
   stdout {}
}

Tried running the above file but pipeline is not creating in logstash.


text:
Q: installing MongoDB to Mac I need help to solve an error that happened while installing MongoDB into Macbook.
I run this command to kick off installing.
brew install mongosh

ALthough I got a warning msg, it seemed like fine.

I waited so long, and the installation got finally done.
Here is the screenshot of the end.

As you can see, I typed below to check if it was successfully installed.
mongosh --version
1.2.2

Finally I tried to run MongoDB, so typed "mongosh". And I got an error to run it and connect to db called cluster0.
mongosh
Current Mongosh Log ID: 621d2adedeee61396fddb367
Connecting to:      mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
takeichimasahironoMacBook-Air:~ masa$ mongosh "mongodb+srv://cluster0.8tjjn.mongodb.net/myFirstDatabase" --apiVersion 1 --username mongo
Enter password: *****
Current Mongosh Log ID: 621d2b0f5a5370a82628edcc
Connecting to:      mongodb+srv://cluster0.8tjjn.mongodb.net/myFirstDatabase?appName=mongosh+1.2.2
MongoServerSelectionError: read ECONNRESET

Any idea to solve this issue?? Thanks for your effort in advance.

A: In addition to the good answer above -- On newer versions mac os x the root directory is read only so you will need place your mongo data directory somewhere else, see this thread:
Read-only file system when attempting mkdir /data/db on Mac
I also needed to separately install the mongo command line tool from the cask:
$ brew install mongodb-community-shell

A: I recommend Homebrew for installing and managing applications on macOS. It is installed using the following command in the macOS terminal. Open up the terminal and paste the command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

The terminal runs through a series of installation operations, and will probably create folders in your local machine to accommodate Homebrews storage requirements. You can find more detailed instructions here. After it's installed, update the Homebrew dependencies and install MongoDB on the command line:
brew update
brew tap mongodb/brew
brew install mongodb-community

It will take a few seconds. Once it's done, create a directory so MongoDB can store its data.
sudo mkdir -p /data/db

Now to make sure this data directory have the right permissions, you'll run this command:
sudo chown -R `id -un` /data/db

Now our data directory is ready with the right permissions. Next run mongo daemon. Which is a service which runs in the background and listens for connections on a given port. Run this command:
mongod

Now mongo daemon will be running in the background and can be used by your applications. Next, check your MongoDB version:
mongo --version
MongoDB shell version v4.2.6

The command-line results will show the version you have installed on your local machine. I recommend using the latest version of libraries and software whenever possible to avoid compatibility issues with client-side applications.


text:
Q: There is no $0$ neighbourhood in the infinite product of topological vector spaces with $X_i \neq \{0\}$ Assume $(X_i,\mathcal{T}_i)$, $i \in I$ is a family of topological vector spaces and $X:=\prod\limits_{i\in I} X_i$ with the product topology $\mathcal{T}$. $I$ is infinite and for all $i\in I: X_i\neq \{0\}$.
I want to prove that there is no bounded neighbourhood of $0$ in $(X, \mathcal{T})$.
My idea so far was to prove this statement indirectly and assume there is a neighbourhood $U$ which is bounded, i.e. for all 0 neighbourhoods $V$ there is a scalar $\lambda$ such that $U\subset \lambda V$.
Further I know that $V = \prod\limits_{i\in I}U_i$ with $U_i=X_i$ for almost all $i \in I$. Hence there are $i_1,...,i_m \in I$ such that $V = \bigcap\limits_{j=1}^m \pi_{i_j}^{-1}(U_{i_j})$.
Can someone give me a hin how to proceed or lead me to the right direction?

A: You cannot assume that $V$ is of this form, because those open sets are only a basis for the product topology. $V$ is an union of open sets of this form.
Anyway I think this is no need to make a proof by contradiction : take $U$ a neighborhood of $0$ in the product, then it contains an open set of the basis $\prod_{i\in I}U_i$, which itself contains $0$, and with $U_i=X_i$ for all but a finite number of $i$. Then, there is some $i_0\in I$ such that $U_{i_0}=X_{i_0}$ because the collection is not finite. Now, take $B_0$ an open neighborhood of $0$ in $X_{i_0}$ which is different from $X_{i_0}$, this is possible because $X_{i_0}\neq 0$. Then, form $V=\prod_{i\in I}V_i$ where $V_i=X_i$ except for $i=i_0$, where we take $V_{i_0}=B_0$. Then, $V$ is an open neighborhood of $0$ in the product, and for $\lambda>0$ we have that $p_{i_0}(\lambda V)=\lambda B_0$, while $p_{i_0}(U)=X_{i_0}$, where $p_{i_0}$ is the projection on the $i_0$-th coordinate. So, this is not possible that $U\subset \lambda V$.


text:
Q: UIKeyboardDidHideNotification error application crashing I'm using a UIView. The application is using ARC. UIView is used in multiple view controllers. In UIView a listener to the UIKeyboardDidHideNotification is added. The listener works fine with some view controllers and with other view controllers it crashes the application. Especially when I use in the second view contoller after using in the first. The error is

* -[appname keyboardWillHide]: message sent to deallocated instance 0xb9c2760

In some scenarios the listener is getting called twice.
The code i have added in the uiview drawrect method is:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];

the code for listener is
-(void)keyboardWillHide
{
    if(boolisViewlifted)
    {

            CGRect newFrame=self.frame;
            newFrame=CGRectMake(self.frame.origin.x, self.frame.origin.y+250, self.frame.size.width, self.frame.size.height);
            self.frame=newFrame;
            boolisViewlifted=false;

    }
}

The uiview appears on top of the calling view controller. Please let me know what causes this error and how to solve it.

A: Your view is getting unloaded because of memory warnings. You need to override dealloc method & remove observer for all notifications in all views where you added observer for notifications.
//do add in all views
-(void)dealloc
{
     //[super dealloc];//As you are using ARC don't call super's dealloc
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}


text:
Q: fckeditor does not show the textarea I am doing admin panel for my project, but the textarea, edited with FCKEDITOR doesn't show.
I get the following source:
<input type="hidden" id="text" name="text" value="here shows the text itself....." style="display:none" />
<input type="hidden" id="text___Config" value="" style="display:none" />

A: Integrate FCKEditor
Step 1
The first thing to do is to include the "JavaScript Integration Module" scripts inside the  of your page, just like this:

Step 2
Now the FCKeditor class is available and ready to use. There are three ways to create an FCKeditor in your page:
Method 1
The inline method (preferred): Go to the body of your page, to the place you want the editor to be (usually inside a form) and place the following script there:

Method 2
The TEXTAREA replacement method:
In  add the "onload" method:

In  add the below code to replace an existing TEXTAREA in the page:
<textarea id="MyTextarea" name="MyTextarea">This is the initial value.</textarea>

Method 3
The CreateHtml() method (for AJAX): For an AJAX application, you'll be setting the inner html dynamically; for example:
var div = document.getElementById("myFCKeditor");
var fck = new FCKeditor("myFCKeditor");
div.innerHTML = fck.CreateHtml();

Sample code
Sample code 1

<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">

<form>

</form>

Sample code 2

<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">

<textarea id="MyTextarea" name="MyTextarea">This is the initial value.</textarea>

Source site


text:
Q: Does the interior angle for an optimized 2-field solution remain constant when going through N dimensions? This problem has been bugging me for literally a decade. I don't quite have the chops to solve it on my own.
Let's start with the basic, 2-dimensional problem.
You have 100 meters of fencing. You need to enclose two equal areas. What's the greatest area you can enclose?
The trick is to realize that two squares aren't the answer, and the "simple" answer is a circle with a line through it. However, it turns out the "Best" answer is actually two partial circles fused together, creating a goggle-like effect. The interior angle for the part of the circle that's going to the fused middle line instead of circling around is 120 degrees.
The math (It's been awhile, and I can't quite remember all of it)
$$P = 2*R(Angle in Radians)+(R^2+R^2-2R^2Cos(Angle))$$
The perimeter of a partial circle, times 2, plus the length of the side, determined with the law of cosines. Formula isn't collapsed more to preserve the logic/ease of viewing.
$$A= 2*(Area of two circles - area of a slice of circle + area of a triangle slice)$$
$$A= 2*(pi*R^2 - Angle/2*R^2 + area of a triangle slice)$$
When solving for 3 dimensions, you get 120 degrees again - two spheres fused with a circular plane between them.
I've tried, and failed, quite a few times to generalize this solution into N-dimensions. I'm aware this is entirely impractical, but it's been driving me nuts for over 10 years at this point, and I'd love some help on it.

A: This is the (restricted case of) famous "Double Bubble" Conjecture (DBC). (The restricted case because you assume equality of the two volumes.) It is now a theorem in all dimensions, see Theorem 1.1 in:
Ben W. Reichardt, Proof of the Double Bubble Conjecture in $R^n$, Journal of Geometric Analysis, 18 (2008) 172–191.
The linked wikipedia article will tell you more about its history.
The  DBC is usually stated so that the enclosed volume is fixed and the hypersurface area is to be minimized, but this is equivalent to your formulation when you fix the area and maximize the volume.


text:
Q: Last symbol is duplicated in LZW I tried implementing LZW encoding/decoding and ended up with the following code
#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>

using Index = std::int16_t;

void encode(std::istream &input, std::ostream &output) {
  Index index{0};
  std::unordered_map<std::string, Index> dictionary{};

  for (int i = 0; i < 256; ++i) {
    dictionary[{static_cast<char>(i & 0xFF)}] = index++;
  }

  char k;
  input.read(&k, sizeof(char));
  std::string buffer{""};
  while (input) {
    const auto tmp = buffer + k;
    if (dictionary.contains(tmp))
      buffer = tmp;
    else {
      dictionary[tmp] = index++;
      output.write(reinterpret_cast<const char *>(&dictionary[buffer]),
                   sizeof(Index));
      buffer = {k};
    }
    input.read(&k, sizeof(char));
  }
  output.write(reinterpret_cast<const char *>(&dictionary[buffer]),
               sizeof(Index));
}

void decode(std::istream &input, std::ostream &output) {
  Index index{0};
  std::unordered_map<Index, std::string> dictionary{};

  for (int i = 0; i < 256; ++i) {
    dictionary[index++] = {static_cast<char>(i & 0xFF)};
  }

  Index k;
  input.read(reinterpret_cast<char *>(&k), sizeof(Index));
  output << dictionary[k];

  Index old{k};
  std::string buffer;
  while (input) {
    input.read(reinterpret_cast<char *>(&k), sizeof(Index));
    buffer = dictionary[old];

    std::string tmp;
    if (dictionary.contains(k)) {
      const auto &entry = dictionary[k];
      tmp = buffer + entry.front();
      output << entry;
    } else {
      tmp = buffer + buffer.front();
      output << tmp;
    }
    dictionary[index++] = tmp;
    old = k;
  }
}

It kinda works but the last character after decoding is duplicated:
int main() {
  std::string input{"hello world!"};
  std::istringstream iss{input};
  std::stringstream ss{};
  encode(iss, ss);
  decode(ss, std::cout);
}

Outputs hello world!! instead of hello world!. I can't find my mistake, maybe someone else can?

A: As @NathanOliver pointed out in the comments
changing the decode loop to
while (input.read(reinterpret_cast<char *>(&k), sizeof(Index))) {

fixes it.


text:
Q: Why can't I apply a rule of inference within an argument expression? This question tells me I cannot apply inference rules to subexpressions. But why can't I? Do I run the risk of making an incorrect inference?

A: In the linked question, suppose you apply the rule of simplification $$\begin{align}
&q \land r \\
&\overline{\therefore r}
\end{align}$$
To simplify $p \rightarrow (q \land r)$ to $p\rightarrow r$.  Obviously from $p\rightarrow r$ and $\lnot q$ we cannot deduce $\lnot p$ ($p$ and $r$ may be true and $q$ false,) so we erroneously conclude that the theorem is false.

A: Yes, applying a rule of inference to a subexpression indeed runs the risk of making an invalid inference.
Example. Suppose you use $\land$ Elim to do:
$$(P \land Q) \to R$$
$$\therefore P \to R$$
Well, that is invalid. With $P$ True and $Q$ and $R$ both false, you have that $(P \land Q) \to R$ is True, but $P \to R$ is False.


text:
Q: Expectation of Brownian function. $(W_t)t≥0$ be a standard one-dimensional Brownian motion
Let $f : R → R$ be a given function and $0 ≤ s ≤ t$. Write down an
expression for $E(f(W_t)|W_s = x)$ in terms of $ϕ(x) = Φ′(x)$
Where $Φ(x)$ denotes the cumulative distribution function of a standard normal random variable
So what I did but I think it is wrong:
$E(f(W_t)|W_s = x) = E(f(W_t - W_s + W_s)|W_s = x)$
$E(f(W_t - W_s + x))$
$E(f(W_t - W_s + x))$
$E(f(\frac{(W_t - W_s)(t-s)^{0.5}}{(t-s)^{0.5}} + x))$
I'm really not sure from here I tried normalizing it but I'm not sure

A: Since $\operatorname{Corr}(W_t,W_s)=\sqrt{s/t}$,
$$
W_t\mid W_s=x\sim N(x,t-s).
$$
Thus,
$$
\mathsf{E}[f(W_t)\mid W_s=x]=\int_{-\infty}^{\infty} \frac{f(w)}{\sqrt{t-s}}\phi\!\left(\frac{w-x}{\sqrt{t-s}}\right)\, dw.
$$


text:
Q: installation and disk partition When I tried to install Ubuntu 12.10 on my laptop some questions were asked regarding drives(i think so). What do they mean?
ntfs
/dev/sda/
/dev/sda1/
/

A: You'll need to give more information to get a better answer.
You need to identify what you're trying to do. Are you installing Ubuntu alongside of Windows or other operating systems? If so, your objective is slightly more difficult. If you're just trying to replace your whole hard drive with Ubuntu, then you're on the easy track.
/dev/sda is usually the device file of the main hard drive on your computer.
Your disk can have one or more partitions. /dev/sda1 is the first partition on your hard drive. You're most likely going to want to install the root of your Ubuntu installation on /dev/sda1 if you're using the whole hard drive for Ubuntu. Otherwise you'll want to partition your drive up and install Ubuntu on a different partition.
ntfs is a type of filesystem often used by Windows.
Please give more information regarding your question or it will be marked as too vague.


text:
Q: Non-constant Linear Boolean Function How can we prove that any non-constant linear Boolean function is balanced ? I know that any non-constant affine function is balanced. But i cannot expend this for Boolean function.

A: if you can prove that any non constant affine function is balanced.then you have proved that any non-constant linear Boolean function is balanced.
beacuse linear functions are aspecial cae of affine functions where a0=0.


text:
Q: Changing the frequency via "set_rx_freq()" is causing ERROR_CODE_TIMEOUT in the metadata of the recv() command I am setting up a USRP to record at 400MHz and receiving data correctly.  I then set up the USRP to record at 400MHz + an 18kHz offset and I get TIMEOUT errors on the recv() command.
I am setting the new frequency using the same code as the prior frequency thus that is the only thing changing in this example.
Is there some clean up or a hold time longer that 2 seconds or so that has to be done to get to a new frequency?
When the interface class is constructed we initialize using the following lines
  uhd::set_thread_priority_safe();

  // Setup device addresses and create object
  uhd::device_addr_t devAddr;
  devAddr["addr0"] = "192.168.10.2";
  devAddr["addr1"] = "192.168.20.2";
  devAddr["addr2"] = "192.168.30.2";

  m_usrp = uhd::usrp::multi_usrp::make(devAddr);

  uhd::usrp::subdev_spec_t rxSpec("A:0");
  m_usrp->set_rx_subdev_spec(rxSpec);

  m_usrp->set_clock_source("external");
  m_usrp->set_time_source("external");
  m_usrp->set_rx_rate(m_sampleRate);  //Sample rate is 500000

We prepare for a particular data capture with the following lines.  The set and gets match up with a bit of difference in the decimal points.
  uhd::stream_args_t streamArgs("fc32");
  for (size_t chan = 0; chan < m_usrp->get_rx_num_channels(); chan++)
  {
    streamArgs.channels.push_back(chan);
  }

  m_rxStreamer = m_usrp->get_rx_stream(streamArgs);

  m_usrp->set_rx_gain(m_gainChannel1, 0); // All gains set to 31.5
  m_usrp->set_rx_gain(m_gainChannel2, 1);
  m_usrp->set_rx_gain(m_gainChannel3, 2);

  uhd::time_spec_t cmdTime = m_usrp->get_time_now() + uhd::time_spec_t(1.0);
  m_usrp->set_command_time(cmdTime);
  m_usrp->set_rx_freq(m_freqChannel1 - CENTER_FREQ_OFFSET_HZ, 0); // Freq is 400000000 and CENTER_FREQ is 100000
  m_usrp->set_rx_freq(m_freqChannel2 - CENTER_FREQ_OFFSET_HZ, 1);
  m_usrp->set_rx_freq(m_freqChannel3 - CENTER_FREQ_OFFSET_HZ, 2);
  m_usrp->clear_command_time();

  sleep(1);

  double actualChannel0Freq = m_usrp->get_rx_freq(0);
  double actualChannel1Freq = m_usrp->get_rx_freq(1);
  double actualChannel2Freq = m_usrp->get_rx_freq(2);

  LOG(INFO) << "Acutal tuned USRP frequencies " << std::fixed << actualChannel0Freq << " " << actualChannel1Freq << " " << actualChannel2Freq;

When it is time when the start to get the data out using:
      uhd::rx_metadata_t md;
      double timeout = 5.0;

        size_t samplesRxThisTime = m_rxStreamer->recv(buffPtrs, sampsThisTime, md, timeout);

        // Smaller timeout for subsequent packets
        timeout = 0.75;

        // Handle any error codes
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT)
        {
          LOG(ERROR) << "Timed out while receiving data from USRPs";
          break;
        }

I had expected that changing the frequency by a small bit wouldn't cause issues.  The original frequency works... the updated frequency doesn't.

A: The type of device you are might matter. It looks like a network interface to the device. Is this an N3xx?
I have seen issues similar to this with the B210 where a large frequency change can cause extra delays. In that case, a large frequency re-tune requires re-calibration which is fairly time-consuming.
If you update this with the type of device, someone might be better able to help you. In the meantime you might look into what happens in the RF frontend when you request a re-tune.


text:
Q: Selecting multiple sub bands in Google Earth engine I'm currently stuck on selecting multiple subbands from a source. Essentially I would like to only select the "Corn" - 1 and "Cotton" - 2 from the "cropland" band from the USDA Crop data layer.
Selecting 1 crop in the eq() function works perfectly, but once I add additional crops I get an error.
CDL = ee.ImageCollection("USDA/NASS/CDL")

# Crop Mask selection

cropland = CDL.filterDate('2019-01-01').select('cropland').map(lambda image: image.clip(county))

cropMask = cropland.map(
lambda img: img.updateMask(img.select(['cropland']).eq([1,2]))
)

cropMask = cropMask.toBands()


text:
Q: Im attempting to change every 4th or 5th line in notepad++ eg If I have this In a large file of script:
DELAY 10000
STRING 1234
DELAY 16000
ENTER
ENTER
STRING 0000
DELAY 16000
ENTER
ENTER
I wish to remove one enter and replace with DELAY,any help much appreciated.

A: Search/Replace
Find What: ENTER\r\nENTER
Replace with: ENTER\nDELAY
Search mode Extended (\n, \r, \t, \0, \x...)

result was
DELAY 10000
STRING 1234
DELAY 16000
ENTER
DELAY
STRING 0000
DELAY 16000
ENTER
DELAY


text:
Q: Question about center of dihedral group I need suggestions for this exercise.
Let $D_{2n}$ stand for the dihedral group of $2n$ elements.

*

*Show that if $n$ is odd and $\forall b \in D_{2n} (ab = ba)$, then $a = e$.

*Show that if $n$ is even, then there is $a\in D_{2n}$ such that $\forall b \in D_{2n} (ab = ba)$ and $a \neq e$.

My ideas: The elements in $G$ can separated into two disjoint sets: $Q=\{a\in G : a^2\neq e\}$ and $G\setminus Q$. If $a\in Q$, then $a\neq a^{-1}$ and this implies that $a$ is not of order 2.
Also, any suggestions of introductory books on abstract algebra are welcome.


text:
Q: Birationality inherited by map between joining lines Let $X^r, Y^s \subset \mathbb{P}^{n}$ be two disjoint subvarieties over $k= \mathbb{C}$ of dimensions $r,s < n-1$ living in complementary linear subspaces $\mathbb{P}^{m}$ and $\mathbb{P}^{n-m-1}$ of $\mathbb{P}^{n}$.
Consider the projection $\pi_{L}: \mathbb{P}^{n} \dashrightarrow \mathbb{P}^{n-k-1}$ from an $k$-plane $L \subset \mathbb{P}^{n}$. It is known that if $V^d \subset \mathbb{P}^{n}$ is an arbitrary subvariety of dimension $k$ disjoint from $L$, then the general fiber of restriction of the projection $\pi_{L}$ to $V$ is finite.
(indeed: if a general fiber $\pi_{L,V}^{-1}(p)= \pi_L^{-1}(p) \cap V$ of $\pi_{L,V}: V \to \mathbb{P}^{n-k-1}$ has dimensionion grater then zero, then it would have a non-trivial intersection with the $k$-plane $\Lambda$, which is a hyperplane in the $k+1$ dimensional linear space $\pi_L^{-1}(p)$. That's a contradiction since this would mean that $V$ and $\Lambda$ intersect, a conradiction to the assumption on $V$)
Moreover, if the dimension $k$ of the projection plane $L$ is $\le n-d-2$, then one can show that the projection $\pi_{L,V}: V \to \mathbb{P}^{n-k-1}$ is birational onto its image, so generically one-to-one.
Let's turn back to $X^r, Y^s \subset \mathbb{P}^{n}$ and consider the variety $V = X \cup Y $ inside $\mathbb{P}^{n}$. Let $0 \le k \le n-\min \{r,s \} -2$ a natural number. We project $V $ as before from a general $k$-plane $L$, which is by dimensionality and generality assumption disjoint from $X$ and $Y$. By previous general arguments the projection $\pi_{L,V}: V \to \mathbb{P}^{n-k-1}$ is birational and so generically one-to-one.
Then the image $\overline{V} =\pi_{L,V}(V) \subset \mathbb{P}^{n-k-1}$ is due to properness of $\pi_{L}$ again a subvariety in $\mathbb{P}^{n-k-1}$. More precisely if we introduce notations $\overline{X} =\pi_{L,V}(X)$ and $\overline{Y} =\pi_{L,V}(Y)$,  then we can write $\overline{V} = \overline{X} \cup \overline{Y}$. Assume in addition that $\overline{X} $ and $\overline{Y} $ are dijoint too, and therefore it make sense to talk about joining lines between points from $\overline{X}$ and $\overline{Y} $.
This leads to the central question if the birationality of $\pi_{L,V}$ is inherited by induced map on  "joining lines" between $X$ and $Y$? The later means that I consider the set of lines $\overline{x \ y}$ for $x \in X, y \in Y$, is then the induced map
$$ ConnLin: \{ \text{ Connecting Lines between } X \text{ and } Y \} \to \{ \text{ Connecting Lines between } \overline{X} \text{ and } \overline{Y} \},
 \\ \overline{x \ y} \mapsto \overline{\pi_{L,V}(x) \ \pi_{L,V}(y)} $$
is "generally" one-to-one. Here by generically I mean that there exist open subsets $X_0 \subset X, Y_0 \subset Y$ such that the map $ ConnLin $ restricted to set of lines $ \overline{x \ y}$ with $x \in X_0, y \in Y_0$ is one to one on level of sets.
Of course with a little more effort one can endow the set lines
joining $X$ to $Y$ with structure of a subvariety sitting in the Grassmannian of lines in $\mathbb{P}^n$ respectively $\mathbb{P}^{n-k-1}$ and interpret $ ConnLin$ as the induced map between them. But I don't see the neccessarity to go so far.
So my question is basically about the existence of the open subsets $X_0 \subset X, Y_0 \subset Y$ I described above. Or in simple terms I want to know that if $\pi_{L,V}$ is birational, then for any general joining line $\overline{\overline{x} \ \overline{y}}$ between $\overline{x} \in \overline{X}, \overline{y} \in \overline{y}$ the only joining line $\overline{x \ y} , \ x \in X, y \in Y$ with $\overline{\overline{x} \ \overline{y}} = \overline{\pi_{L,V}(x) \ \pi_{L,V}(y)} $ is that one with $x \in \pi_{L,V}^{-1}(\overline{x})$ and $y \in \pi_{L,V}^{-1}(\overline{y})$.
The question could be also reformulated to the question if the preimage under $\pi_{L,V}$ in $V = X \cup Y$ of a general line $\overline{\overline{x} \ \overline{y}}$ joining two points $\overline{x} \in \overline{X}, \overline{y} \in \overline{y}$ has cardinality two, one point in the fiber of $\overline{x}$ and the other in the fiber of $\overline{y}$. But that's the same as to ask if a general line connecting a point from  $\overline{X} $ to a point  from $\overline{Y}$ not intersects with other points from $\overline{X} \cup \overline{Y}$?


text:
Q: Setting expiry time for a collection in mongodb using mongoose Below is the command that can be used via the mongo terminal to set an expiry time for collections (a TTL):
db.log.events.ensureIndex( { "status": 1 }, { expireAfterSeconds: 3600 } )

How do I do this from my code in Node.js using mongoose?

A: this code is working for me.
may it help
let currentSchema = mongoose.Schema({
    id: String,
    name: String,
    packageId: Number,
    age: Number
}, {timestamps: true});

currentSchema.index({createdAt: 1},{expireAfterSeconds: 3600});

A: If you are working with Mongodb Atlas Replica Sets - try:
import * as mongoose from 'mongoose';

let currentSchema = new mongoose.Schema({
        createdAt: { type: Date, expires: 10000, default: Date.now },
        id: String,
        name: String,
        packageId: Number,
        age: Number
        });

currentSchema.index({"lastModifiedDate": 1 },{ expireAfterSeconds: 10000 });

A: Providing a string to expires also works nicely with Mongoose if you do not want to deal with the expire time calculation and improve the overall readability of the schema.
For example here we are setting the expires to 2m (2 minutes) and mongoose would convert to 120 seconds for us:
var TestSchema = new mongoose.Schema({
  name: String,
  createdAt: { type: Date, expires: '2m', default: Date.now }
});

Mongoose would create an index in the background and auto set the expireAfterSeconds to in this case 120 seconds (specified by the 2m).
It is important to note that the TTL process runs once every 60 seconds so it is not perfectly on time always.

A: new Scehma({
    expireAt: {
      type: Date,
      expires: 11,
      default: Date.now
  }
)}

This is the solution that worked for me according to this in the current Mongoose docs.

A: In Mongoose, you create a TTL index on a Date field via the expires property in the schema definition of that field:
// expire docs 3600 seconds after createdAt
new Schema({ createdAt: { type: Date, expires: 3600 }});

Note that:

*

*MongoDB's data expiration task runs once a minute, so an expired doc might persist up to a minute past its expiration.

*This feature requires MongoDB 2.2 or later.

*It's up to you to set createdAt to the current time when creating docs, or add a default to do it for you as suggested here.

*

*{ createdAt: { type: Date, expires: 3600, default: Date.now }}

A: There is a npm library - 'mongoose-ttl'.:
var schema = new Schema({..});
schema.plugin(ttl, { ttl: 5000 });

you can see all the options of this library:
https://www.npmjs.com/package/mongoose-ttl

A: const Schema = new mongoose.Schema({id: {
type: Number},
createdAt: {
type: Date, expires: '4h', index: true,
default: Date.now}});

You need to add index: true while creating you schema

A: 9/2022 Working Solution using Mongoose 6.5.4
None of the answers here worked for me, but I was able to finally get it working using the latest version of Mongoose currently available, 6.5.4.
Say our Schema looks like this:
const MySchema = new mongoose.Schema({
  id: { type: Number },
  myCustomTTLField: { type: Date }
});

myCustomTTLField is the field you want to index and have control the expiration. To achieve this, we add the following under our schema definition:
MySchema.path('myCustomTTLField').index({ expires: 60 });

The argument in MySchema.path is the name of the field you want to index for TTL. The expires option should be the number of seconds that will elapse from the Date represented in myCustomTTLField before the document is deleted. In the example above, the document will be deleted 60 seconds after whatever date is saved in myCustomTTLField. The full example:
const MySchema = new mongoose.Schema({
  id: { type: Number },
  myCustomTTLField: { type: Date }
});
MySchema.path('myCustomTTLField').index({ expires: 60 });

Please let me know if this works for you, I hope this helps. Mongoose TTL has been a thorn in my side for a long time, as their docs are notoriously tough to navigate. I found this solution via a small example buried in the docs here.
IMPORTANT NOTE:
TTL is not guaranteed to happen at exactly the time specified by your date + expiration seconds. This is due to how MongoDB's background delete process works. It runs every 60 seconds, so you may theoretically wait up to 60 seconds past expected TTL before seeing your document deleted. More info on that from the MongoDB docs.

A: FWIW I could only get the expires feature to work on a field called expiresAt. Here's my interface, and schema for implementing this in Typescript.
import { model, Schema, Types } from 'mongoose';

export interface ISession {
  sessionId: string;
  userId: Types.ObjectId;
  role: string;
  expiresAt?: Date;
}

const sessionSchema = new Schema<ISession>({
  sessionId: { type: String, required: true, indexes: { unique: true} },
  userId: { type: Schema.Types.ObjectId, required: true, ref: 'users'},
  role: { type: String, required: true, enum: [ 'ADMIN', 'BASIC_USER' ]},
  expiresAt: { type: Date, expires: '1h', default: Date.now }
}, { versionKey: false });

Reading the Mongoose documentation it seems like all the other proposed solutions should work too. I don't know why they were not for me. You can read the official Mongoose docs on expiresAt here.


text:
Q: jQuery plugin problems I am having problems with making my webpage responsive. I am using a plugin called jquery-momentum-scroll. But when I give specific height for a specific resolution (using @media), it does not instantly respond to my given resolution.
For example, if I resize my browser window, it shows the previous given responsive resolution that I set for different resolution. But, after a refresh on the browser, it takes the given property and works fine. After, including the plugin this problem occurred.
I have tried this in all other browsers it gives same result.
Can anyone help me fix this?

A: Did you try with! !important?
You can override the height by using !important. Just try it,  I hope it will be OK.


text:
Q: When is n small enough to abstain from having a global test set? This question relates to model selection and validation. This post laid out three strategies on how to deal with very small n. In conclusion (option 3), one might resign using a global test set, but use every instance for training. The use of cross validation still allows to get average performance indicators on the validation folds (for the sake of this question: regardless if single or nested). Is there any (scientifically) safe rule on when one might abstain from having a global test set?
The question is based on these two discussions:
No need of global testing set with small n
Possibilities to deal with small n, w/o global test set

A: I think if you look carefully you will find your answer in the posts that you have linked. The case of global test set is the best case scenario often referred to as three-way-split which is recommended for large datasets. However, for smaller datasets, this isn't feasible and you can revert to the k-fold cross-validation. But taking care about following issues:

*

*Use different k-fold cross-validation for model selection, i.e., optimizing the parameters and determining the generalization capability of the model. First optimize model parameters with one round of cross-validation and second determine their generalization capability.

*Since number of samples are small, try repeating k-fold cross-validation with different random splits which helps eliminate variance.
This two methods above have been scientifically accepted across literature, especially repeated cross validation: The relevant literature is Beleites, C. & Salzer, R.: Assessing and improving the stability of chemometric models in small sample size situations, Anal Bioanal Chem, 390, 1261-1271 (2008). http://link.springer.com/article/10.1007%2Fs00216-007-1818-6
Caution
However, these procedures as you have hinted may not produce best results and there are considerable issues when reporting k-fold CV results as detailed here:Cross-validation misuse (reporting performance for the best hyperparameter value)


text:
Q: Здравствуйте. Мне нужно сделать одно задание, но я не могу понять, как это сделать
Задание следующее: Путем перестановки элементов квадратной вещественной матрицы добиться того, чтобы ее максимальный элемент находился в левом верхнем углу (1,1), следующий по величине – в позиции (2, 2), следующий по величине – в позиции (3, 3) и т. д., заполнив, таким образом, всю главную диагональ. Найти номер первой из строк, не содержащих ни одного положительного элемента.
Ища решение и объяснение этого задания в интернете, я мало практически ничего не понял. Есть только начальный код с двумерным массивом.
Вот код:

<?
  $i = $_POST["i"];
  $j = $_POST["j"];

// Генерация массива
  for ($ii = 0; $ii < $i; $ii++){
    for ($jj = 0; $jj < $j; $jj++){
        $a[$ii][$jj] = rand(-100, 100);
    }
  }

?>

 <meta charset="utf-8">

<?

  print "
Sgenerirovanniy massiv iz ".$i * $j." elementov
";
  print "
";

  // Печать индексов индексов столбцов
  print "
	";
  for ($jj = 0; $jj < $j; $jj++){
    print "".$jj."	";
  }
  print "
";

  // Печать элементов
  for ($ii = 0; $ii < $i; $ii++){
    print "
".$ii."	";
    for ($jj = 0; $jj < $j; $jj++){
        if ($ii == $jj){
            print "".$a[$ii][$jj]."	";
        }
        else{
            print "".$a[$ii][$jj]."	";
        }

    }
    print "
";
  }

  //print "
";
  print "
";

?>

A: Сейчас всё поймёте:
Обходите весь массив, ищете максимум, запоминаете его позицию. После обхода всей матрицы меняете элемент [0][0] c элементом в запомненной позиции
Снова обходите массив, пропуская элемент [0][0], находите позицию максимума, меняете с элементом  [1][1]
Снова обходите массив, пропуская элементы [0][0] и [1][1], находите позицию максимума, меняете с элементом  [2][2]
Повторяете это дело n (размер матрицы) раз


text:
Q: How to manage memory using Spring Boot Maven Plugin with Kubernetes I'm using spring boot 2.5.6 and I'm generating the docker image with the spring boot maven plugin.
I'm deploying the application using AWS EKS with nodes managed by fargate.
The plugin configuration is the following
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <excludes>
            <exclude>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </exclude>
        </excludes>
    </configuration>
</plugin>

The command I use to execute it is the following
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=my-image-name

When the application is deployed on AWS EKS, the application print the following data
Setting Active Processor Count to 2
Adding $JAVA_OPTS to $JAVA_TOOL_OPTIONS
Calculated JVM Memory Configuration:
    -XX:MaxDirectMemorySize=10M
    -Xmx408405K
    -XX:MaxMetaspaceSize=128170K
    -XX:ReservedCodeCacheSize=240M
    -Xss1M
    (Total Memory: 1G, Thread Count: 250, Loaded Class Count: 20215, Headroom: 0%)
Enabling Java Native Memory Tracking
Adding 128 container CA certificates to JVM truststore
Spring Cloud Bindings Enabled
Picked up JAVA_TOOL_OPTIONS:
    -Djava.security.properties=/layers/paketo-buildpacks_bellsoft-liberica/java-security-properties/java-security.properties
    -XX:+ExitOnOutOfMemoryError
    -XX:ActiveProcessorCount=2
    -XX:+HeapDumpOnOutOfMemoryError
    -XX:HeapDumpPath="/var/log/containers/heapDump.hprof"
    -XX:MaxDirectMemorySize=10M
    -Xmx408405K
    -XX:MaxMetaspaceSize=128170K
    -XX:ReservedCodeCacheSize=240M
    -Xss1M
    -XX:+UnlockDiagnosticVMOptions
    -XX:NativeMemoryTracking=summary
    -XX:+PrintNMTStatistics
    -Dorg.springframework.cloud.bindings.boot.enable=true

If I go inside the container and I run the command "free -h" I get the following output
total mem  : 7.7G
used mem   : 730M
free mem   : 4.6G
shared     : 820K
buff/cache : 2.4G
available

Why the -Xmx is filled with 400Mb only? And why the total memory is only 1Gb?

A: Posting this out of comments for better visibility.

An important thing to mention is when free command is run inside a pod's container, it shows all available memory on the node where this pod is scheduled and running.
At this point it's very important to have memory resources and limits for java applications since JVM memory allocation can be set incorrectly if it happens by the application.

There are two main options for resource allocation (in this particular case is memory):

*

*requests (spec.containers[].resources.requests.memory) - kubernetes scheduler has to find a node which has requested amount of memory, not less than specified.
It's very important to set the requests reasonably since it's used for scheduling and there are chances that kubernetes scheduler won't be able to find a sufficient node with enough free memory to schedule the pod - good example of incorrect requests

*limits (spec.containers[].resources.limits.memory) - kubelet insures that pod will not consume more than specified in limits, since containers in pod are allowed to consume more than requested.
It's also important to have limits set up for predictable resource consumption since containers can exceed requested memory and consume all node's memory until OOM killer is involved. Possible cases when limits are not set