text:
Q: Probability of two people meeting given that one arrivas at a specifc time I was just wondering if someone could maybe check my logic of working this question out. As a disclaimer I realise that there is questions of similar nature on the forum but, I have not looked due then if I see how it been worked out it doesn't help me if there fault in my logic.
Question:

Bob and Jane agree to meet at a known location between 2pm and 3pm.  The problem is that neither of them know what time the other will arrive.
We may assume that both of them are equally likely to arrive at any time between 1pm and 2pm.
However Bob is prepared to wait 10 minutes for Jane to arrive before leaving. And Jane is prepared to wait only 5 minutes for  Bob  to  arrive  before  she  leave.
a) If Bob arrived at 1 pm what would be the probability that they meet?
b)If Bob arrived at 1.05 pm, what would be the probability that they meet?
c) If Bob arrived at 1.30 pm, what would be the probability that they meet
d) Draw a sketch of the probability of meeting as a function of Bob arrival time where the arrival time is the time elapsed in hours from 1pm.

So for part a) my thinking is this. If Bob arrives at 1pm then for them to meet, Jane could arrive at the following times my assumption is that it on the minute and not the second from looking at other  questions.
Jane can arrive at: {1,1:01,1:02........1:10}pm so then the probability of them metting is $P=\frac{10}{60}=\frac{1}{6}$
for b) Jane can arrive at : {12:55,12:56........12:59} and {1,1:01......1:10} so the probability of them meeting is $P=\frac{15}{60}=\frac{1}{4}$
for c) because Jane could arrive at {1:25....1:29} and {1:30......1:40} so the probability of them meeting is $P=\frac{15}{60}=\frac{1}{4}$
for d) I remember reading in a old text book which iv lost at the moment that this is can be solved geometric probability and I think the diagram I am looking for is a line of y=x-10 where $x\geq0$ as this would included all possibilities from the seconds.

A: I'll assume the agreement was to meet between 1 and 2 pm, not 2 and 3, because otherwise the rest of the question makes no sense.
I think the usual idea is not to assume Jane arrives only on at one of the on-the-minute times, because the arithmetic for on-the-minute times is more complicated than if you assume that Jane might arrive at any time during the interval, giving an infinite number of possibilities for what time she might arrive.
Notice that if only on-the-minute times are possible, then there are $61$ possible times to arrive, not $60$. That is, one can arrive at $0, 1, 2, 3, \ldots, 58, 59,$ or $60$ minutes past the hour.
There are $61$ numbers in that list: the sixty numbers
$1, 2, 3, \ldots, 59,$ and $60$, and the number $0.$
Similarly, there are $11$ numbers, not $10,$ in the list of numbers $0, 1, \ldots, 10.$ So if you let Jane arrive at 1:00, 1:01, 1:02, 1:03, 1:04, 1:05, 1:06, 1:07, 1:08, 1:09, or 1:10, she has $11$ possible arrival times. (Count them!)
Working only in whole minutes, therefore, the answer to part a) is $\frac{11}{61}.$
Or maybe it's $\frac{10}{61},$ because if Jane arrives at 1:10 then Bob is already leaving by a different path and doesn't see her.
But if we allow Jane to arrive at any time between 1 and 2 pm, with a uniform continuous probability distribution, then she has a $\frac{1}{60}$ chance to arrive between 1:00 and 1:01 and $\frac{10}{60}$ chance to arrive between 1:00 and 1:10. While it is possible  for her to arrive at 1:10 exactly, the probability of that exact time is zero, so whether Bob is still waiting or already leaving at that exact instant makes no difference.
The continuous-distribution assumption also helps in part d), because when we graph Bob's arrival times at every point along one axis and Jane's arrival times at every point along the other axis, not just at the $61$ whole-minute times,
the graph of the set of events in which they successfully meet is a polygon whose area we can easily compute. If we dealt only in whole-minute times then we'd have to count the individual lattice points, for which we can also derive formulas but not ones quite as simple. For example, the area of a right triangle with legs $n$ and $n$ is $\frac12 n^2,$ but it has $\frac12(n^2 + n)$ lattice points (if $n$ is an integer).
In short, under your assumptions, your answer for part a) is incorrect, but if you make the same assumptions that I would, your answer is correct.
For part b), you say Jane might arrive at 12:56 (among other times), but that is not correct: it is assumed that Jane arrives between 1 and 2 pm, and 12:56 is not between 1 and 2 pm.
On the other hand, even if Jane is later than 1:10, as long as she arrives by 1:15 Bob will still be waiting.
You did not consider that possibility, but when you do consider it then the probability of meeting becomes $\frac14.$ So again you have the same answer I would give, but the wrong reasons for it.
For part c) you have the right range of times, but miscounted them: there are $16$ distinct whole-minute times from 1:25 to 1:40 inclusive.
And again if you allow Jane to arrive at any time in that interval the formula is simplified and your result turns out to be correct.
For part d), the line $y = x - 10$ is useful if $x$ is Jane's arrival time in minutes (and possibly fractions thereof) after 1 pm and $y$ is Bob's arrival time.
That line separates the "good" events from the events where $y < x - 10,$
in which Bob arrives more than $10$ minutes before Jane and therefore leaves before she arrives.
Another line to look at is the one that separates the "good" events from the ones where Bob arrives more than 5 minutes after Jane and she has already left.


text:
Q: rpyc connection closed by peer I'm following rpyc tutorials on this page but get EOFError when run this code
bgsrv = rpyc.BgServingThread(conn) #creates a bg thread to process incoming events

I've searched a lot but didn't find a way to fix this issue.
The server and client run in same machine. I'm running the script on macbook pro.
Need help in fixing this error.
You can find the source code of stream.py here.
Here is the traceback:
Exception in thread Thread-10:
Traceback (most recent call last):
  File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
File "/Library/Python/2.7/site-packages/rpyc-3.3.0-py2.7.egg/rpyc/utils/helpers.py", line 204, in _bg_server
    self._conn.serve(self.SERVE_INTERVAL)
File "/Library/Python/2.7/site-packages/rpyc-3.3.0-py2.7.egg/rpyc/core/protocol.py", line 387, in serve
    data = self._recv(timeout, wait_for_lock = True)
File "/Library/Python/2.7/site-packages/rpyc-3.3.0-py2.7.egg/rpyc/core/protocol.py", line 345, in _recv
    data = self._channel.recv()
File "/Library/Python/2.7/site-packages/rpyc-3.3.0-py2.7.egg/rpyc/core/channel.py", line 50, in recv
    header = self.stream.read(self.FRAME_HEADER.size)
File "/Library/Python/2.7/site-packages/rpyc-3.3.0-py2.7.egg/rpyc/core/stream.py", line 195, in read
    raise EOFError("connection closed by peer")
EOFError: connection closed by peer

redpajama_set_name: RedPajamaStackExchange


text:
Q: linker command failed with exit code 1 (use -v to see invocation) in React-natibve-branch with the error "framework not found React" using pods for only react-native-branch got this error :
Directory not found for option '-F/Users/.../Library/Developer/Xcode/DerivedData/...../Build/Products/Debug-iphoneos/React'
but with manual installation, it gives the error in


text:
Q: How to use regex beginning marker (^) in a kotlin regex statement How do I check whether a string contains and starts with a given regex in Kotlin?
I was expecting that I could just do:
fun main(args: Array<String>) {
    var text = "test string"
    val regex = Regex.fromLiteral("^test")
    val matches: Boolean = text.contains(regex)
    assert(matches)
}

But this does not work. It works as expected without the ^. Even doing matches or find, or the Regex operators like containsMatchIn don't seem to work.
Am I missing something obvious? Perhaps I can't use the beginning boundary, or I shouldn't be using it.
Note: I am aware of startsWith but that doesn't allow me to use a regex. I am wanting to use a regex as my code has more complex strings than just "test string".

A: The Regex.fromLiteral("^test") results in a \^test regex that matches ^test substring iterally. Check Regex.fromLiteral() documenation:

Returns a literal regex for the specified literal string.

You just need to make a regex out of the string literal, use
val regex = """^test""".toRegex()

See the Kotlin demo.


text:
Q: Managing high-volume writes to SQL Server database I have a web service that is used to manage files on a filesystem that are also tracked in a Microsoft SQL Server database. We have a .NET system service that watches for files that are added using the FileSystemWatcher class. When a file-added callback comes from FileSystemWatcher, metadata about the file is added to our database, and it works fairly well.
I've now come to a bit of a scalability problem. I'm adding large quantities of files to the filesystem in rapid succession, and this ends up hammering the database with file adds which results in locking up my web front-end.
I have yet to work on database scability issues, so I'm trying to come up with mitigate tactics. I was thinking of perhaps caching file adds and only writing them off to the database every five minutes or so, but I'm not sure how practical that is. This is data that needs to find its way into our database at some point anyway, and so it's going to have to get hammered at some point. Maybe I could limit the number of file db entries written per second to a certain amount, but then I risk having that amount be less than the rate at which files are added. How can I best tackle this?

A: Have you thought about using something like SQL Server Service Broker? That way you could push through tons of entries in a burst and it would level out the inserts into your database.
Basically you'd be pushing messages onto a queue which would then be consumed by a receiver stored procedure that would perform the insert for you. You could limit the maximum number of receivers executing to help with the responsiveness issues in your web interface.
There's a nice intro paper here. Although it's for 2005, not much has changed between 2005 and the newer versions of SQL Server.

A: You have a performance problem and you should approach it with a performance investigation methodology like Waits and Queues. Once you identify the actual problem, we can discuss solutions.
This is just a guess but, assuming the notification 'update metadata' code is a stright forward insert, the likely problem is that you're generating one transaction per notification. This results in commit flush waits, see Diagnosing Transaction Log Performance . Batch commit (aggregate multiple notifications before committing) is the canonical solution.

A: first option is using Caching to handle high-volume data. or using clusters for analysis high volume data. please click here for more information.


text:
Q: Java Spark withColumn algebra by example Spark (spark-core_2.13:3.3.2) and Java 11 here (very important, I need Java solutions please, not Scala!).
I am reading an Excel spreadsheet into a Dataset like so:
public void runSpark(MyDataJob dataJob, JavaSparkContext sparkContext) {

    SparkSession session = SparkSession.builder().sparkContext(sparkContext.sc()).getOrCreate();

    Dataset<Row> dataset = session.read()
        .format("com.crealytics.spark.excel")
        .option("dataAddress", "'My Sheet'!B3:C35")
        .option("header", "true")
        .option("treatEmptyValuesAsNulls", "true")
        .option("setErrorCellsToFallbackValues", "true")
        .option("usePlainNumberFormat", "false")
        .option("inferSchema", "true")
        .option("addColorColumns", "true")
        .option("timestampFormat", "MM-dd-yyyy HH:mm:ss")
        .option("maxRowsInMemory", 100)
        .option("maxByteArraySize", 2147483647)
        .option("tempFileThreshold", 10000000)
        .option("excerptSize", 10)
        .load(dataJob.getFileName());

    dataset.withColumn("CountDiff", ???);

}

The spreadsheet has 2 columns in it, NumFizz and NumBuzz, and hence, I'm guessing the Dataset has these columns as well. I need to add a new column that is the difference of these values in each row, meaning if a row's NumFizz value is 17, and its NumBuzz is 10, then its value in the new column should be 7. Unfortunately, since literally all the withColumn examples appear to be in Scala, I can't figure out how to do this in Java. I am also open to using Spark SQL if there's a simple solution using that as well. I just need a new CountDiff column added to my Dataset that has the difference of these two columns.
Can anyone nudge me in the right direction?
I tried to import the col functions and pass them in as args but the lack of viable Java examples is blocking me from making headway.

A: How about this:
dataset.withColumn("CountDiff", dataset.col("Numfizz").minus(dataset.col("Numbuzz")));

The Column.minus docs show examples of both Scala and Java usage, where scala applies it's magic operator conversion, and Java needs explicit function calls:
// Scala: The following selects the difference between people's height and their weight.
people.select( people("height") - people("weight") )

// Java:
people.select( people.col("height").minus(people.col("weight")) );

alternatively use SQL
You can also use SQL to perform express all the transformations you need:
dataset.createOrReplaceTempView("my_sheet")

session.sql("
SELECT
*,
Numfizz - Numbuzz as CountDiff,
... -- other calculations you may need
FROM my_sheet
").show();

When working with SQL you will may find the docs for SQL functions available in spark useful.


text:
Q: surjective group Homomorphism from $A_5$ to $A _4$
Is there a  surjective group  homomorphism from  $f :\mathbb{A_5} \rightarrow \mathbb{A _4} ?$

My attempt : i know that there is  no  surjective group  homomorphism from  $f :\mathbb{S_5} \rightarrow \mathbb{S _4} $ because $A_5$ is the  only  normal subgroup  after $n \ge 5$.
Here im confused  about   $A_5$ and $A_4$

A: Nope, such morphism would have a  nontrivial kernel but $A_5$ is simple.


text:
Q: how to scrape json api in scrapy I am trying to scrape an API using scrapy. i have tried various ways and couldnt do it but i have succefully returned the api as json in anaconda ! but cant seems to figure out how to parse it !
json code looks like this :
[
{
  "id": "6975526564553428229",
  "secretID": "6975526564553428229",
  "text": "I did a thing  Pre-order link in my bio!! #WillTheBook",
  "createTime": 1624116353,
  "authorMeta": {
  "id": "6727327145951183878",
  "secUid": "MS4wLjABAAAA8ezUaW4ecJX222ObGXxt07F9BIh4QH3-g1P1DHyChT2LLi2cn-vAE2R53-
  H672ZO",
  "name": "willsmith",
  "nickName": "Will Smith",
  "verified": true,
  "signature": "Same kid from West Philly.",
  "avatar": "https://p16-sign-va.tiktokcdn.com/musically-maliva-
  obj/1646315618666501~c5_1080x1080.jpeg?x-expires=1624215600&x-
  signature=JWCnkyJ1Lq7G6K3W32nSB4NKc%2Fk%3D",
  "following": 24,
  "fans": 55900000,
  "heart": 340900000,
  "video": 81,
  "digg": 88
  },

what i did is after looking into some tutorials is :
# -*- coding: utf-8 -*-
import requests
import scrapy
import json
from pprint import pprint
from ..items import TiktokscrapyItem
from scrapy.crawler import CrawlerProcess
from datetime import datetime

def send_request():
   response = requests.get(
       url="https://app.scrapingbee.com/api/v1/store/tiktok/user-feed",
       params={
        "api_key": "api key hiudden",
        "username": "willsmith",
    },

)
print('Response HTTP Status Code: ', response.status_code)
print('Response HTTP Response Body: ', response.content)
send_request()

class tiktokSpider(scrapy.Spider):
   name = 'tiktok'
   allowed_domains = ['app.scrapingbee.com']
   custom_settings = {'CONCURRENT_REQUESTS_PER_DOMAIN': 10}
   custom_settings = {'FEEDS':{'poststoday.csv':{'format':'csv'}}}

def parse(self, response):
     authorMeta = json.loads(response.body_as_unicode())
     print(authorMeta)

     #main driver
if __name__ == "__main__":
   process = CrawlerProcess()
   process.crawl(tiktokSpider)
   process.start()

dont know what to do i am trying to scrape only the text and createtime and nickname :/ but cant figure it out! any tips?


text:
Q: What is the correct way of saving values into a constant in mongoose? I have a user model and I have used timestamps in it. I need to access the createdAt date and save it in a variable. I tried
const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

But this is returning
[ { createdAt: 2021-09-23T10:47:24.400Z } ]

However the only thing that i want to be saved inside my date constant is
2021-09-23T10:47:24.400Z

that also as a Date()

A: You are getting an array because find() returns all matches.
Get the property from the first object. Use it with the Date() constructor to get your required value as date.
Try this:
const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

let finalDate = new Date(date[0].createdAt);
console.log(finalDate);

A: Use findOne, it returns one document. documentation of findOne : https://mongoosejs.com/docs/api.html#model_Model.findOne
const date = await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();

    console.log(date.createdAt)

or
const {createdAt :  date}= await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();

    console.log(date)

const {createdAt :  date} = { createdAt: '2021-09-23T10:47:24.400Z' }
console.log(date)
let fromDate = new Date(date);
console.log(fromDate.getDate())

Also look here : https://docs.mongodb.com/manual/reference/method/Date/#return-date-as-date-object


text:
Q: toggle menu with one menu open at a time in pure javascript I want to make menu toggle and one item from menu is open at a time. I am able to open one item at a time but unable to do toggle at the same time.

var navclick = document.getElementsByClassName("js-dropdown");
var navContent = document.getElementsByClassName('-arrow-link-content');
for (var i = 0; i < navclick.length; i++) {
    navclick[i].onclick = function () {
      if (this.parentNode.querySelector('div.-arrow-link-content').classList.contains('nav-active')) {
        this.parentNode.querySelector('div.-arrow-link-content').classList.remove('nav-active');
      }
      else {
        this.parentNode.querySelector('div.-arrow-link-content').classList.add('nav-active');
      }
    }
  }
.-arrow-link-content {
  display:none;
}
.nav-active{ display:block;}

heading 1

 Content 1

heading 2

 Content 2

if anyone have any suggestions.. please share.. Thanks in advance

A: For toggle to work, we need to get all the node with class name -arrow-link-content, and then remove the nav-active class first, then add nav-active to the selected item.
Check the snippet.

var navclick = document.getElementsByClassName("js-dropdown");
var navContent = document.getElementsByClassName('-arrow-link-content');
for (var i = 0; i < navclick.length; i++) {
  navclick[i].onclick = function() {
    if (this.parentNode.querySelector('div.-arrow-link-content').classList.contains('nav-active')) {
      this.parentNode.querySelector('div.-arrow-link-content').classList.remove('nav-active');
      return false
    }

    var el = document.querySelectorAll('div.-arrow-link-content');
    for (var i = 0; i < el.length; i++) {
      if (el[i].classList.contains('nav-active')) el[i].classList.remove('nav-active');
    }
    this.parentNode.querySelector('div.-arrow-link-content').classList.add('nav-active');

  }
}
.-arrow-link-content {
  display: none;
}

.nav-active {
  display: block;
}

heading 1

 Content 1

heading 2

 Content 2

A: Since at most one element can be open at a time, we just have to look for that one elment and close it first if it exists, before we open an unopened element

var navclick = document.getElementsByClassName("js-dropdown");
var navContent = document.getElementsByClassName('-arrow-link-content');
for (var i = 0; i < navclick.length; i++) {
    navclick[i].onclick = function () {
      if (this.parentNode.querySelector('div.-arrow-link-content').classList.contains('nav-active')) {
        this.parentNode.querySelector('div.-arrow-link-content').classList.remove('nav-active');
      }
      else {
        try {
          // if an open element exists, close it first
          this.parentNode.parentNode.querySelector('.nav-active').classList.remove('nav-active');
         }
          catch (error){
            // Error occurs when no open elment exists, in that case: Do nothing
          }
        this.parentNode.querySelector('div.-arrow-link-content').classList.add('nav-active');
      }
    }
  }

.-arrow-link-content {
  display:none;
}
.nav-active{ display:block;}

heading 1

 Content 1

heading 2

 Content 2


text:
Q: Aggregation on Pandas data frame for selected rows I have a pandas sorted data frame (based on time) like this:
from datetime import datetime
df = pd.DataFrame({ 'ActivityDateTime' : [datetime(2016,5,13,6,14),datetime(2016,5,13,6,16),
                                 datetime(2016,5,13,6,20),datetime(2016,5,13,6,27),datetime(2016,5,13,6,31),
                                 datetime(2016,5,13,6,32),
                                datetime(2016,5,13,17,34),datetime(2016,5,13,17,36),
                                 datetime(2016,5,13,17,38),datetime(2016,5,13,17,45),datetime(2016,5,13,17,47),
                                datetime(2016,5,16,13,3),datetime(2016,5,16,13,6),
                                 datetime(2016,5,16,13,10),datetime(2016,5,16,13,14),datetime(2016,5,16,13,16)],
              'Value1' : [0.0,2.0,3.0,4.0,0.0,0.0,0.0,7.0,8.0,4.0,0.0,0.0,3.0,9.0,1.0,0.0],
               'Value2' : [0.0,2.0,3.0,4.0,0.0,0.0,0.0,7.0,8.0,4.0,0.0,0.0,3.0,9.0,1.0,0.0]
        })

Which turns out like this:
ActivityDateTime    Value1  Value2
0   2016-05-13 06:14:00 0.0 0.0
1   2016-05-13 06:16:00 2.0 2.0
2   2016-05-13 06:20:00 3.0 3.0
3   2016-05-13 06:27:00 4.0 4.0
4   2016-05-13 06:31:00 0.0 0.0
5   2016-05-13 06:32:00 0.0 0.0
6   2016-05-13 17:34:00 0.0 0.0
7   2016-05-13 17:36:00 7.0 7.0
8   2016-05-13 17:38:00 8.0 8.0
9   2016-05-13 17:45:00 4.0 4.0
10  2016-05-13 17:47:00 0.0 0.0
11  2016-05-16 13:03:00 0.0 0.0
12  2016-05-16 13:06:00 3.0 3.0
13  2016-05-16 13:10:00 9.0 9.0
14  2016-05-16 13:14:00 1.0 1.0
15  2016-05-16 13:16:00 0.0 0.0

I'd like to aggregate the data (averaging) without a for loop. However, the way I am going to group the observations is not straight forward! Looking at Value1, I want to group them as non-zero values together. For example, indicies 1,2,3 would be in one group. Incidies 7,8,9 in one group and another one would be 12,13,14. The rows where value1==0, should be avoided and the zeros just act as a separation between groups. Eventually I'd like to get something like this:
Activity_end    Activity_start  Value1  Value2  num_observations
0   2016-05-13 06:27:00 2016-05-13 06:16:00 4.50    4.50    3
1   2016-05-13 17:45:00 2016-05-13 17:36:00 6.33    6.33    3
2   2016-05-16 13:14:00 2016-05-16 13:06:00 4.33    4.33    3

Currently, I am thinking that I should somehow assign numbers 1,2 and 3 to a new column and then aggregate them based on that. I am not sure how to make that column without a for loop though! Please notice that Value1 and Value2 are not necessarily the same.

A: One way of doing it involves creating some temporary columns
# First create a new series, which is true whenever the value changes from a zero value to a non-zero value (which will be at the start of each group)
nonzero = (df['Value1'] > 0) & (df['Value1'].shift(1) == 0)
# Take a cumulative sum. This means each group will have it's own number.
df['group'] = df['nonzero'].cumsum()
# Group by the group column
gb = df[df['Value1'] > 0].groupby('group')

You can then take aggregates of this group using the aggregate functions http://pandas.pydata.org/pandas-docs/stable/groupby.html
For what you're specifically wanting to get as an output, have a look at this answer too: Python Pandas: Multiple aggregations of the same column
df2 = gb.agg({
    'ActivityDateTime': ['first', 'last'],
    'Value1': 'mean',
    'Value2': 'mean'})


text:
Q: How to take one dataset/datatable and print nested content? I have a DataTable with the following content:
Category    Vehicle_Num
Minivan     1
Minivan     2
Minivan     3
Caravan     1
Caravan     6
5door       1
5door       3

etc...

I want to print the results to an aspx page in the format:

Minivan

1

2

3

Caravan

1

6

5door

1

3

I'm a little confused on how to do this in asp.net.  In the PHP world, it's easy for me to convert a data table into associative arrays, then print to template files.  I'm wondering if that's the same approach I need to take with asp.net.

A: It's easy with two repeaters:
<asp:Repeater Id="Categories" runat="server">
<ItemTemplate>

<%#Eval("Category") %>

    <asp:Repeater Id="myRep" runat="server" DataSource='<%# Eval("Numbers") %>'>
    <ItemTEmplate>

<%# Eval("VehicleNum") %>

    </ItemTemplate>
    </asp:Repeater>

</ItemTemplate>
</asp:Repeater>

and in code behind something like this:
Categories.DataSource = dt.Rows.Cast<DataRow>
.Select(r => new { Category = r.Field<string>("Category"), VehicleNum = r.Field<string>("Vehicle_Num") })
.GroupBy(v => v.Category)
.Select(g => new { Category = g.Key, Numbers = g.ToList() });


text:
Q: How to fit width columns with xlwings I wrote a function to save data in a WorkBook with xlwings and I want to fit the width column
class VehicleClass:
    def __init__(self, VehClass):
        # Vehicles 4 - Vehicle Classes
        self.VehClass = [VehClass]
        self.VehName = []
        self.ScaleFactor = []

    def add(self, VehName, ScaleFactor):
        self.VehClass*=1
        self.VehName.append(VehName)
        self.ScaleFactor.append(ScaleFactor)

    def save(self):
        # Vehicles 4 - Vehicle Classes
        sht = wb.sheets['Vehicles 4 - Vehicle Classes']
        rng = sht.range("A1").end('down').offset(1, 0)

        for i, item in enumerate([self.VehClass, self.VehName, self.ScaleFactor]):
            rng.offset(0, i).options(transpose=True).value = item
            rng.autofit() # or rng.columns.autofit()

but doesn't work.
Do you have any idea ? Thank you !

A: You can autofit the width of all columns in an excel file with the following code:
import xlwings as xw

path = r"test.xlsx"

with xw.App(visible=False) as app:
    wb = xw.Book(path)

    for ws in wb.sheets:
        ws.autofit(axis="columns")

    wb.save(path)
    wb.close()

A: You need to take autofit() outside of the loop as it will auto fit the column width for each row.  Unless the last row has the longest text this won't work.
If you want to auto fit the entire column you can use rng.entirecolumn.autofit() or specify your range to include all rows that you want to auto fit the column width such as sht.range("A1:A20").columns.autofit()


text:
Q: Group laws in class field theory In the case of a quadratic imaginary number field one can construct its maximal abelian extension using torsion points of an elliptic curve with complex multiplication by this field.
In the case of a local field, Lubin-Tate theory provides an explicit construction of its maximal abelian extension using torsion points of a formal group law on the maximal ideal.
Are there any examples of similar arguments, or even general facts?

A: As mentioned in the comments, this is precisely Hilbert's twelfth problem, for the simple reason that any solution to that problem can be turned into a "group law argument" (or any solution to it is a "group law argument" in disguise in the first place).
For example, you can think of the Kronecker-Weber theorem as saying that abelian extensions of $\mathbb{Q}$ are generated by torsion points of its multiplicative group.
The most general result of this type is Shimura's complete solution for CM-fields (see Complex multiplication of Abelian varieties and its applications to number theory).
You can complete the global field picture as mentioned in the comments (Carlitz-Hayes-Drinfeld) and the local one with Lubin-Tate.
PS. I corrected the question: "In the case of quadratic number field...". Only the imaginary case is know. For real quadratic fields this is wide open (the best way to attack it seems to be via the Stark conjectures).


text:
Q: foreachRDD to pull average number of words & characters for each RDD in J8 Spark Streaming of Twitter API I'm trying to get the average number of words and characters in each RDD I pull from the Twitter API using spark in Java 8. However, I'm having trouble using streams to achieve this. My code is as follows:
//Create the stream.
JavaReceiverInputDStream<Status> twitterStream = TwitterUtils.createStream(jssc);
//Outputs the text of tweets to a JavaDStream.
JavaDStream<String> statuses = twitterStream.map(Status::getText);
//Get the average number of words & characters in each RDD pulled during streaming.
statuses.foreachRDD(rdd -> {
            long c = rdd.count();
            long wc = rdd.map(s -> s.split(" ").length).reduce(Integer::sum);
            long cc = rdd.map(s -> s.split("").length).reduce(Integer::sum);
            long avgWc = wc / c;
            long avgCc = cc / c;
            System.out.println(wc / c);
            System.out.println(cc / c);
        return avgWc, avgCc;});

The error I'm getting is that the return type expected for foreachRDD is void and my return is a long format.
How can I get around this? Is there another way I need to approach this?

A: A possible solution would be to use JavaDStream.transform. This functions allows to stay within the SparkStreaming-API:
JavaDStream<String> statuses = ...
JavaDStream<Tuple2<Long, Long>> avgs = statuses.transform(rdd -> {
            long c = rdd.count();
            long wc = rdd.map(s -> s.split(" ").length).reduce(Integer::sum);
            long cc = rdd.map(s -> s.split("").length).reduce(Integer::sum);
            long avgWc = wc / c;
            long avgCc = cc / c;
            //System.out.println(wc / c);
            //System.out.println(cc / c);
            return jssc.sparkContext().parallelize(Collections.singletonList(Tuple2.apply(avgWc, avgCc)));
        }
);
avgs.print();

A: There is no possibility to return data if the return type is void.
You can create a list outside the "foreachRDD" function and pass the values as shown below:
List<Data> listData=new ArrayList();
statuses.foreachRDD(rdd -> {
            long c = rdd.count();
            long wc = rdd.map(s -> s.split(" ").length).reduce(Integer::sum);
            long cc = rdd.map(s -> s.split("").length).reduce(Integer::sum);
            long avgWc = wc / c;
            long avgCc = cc / c;
            System.out.println(wc / c);
            System.out.println(cc / c);
            Data data=new Data();
            data.setAvgCc(avgCc);
            data.setAvgWc(avgWc);
            listData.add(data);
        });

Data is a class with two variables avgCc and AvgWc as shown below
public class Data {
    long avgWc;
    long avgCc;
    public long getAvgWc() {
        return avgWc;
    }
    public void setAvgWc(long avgWc) {
        this.avgWc = avgWc;
    }
    public long getAvgCc() {
        return avgCc;
    }
    public void setAvgCc(long avgCc) {
        this.avgCc = avgCc;
    }
    public Data(long avgWc, long avgCc) {
        super();
        this.avgWc = avgWc;
        this.avgCc = avgCc;
    }
    public Data() {
        super();
    }
}

Please let me know if this helps. Or you need more clarifications.


text:
Q: Laravel Generate not working I am running Sublime Test 2 in Windows 7 64-bit. I have installed (and re-installed many times) Laravel Generator and Laravel 4 Artisan. I have updated composer and all dependencies. But I cannot get it to work properly. If I press ctrl-shift-P and type 'laravel' I get a list of 11 Artisan options, then a list of 17 Generate options, 6 of which appear to be duplications, and then another list of 20 Artisan options. The first lot of Artisan options give WindowsError: [Error 2] The system cannot find the file specified, the Generate options give [InvalidArgumentException] There are no commands defined in the "generate" namespace.
The second batch of Artisan options do appear to work eg Laravel Artisan: Controller: Make gives a command line and if I type 'test' it creates a restful controller called test.php.
However, the more comprehensive resource generation remains unavailable to me.
Can anyone shed any light?

A: If you are using the way/generators package, you need to make sure to include the service provider ('Way\Generators\GeneratorsServiceProvider') in your config.app file.

A: First make sure you install this plugin first: https://github.com/laravelbook/laravel4-sublimetext-helper
And then you might want to do what is referred here:
http://net.tutsplus.com/tutorials/tools-and-tips/pro-workflow-in-laravel-and-sublime-text/#comment-925470112
There are other Windows users that had difficulties with this, but seem to have resolved them.


text:
Q: php multidimensional array - value minus 1 I am having trouble with my multidimensional array.
I have various items in the array.
The name and quantity of each item are displayed on the screen, with a - and + button to alter the quantity of each item by 1. Each button is a form posting back to the same page.
The example below is the function that is called when i click on the - button. It is supposed to subtract one from the quantity of the item.
It is correctly deducting one from the quantity and the item_id is correct. However, it is not updating the correct array item. In fact it seems to be creating a new array item, as a new item is appearing under the other items in the basket when the minus button is pressed.
I don't think I am referencing the correct array item in the array_splice call. I don't think I should be saying "$thisKey," after "array_splice($_SESSION["cart_array"]".
But, I'm not sure how to reference the array item I want correctly.
Please advise.
Code:
if (isset($_POST['itemMinus']) && $_POST['itemMinus'] != "") {
// Access the array and run code to remove that array index
$thisKey = $_POST['itemMinus'];
$thisKeyQuantity = $_POST['itemMinusQuantity'];
if (count($_SESSION["cart_array"]) <= 1) {
    unset($_SESSION["cart_array"]);
} else {
    array_splice($_SESSION["cart_array"], $thisKey, 1,
 array(array("item_id" => $thisKey, "quantity" => $thisKeyQuantity - 1)));
     }
 }

/********/
Solution:
Big thanks to Jeroen Bollen for contribution to solution.
My code now works as so:
if (isset($_POST['itemMinus']) && $_POST['itemMinus'] != "") {
// Access the array and run code to remove that array index
$thisKey = $_POST['itemMinus'];
$thisKeyQuantity = $_POST['itemMinusQuantity'];
if (count($_SESSION["cart_array"]) <= 1) {
    unset($_SESSION["cart_array"]);
} else {
    $i=0;
    foreach($_SESSION['cart_array'] as $key => $value) {
        if($value['item_id'] == $thisKey) {
            array_splice($_SESSION["cart_array"], $i, 1, array(array("item_id" => $thisKey, "quantity" => $thisKeyQuantity - 1)));
            break;
             }
              else{$i++;}//end if
         }//end foreach
     }//end else
 }//end if POST

A: How about:
foreach($_SESSION['cart_array'] as $key => $value) {
    if($value['item_id'] == $thisKey) {
        $value['quantity']--;
        break; // Stop the loop, we're done
    }
}


text:
Q: Can BLE iOS device be peripheral and central at the same time? Is there any possibility to have both peripheral and central mode available at the same time?
In that case we are advertising as peripheral while listening for advertisements of other devices.
Thanks

A: Yes - You can
Althpough the same device being central and peribheral at the same time is not standard as pe Bluetooth current specification, iOS currently supports it


text:
Q: C++ why is creating a new node to delete a node on a stack wrong I'm learning about singly linked list stacks in class and I came across this stackoverflow page that gave me some reference on how to pop a node:
Pop function on Linked list stack
The first answer uses the following code to pop off a node:
struct Node
{
    int data;
    Node *next;
};

int pop(Node *head)
{
    while(head->next != NULL)
    {
        head = head->next;
    }
    int value;
    Node *tmp;
    tmp = new Node;
    value = head->data;
    tmp = head;
    delete tmp;
    return value;
}

the third answer uses the following code:
int pop( Node * &top )
{
    int value = 0;

    if ( top )
    {
        value = top->num;
        Node *tmp = top;
        top = top->next;
        delete tmp;
    }

    return value;
}

now, because of the first answer I originally wrote my pop function like so:
// Pop the top element off of the stack and return its value.
StackElement Stack::Pop()
{
   assert (!Empty());
   StackElement poppedData = tos->data;
   Node *temp = new Node;
   temp = tos;
   tos = tos->next;
   delete temp;
   return poppedData;
}

but, my teacher said that creating a new node to delete a previous node will cause a memory leak.
Ultimately I rewrote my code to match style two like so:
StackElement Stack::Pop()
{
   assert (!Empty());
   StackElement poppedData = tos->data;
   Node *temp = tos;
   tos = tos->next;
   delete temp;
   return poppedData;
}

Can anyone explain to me why the first implementation is wrong? I'm surprised nobody commented on this when the person posted it on the other stackoverflow question. It seems to me like I'm creating a pointer temp of type Node that points to a new Node (aka new memory address), and then I'm setting the value of that memory address to the value in the top of the stack's memory address. I move the top of stack to the next node, and then delete this temp node I created, but because I declared it as a new Node that just has the value of the old top of stack, it doesn't actually have any relation to that node. The old top of stack node is removed from the stack but the memory is not properly freed. Is this correct?

A: The first answer is wrong.
tmp = new Node;
value = head->data;
tmp = head;
delete tmp;

This deletes the head pointer, which is what you want. But the function creates a new memory allocation at tmp and then immediately overwrites the pointer with the value head. You have now lost the pointer  to the allocated data. This is a memory leak.


text:
Q: llamar una funcion en el login de laravel Estoy trabajando con laravel 5.5 y quiero llama a una función cada vez que un usuario se logueo y es autenticado en laravel, he estado buscando y no encuentro nada.
y la pregunta final es
¿llama a una función en laravel cuando es logueo o autenticado?
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    //protected $redirectTo = '/home';
    //protected $redirectTo = 'Solicitude_estado';
    protected $redirectTo = 'dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        echo "como esta tu";
    }

}

A: Hay varias formas para hacerlo, asumiendo que quieras llamar la función una vez el usuario haya sido autenticado correctamente. Yo utilizaría el método authenticated() que está en el trait AuthenticatesUsers, para realizar lo que necesite, o para llamar a la otra función desde ahí, dependiendo lo que vaya a hacer, basta con incluir la función (que está definida vacía en el trait) en el controlador de login:
/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    //
}

También es importante que mires el método sendLoginResponse() del mismo trait, para que veas lo que ocurre cuando se utiliza authenticated():
/**
 * Send the response after the user was authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}


text:
Q: TextView con varios estilos Es posible crear un único TextView y situar en el varios textos con diferentes estilos?

Resultado esperado
De no ser posible hacerlo con un único TV, como sería la mejor forma?
Un saludo

A: Si, es posible utilizando la clase SpannableString o SpannableStringBuilder si queremos que la cadena sea mutable.
val textView : TextView = findViewById(R.id.textview)
val spannableText = SpannableString("Texto a cambiar dentro del span")

spannableText.span= TextAppearanceSpan(context, R.style.myStyle), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableText.setSpan(TextAppearanceSpan(context, R.style.myNextStyle), 6, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

textView.text = spannableText


text:
Q: How configure multiples process on 443 port? Apache - ubuntu here its my problem:
I have 2 applications configured on a server. React (client) and nodejs backend with their respective domains.
1 - example1.com
2 - example2.com
I have configured both SSL certificates for each of it as well. The problem occurs when you want to start the backend on the same port that the client is running.
Is it possible to run 2 processes on it? How should I do it?
these are my virtual host files:
example1-le.ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName example1.com
    ServerAlias www.example1.com
    ServerAdmin info@xample.com
    DocumentRoot /var/www/example1
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

SSLCertificateFile /etc/letsencrypt/live/example1.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example2.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

example1.conf
        ServerName example1.com
        ServerAlias example1.com
        ServerAdmin info@example.com.ar
        DocumentRoot /var/www/example/build

        <Directory "/var/www/example/build">
          RewriteEngine on
         # Don't rewrite files or directories
          RewriteCond %{REQUEST_FILENAME} -f [OR]
          RewriteCond %{REQUEST_FILENAME} -d
          RewriteRule ^ - [L]
           # Rewrite everything else to index.html to allow html5 state links
           RewriteRule ^ index.html [L]
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
RewriteCond %{SERVER_NAME} =example1.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

And the same for the another one.
When i tried to start the second project i receive :  EADDRINUSE: address already in use :::443
Thanks a lot for you help

A: You can NOT have to 2 different processes bind on the same port. What Olaf Kock suggested works fine and is easy to implement: you install apache on a dedicated server (or on the same machine: there's no difference) and then you configure a reverse proxy (the module is called mod_proxy). There are also other solutions (like haproxy) which require a bit more complex configuration but provide many more configuration options.


text:
Q: Помогите с регуляркой в htaccess Помогите написать правильное регулярное выражение в htaccess.
У меня прописано такое правило
RewriteRule ^search/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ inex.php?val=$1&val1=$2&val2=$3

Оно работает нормально, но мне нужно чтобы когда в строке, а именно в val2, было слово "page" срабатывало не это правило, а следующее:
RewriteRule ^search/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/page-([0-9]+)/$ index.php?val=$1&val1=$2&page=$3

Пробовал вот так прописать первое правило
RewriteRule ^search/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/(^[?!.*page]+[a-zA-Z0-9_-]+)/$ inex.php?val=$1&val1=$2&val2=$3

но не получатся, исключает только символы p,a,g,e, а мне нужно, чтобы исключало слово page. Подскажите возможно ли так сделать?
Заранее спасибо.

A: Для правил в mod_rewrite есть "модификатор" [L], который говорит, что при срабатывании этого правила другие просматривать не надо.
В вашем случае, правила надо поменять местами. То, которое, "ловит" page надо поставить первым и добавить для него [L]. Если же это правило не сработает, т.е. там нет page, то будет проверяться следующее правило.


text:
Q: xarray gives HDF error when iterating through opendap datasets I am trying to download some data from an OpenDAP server using xarray and python 3.7 on Windows 10, iterating through a series of stations and years and writing local files. A simple example below uses two of each and would fail for me:
import xarray as xr
stations = ["pxsc1","obxc1"]
for station in stations:
    for year in ["2019","2020"]:
        print(f"Working on station: {station} year: {year}")
        ndbc_url  = f"http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/{station}/{station}h{year}.nc"
        print(ndbc_url)
        fileout = "noaa_stdmet_{}_{}.nc".format(station,year)
        print(fileout)
        with xr.open_dataset(ndbc_url, engine='netcdf4') as remote:
            remote.to_netcdf(fileout,format="NETCDF4_CLASSIC")

The first example seems to go OK, then I get HDF Errors as shown below. The value of HDF5_USE_FILE_LOCKING does not seem to influence the behavior ... I don't really understand that limitation but I've tried it. Are there other ways to make it work?
Working on station: pxsc1 year: 2019
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/pxsc1/pxsc1h2019.nc
noaa_stdmet_pxsc1_2019.nc
Working on station: pxsc1 year: 2020
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/pxsc1/pxsc1h2020.nc
noaa_stdmet_pxsc1_2020.nc
Traceback (most recent call last):
  File "F:\atmospheric\noaa\ndbc_xarray2.py", line 57, in <module>
    ndbc_opendap()
  File "F:\atmospheric\noaa\ndbc_xarray2.py", line 54, in ndbc_opendap
    remote.to_netcdf(fileout,format="NETCDF4")
  File "C:\Users\eli\miniconda3\envs\schimpy_env\lib\site-packages\xarray\core\common.py", line 1499, in __exit__
    self.close()
  File "C:\Users\eli\miniconda3\envs\schimpy_env\lib\site-packages\xarray\core\common.py", line 1294, in close
    self._close()
  File "C:\Users\eli\miniconda3\envs\schimpy_env\lib\site-packages\xarray\backends\netCDF4_.py", line 512, in close
    self._manager.close(**kwargs)
  File "C:\Users\eli\miniconda3\envs\schimpy_env\lib\site-packages\xarray\backends\file_manager.py", line 222, in close
    file.close()
  File "netCDF4\_netCDF4.pyx", line 2276, in netCDF4._netCDF4.Dataset.close
  File "netCDF4\_netCDF4.pyx", line 2260, in netCDF4._netCDF4.Dataset._close
  File "netCDF4\_netCDF4.pyx", line 1754, in netCDF4._netCDF4._ensure_nc_success
RuntimeError: NetCDF: HDF error

A: It does not seem to be a problem of your code, since everything is working fine on my computer:
Working on station: pxsc1 year: 2019
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/pxsc1/pxsc1h2019.nc
noaa_stdmet_pxsc1_2019.nc
Working on station: pxsc1 year: 2020
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/pxsc1/pxsc1h2020.nc
noaa_stdmet_pxsc1_2020.nc
Working on station: obxc1 year: 2019
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/obxc1/obxc1h2019.nc
noaa_stdmet_obxc1_2019.nc
Working on station: obxc1 year: 2020
http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/obxc1/obxc1h2020.nc
noaa_stdmet_obxc1_2020.nc

However, I think it is because of limited computational power. I assume that Python still has stored the first array (which worked perfectly fine) but does not have enough memory to store the second one. This is why it returns RuntimeError and probably restarts the kernel (?).
Try to add remote.close() at the end of your with statement. This might solve it.
Is it necessary to use NETCDF4_CLASSIC? I prefer to use NETCDF4 instead, which is more common from what I know (?). I doubt that this would solve your issue, but you could give it a try.
In the following a slightly adapted version of your code:
import xarray as xr

stations = ['pxsc1', 'obxc1']
year = [str(x) for x in range(2019,2020+1,1)]

url_base = 'http://dods.ndbc.noaa.gov/thredds/dodsC/data/stdmet/'
files_in = [f"{url_base}{s}/{s}h{y}.nc" for s in stations for y in year]
files_out = [f"noaa_stdmet_{s}_{y}.nc" for s in stations for y in year]

def load(file, fileout):
    print(f"open file: {file}")
    with xr.open_dataset(file, engine='netcdf4') as remote:
        print(f"writing file: {fileout}")
        remote.to_netcdf(fileout, format="NETCDF4")
        remote.close()

for fin, fout in list(zip(files_in, files_out)):
    load(fin,fout)

A: I had the same problem and I managed to solve it by changing the format to 'NETCDF3_64BIT', which is used to work with files larger than 2 GB for specific versions of NETCDF. It may be something related to memory or the NETCDF version itself. I had this problem only on ubuntu, on windows (on the same machine) the routine ran normally.
Ex:
remote.to_netcdf(fileout,format="NETCDF3_64BIT")


text:
Q: Razor pages client site validation not working I'm trying to use client-side validation in my razor pages app but it's not working for the views.
It does work on the register page that is located under the identity area.
Create.cshtml
@model Toolbox.Models.ProjectsModel.Assignment

@{
    ViewData["Title"] = "Create";
}

Nieuwe taak maken

Taak

        <form asp-action="Create">

                <input asp-for="Name" class="form-control" />

                <input asp-for="Fase" class="form-control" />

                <input type="submit" value="Maak nieuwe taak" class="btn btn-primary my-2"/>

        </form>

    Terug

Assignment.cs
using System.ComponentModel.DataAnnotations;
using Toolbox.Interfaces;

namespace Toolbox.Models.ProjectsModel
{
    public class Assignment : IAssignment
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Naam")]
        [Required]
        public string Name { get; set; }
        [Required]
        public string Fase { get; set; }

        public List<SubAssignment> SubAssignment { get; set; }
    }
}

_ViewImports.cshtml
@using Toolbox
@using Toolbox.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

_viewStart.cshtml
@{
    Layout = "_Layout";
}

Program.cs
    app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(name: "default",
    pattern: "{controller=Home}/{action=Index}");
    endpoints.MapRazorPages();
});

Does anybody know how I need to solve this problem?

A: You need to include the _ValidationScriptsPartial file in the Razor page. Add the following to the bottom of the page/view:
@section scripts{
    <partial name="_ValidationScriptsPartial" />
}


text:
Q: How a chrome extension can write something in a textbook in calendar? I am the beginner for the chrome extension, I want to develop a simple function now.
I want to write something to the textbox in the calendar likes photo
perhaps it is not named textbook, so I add a photo here.
I have some questions:
1. how can i use *.js to detect the textbox?
2. how to write something in it automatic?
Could you poste some codes to understand better? Thank you.
I hava a *.js to inverse the text, but i don't really understand it 100%, could you explain it to me? thank you.
 // Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {

  if (tab.url.indexOf('calendar') > -1) {

         chrome.tabs.insertCSS(null, {code: '.ui-sch input { direction: rtl }'});
         chrome.tabs.insertCSS(null, {code: '.ui-sch textarea { direction: rtl }'});
  }
};

// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

A: I have found this answer, we can do this by search his ID and write somethings in it


text:
Q: Disable HTTP methods in Tomcat I have read these questions on disabling a list of methods in Tomcat:

*

*How can I disable HTTP Methods for Tomcat 5.5.27

*Disabling PUT TRACE DELETE request in Apache Tomcat 6.0
But is there a way to return a 405 response instead of a 403 response?

A: Build a servlet filter that checks the request method and sends a 405 response if the method is on a blacklist.


text:
Q: conda create with 'anaconda' flag no longer installs all of the packages It seems to me that when I used to run the following command from terminal:
conda create -n envname python=3.5 anaconda

Under The following NEW packages will be INSTALLED there was a list of several dozen packages, including numpy, pandas, matplotlib, etc.
Now when I run that command, it only lists six packages: anaconda, pip, python, setuptools, vs2015_runtime and wheel.
Is there something I need to do to get conda to install all of the default anaconda packages? Perhaps with that anaconda python library?
EDIT: This happens both on Windows 7 and on a Red Hat Linux server.


text:
Q: Not connecting to specific WiFi network My Lenovo thinkpad (ubuntu 16.04 LTS) can't connect to a specific network. Other devices can connect to this network, and my laptop can also connect to other WiFi networks.
I had this same issue already some time ago on a different network and, if I remember well, fixed it with something similar to the answer in this thread:
Can't connect to specific wifi network
I tried this and lots of other suggestions again but after trying for hours I've got no solution. Any ideas would be very much welcome.
Output of lspci:
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)

08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 [Condor Peak]

Output of sudo lshw -c network:
   *-network
   description: Ethernet interface
   product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
   vendor: Realtek Semiconductor Co., Ltd.
   physical id: 0
   bus info: pci@0000:02:00.0
   logical name: enp2s0
   version: 06
   serial: f0:de:f1:5b:36:ee
   size: 10Mbit/s
   capacity: 1Gbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl_nic/rtl8168e-2.fw latency=0 link=no multicast=yes port=MII speed=10Mbit/s
   resources: irq:24 ioport:4000(size=256) memory:d0404000-d0404fff memory:d0400000-d0403fff

*-network
   description: Wireless interface
   product: Centrino Wireless-N 1000 [Condor Peak]
   vendor: Intel Corporation
   physical id: 0
   bus info: pci@0000:08:00.0
   logical name: wlp8s0
   version: 00
   serial: 8c:a9:82:77:47:fc
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
   configuration: broadcast=yes driver=iwlwifi driverversion=4.4.0-34-generic firmware=39.31.5.1 build 35138 ip=192.168.43.70 latency=0 link=yes multicast=yes wireless=IEEE 802.11bg
   resources: irq:28 memory:d1d00000-d1d01fff

Output of rfkill list:
0: tpacpi_bluetooth_sw: Bluetooth
Soft blocked: yes
Hard blocked: no
2: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no


text:
Q: How to use the xml-conduit Cursor Interface for information extraction from a large XML file (around 30G) The following question is based upon the accepted answer of this question. The author of the accepted answer said that the streaming helper API in xml-conduit was not updated for years (source: accepted answer of SO question), and he recommends the Cursor interface.
Based on the solution of the first question, I wrote the following haskell code which uses the Cursor interface of xml-conduit package.
import Text.XML as XML (readFile, def)
import Text.XML.Cursor (Cursor, ($/), (&/), ($//), (>=>),
    fromDocument, element, content)
import Data.Monoid (mconcat)
import Filesystem.Path (FilePath)
import Filesystem.Path.CurrentOS (fromText)

data Page = Page
    { title :: Text
    } deriving (Show)

parse :: FilePath -> IO ()
parse path = do
    doc <- XML.readFile def path
    let cursor = fromDocument doc
    let pages = cursor $// element "page" >=> parseTitle
    writeFile "output.txt" ""
    mapM_ ((appendFile "output.txt") . (\x -> x ++ "\n") . show) pages

parseTitle :: Cursor -> [Page]
parseTitle c = do
    let titleText = c $/ element "title" &/ content
    [Page (mconcat titleText)]

main :: IO ()
main = parse (fromText "input.xml")

This code works on small XML files. However, when the code is run on a 30G XML file, the execution is killed by the OS.
How can I make this code work on a very large XML file?

A: The Cursor module requires that the entire contents be in memory, which seems to not be possible in this case. If you want to process files that large, you'll need to use the streaming interface.


text:
Q: UWP/Win2D - save drawing in memory A code sample would be nice, but just some generic advice on the best way to handle this situation would suffice.
I'm rendering an image on a Win2D Canvas.  The image is first made up of piecing together tile bitmaps to form a large image.  I'll call that the "Base Image".
I am then using various "draw" calls to mark up the base image and I'm also placing other bitmaps over the base image, to create the final image.
The user can scroll the image in any direction and/or zoom in and out of the image.  Mouse movements are tracked and tooltip-like is displayed over the canvas to provide the user with detailed information. Each time the user does anything that affects the image, I'm redrawing the entire image.  In some cases, the base image is made up of as many as 46,000 tiny bitmaps.
Even using this heavy-handed approach, the image redraws itself pretty quickly but this feels like the worst possible way of doing it.
My gut tells me that I should render the base image once, keep in it memory and then copy it onto the canvas as needed.  After that, overlay the necessary bits to finish the image.  I can't find any material that suggests how to keep an in-memory bitmap for this purpose.  Nor do I know if that is the most appropriate approach.
Any guidance or suggestions on the most appropriate course of action would be appreciated.
Paul

A: Your instincts are quite right here - you can most likely get a huge performance increase by drawing the image just once and then reusing a cached version of it.
CanvasRenderTarget is the way to go about this: check out https://microsoft.github.io/Win2D/html/T_Microsoft_Graphics_Canvas_CanvasRenderTarget.htm and https://microsoft.github.io/Win2D/html/Offscreen.htm as starting points.


text:
Q: Redux thunk: wait for async function to dispatch I'm creating a React Native application and using redux and redux-thunk to implement my API requests. I would like to know how I can wait for my action to be dispatched and make sure that my state has been updated in an async thunk logic. If I understand correctly, await will wait for the end of the thunk but the action is not dispatched yet. Although, as you can see in my usage, I need the state to be modified to proceed the rest of the code accordingly.
actions/user.js
export const tryLogin = (
  email: string,
  password: string,
  sessionToken: string = ''
): Function => async (dispatch: Function) => {
  const logUser = () => ({ type: LOG_USER })

  const logUserSuccess = (data: any, infos: any) => ({
    type: LOG_USER_SUCCESS,
    data,
    infos,
  })

  const logUserError = (signinErrorMsg: string) => ({
    type: LOG_USER_ERROR,
    signinErrorMsg,
  })

  dispatch(logUser())

  try {
    { /* Some API requests via axios */ }

    dispatch(logUserSuccess(responseJson, infos))
    return true
  } catch (error) {
    { /* Error handling code */ }

    dispatch(logUserError(error.response.data.error))
    return false
}

reducers/user.js
case LOG_USER:
  return {
    ...state,
    isLoggingIn: true,
  }
case LOG_USER_SUCCESS:
  return {
    ...state,
    isLoggingIn: false,
    data: action.data,
    infos: action.infos,
    error: false,
    signinErrorMsg: '',
  }
case LOG_USER_ERROR:
  return {
    ...state,
    isLoggingIn: false,
    error: true,
    signinErrorMsg: action.signinErrorMsg,
  }

RegisterScreen.js
if (await trySignup(
    emailValue,
    firstNameValue,
    lastNameValue,
    passwordValue,
    birthdateValue,
    genderValue
  )
) {
  if (userReducer.data) {
    navigation.navigate('Secured')
  }

A: In Redux,
When an Action is dispatched to the store, it will update the state of the UI automatically with new props.
Instead of watching the dispatched action, You can add a flag in the reducer signUpSuccess similar to isLoggingIn flag and listen to the changes in componentDidUpdate lifecycle method.
trySignup can be called separately (like on an event, formSubmit, button click, etc.)
RegisterScreen.js
class RegisterScreen extends React.Component{
...
componentDidUpdate(prevProps) {
  if (prevProps.signUpSuccess !== this.props.signUpSuccess){
    if (this.props.signUpSuccess) {
      navigation.navigate('Secured')
    }
  }
}
...
}
const mapStateToProps = (state) => ({
  signUpSuccess: state.userReducer.signUpSuccess,
});

export default connect(mapStateToProps)(RegisterScreen);

A:
If I understand correctly, await will wait for the end of the thunk
  but the action is not dispatched yet.

*

*Render can be update if any changes happens in props, so extract props in your render method and update UX as per change in props.

*I would suggest use React native debugger to check your actions
and current saved state.


text:
Q: How to edit data in JS file from .VUE file? TEST.VUE
<template>
  <div>
    <button @click="test()">test</button>
    <button @click="adddata()">add</button>
  </div>
</template>
<script>
import logs from './data.js'
export default {
    data () {
        return {
        logitems: logs.data().infomation,
    }
    },
    methods:{
      test(){
         console.log(logs.data().infomation)
      },
      adddata(){

        //FAIL
        logs.data().infomation.log1d = logs.data().infomation.log1d+1
        console.log(logs.data().infomation)

        //PASS
        this.logitems.log1d=this.logitems.log1d+1
        console.log(this.logitems)
      }
    }
}
</script>

DATA.JS
export default {
  data() {
    return {
      infomation: {
        log1d: 1,
        logDetail: "This is some log detail for log 1",
        logType: "general",
        createdBy: "name",
        CreatedAt: "date",
      },
    };
  },
};

from the above code If I run the fetched DATA in TEST.VUE I can update the data.
But if fetching data from DATA.JS when I fetch data The information will not be updated.
What can I do to get the data on DATA.JS to be modified?


text:
Q: How do I use my LSTM output as input for another LSTM in keras? In a sentence, I want to predict five different binary values. For each binary value, I want to predict a one-hot encoded value.
To do so I programmed 2 different LSTMs. But now I am not sure how I could use the output of the first LSTM to use it correctly in my second LSTM. So first, my two models:
First model
model = Sequential()
model.add(Embedding(word_count, embedding_size, input_length = sentence_length))
model.add(LSTM(hidden_layer_units))
model.add(Dense(5))
model.add(Activation("sigmoid"))

The output can be 0 or 1 for 5 values. F.e. [0,1,0,0,1]
Second model
main_input = Input(shape = (sentence_length,), dtype = 'int32', name = 'main_input')
embedding = Embedding(word_count, embedding_size,
                    input_length=sentence_length)(main_input)
lstm_out = LSTM(hidden_layer_units)(embedding)

auxiliary_input = Input(shape=(5,), name='aux_input')
x = concatenate([lstm_out, auxiliary_input])
main_output = Dense(4, activation='sigmoid', name='main_output')(x)

model = Model(inputs=[main_input, auxiliary_input], outputs=main_output)

The input of my auxiliary_input is like [0,0,0,1,0].
The output is one-hot encoded [0,0,1,0]
My idea
I first thought that maybe I can use the output of my first model directly as input for my second model. The problem: THe output of my secon model would change and I do not know how it is possible to have a output layer for my second model that can predict a 2-dimensional output like
[
 [0,0,0,1]
 [0,0,1,0]
 [0,0,0,1]
 [0,0,0,1]
 [1,0,0,0]
]

So my question:

*

*Is it possible to use the data of the first model directly as input for the second model by having an 2-dimensional output layer?
or 2. Is the following possible: For each binary value of my first model I pass a one-hot encoded array as input to the second model. So the second model exists 5 times. Only if all 5 second models predict the output correct my complete model is correct.

A: I reshaped my output layer and evaluated that reshaped layer. SO my last two layers look like this:
main_output = Dense(20,activation='sigmoid')(concatenated_layer)
reshaped_out = Reshape(target_shape=(5,4))(main_output)


text:
Q: SuiteCRM/Sugar CRM 6.5: Never Redeploy a Package in a Production Environment? I'm reading documentation at it says that you should never redeploy a package, but what if we modify/add additional Logic Hooks as time goes by?
We need to click "deploy" after these modifications, but it says we shouldn't..
Does it mean we need to publish the package, perform changes in the zip then re-install the zip?
Just trying to get a sense of the work flow.


text:
Q: Firebase - One to Many relationship & Queries It's been a while since heard about Firebase and I decided to start a small project of mine last week.
I've read many articles about database structure and I came up with two solutions for my database:
Case 1
Table B has the references, via the ownerId, to the records in table A
{
    "A" : {
        "user-id-1" : {
            "name": "James",
            "number": "11111"
        },
        "user-id-2" : {
            "name": "Rob",
            "number": "11111"
        },
        ...
    },

    "B" : {
        "id-b-1" : {
            "something": "value1",
            "ownerId" : {
                "user-id-1": true
            }
        },
        "id-b-2" : {
            "something": "value2",
            "ownerId" : {
                "user-id-2": true
            }
        },
        "id-b-3" : {
            "something": "value3",
            "ownerId" : {
                "user-id-2": true
            }
        },
        "id-b-4" : {
            "something": "value4",
            "ownerId" : {
                "user-id-1": true
            }
        },
        ...
    }
}

Case 2
Table A has the references, via the Bs array, to the records in table B
{
    "A" : {
        "user-id-1" : {
            "name": "James",
            "number": "11111"
            "Bs": {
                "id-b-1": true,
                "id-b-4": true,
                "id-b-7": true,
            }
        },
        "user-id-2" : {
            "name": "Rob",
            "number": "11111"
            "Bs": {
                "id-b-2": true,
                "id-b-3": true,
                "id-b-6": true,
            }
        },
        ...
    },

    "B" : {
        "id-b-1" : {
            "something": "value1",
        },
        "id-b-2" : {
            "something": "value2",
        },
        "id-b-3" : {
            "something": "value3",
        },
        "id-b-4" : {
            "something": "value4",
        },
        ...
    }
}

In table A the IDs of the records are the same as the IDs assinged to the logged-in user, user-id-1, since I can not add more properties to the user object provided by firebase.
I'd like to say that the records related between A and B can grow to thousands of records.
So there is a one-to-many relationship between A and B.
Let's say I want to retrieve all the Bs related to the user-id-1:

*

*Which database structure is better in this situatio, according to your experience?

*How can I retrieve all the Bs objects, by running only one query on the database?

*Can I use a sort of where clause which allows me to filter the Bs by looking at the ownerId value?

Thank you in advance for your answers.

A: Your structure seems to be describing a "Many to many" relationship but on different sides. since in "Case 1" ownerId can contain more than one id:
"ownerId":
{
    "user-id-1": true,
    "user-id-1": true
}

and in "Case 2" two of the "Bs" can contain the same Id:
"user-id-1" : {
       "name": "James",
       "Bs": {
           "id-b-1": true
       }
   },
   "user-id-2" : {
       "name": "Rob",
       "Bs": {
           "id-b-1": true
       }
   }

In both cases you have one "A" owning multiple "Bs" and one "B" being owned by multiple "As".
To make this One to many I would suggest to use "Case 1" and change the object to
"id-b-4" : {
    "something": "value4",
    "ownerId" :  "user-id-1"
}

This will allow only one owner of the item.
In "Case 2" nothing can enforce having unique "Bs" for each "A". And it will also make queries hard.
All that said, both cases are viable in my opinion, it depends on how are you using those objects, since the selling point of Firebase is the real time data you should choose the one that is more relevant for your use case. If you are observing "As" chose Case 2. If you are observing "Bs" choose "Case 1". Or you can use both, whatever makes you life easier.


text:
Q: AngularJS: load more data after main page loads I'm making an app in Angular (v1.6.10) where I'd like the main elements on the page to load first, allowing the user to interact with the page, and then use a service to load additional supplementary data (~50-100 network requests) / refresh certain elements on the page (e.g. load the text, then load the highlights and annotations that would style the text).
What is the right way / potential options to do this in Angular (render some stuff, get some data, then refresh elements)? I've looked into:

*

*WebWorkers - seems like the use case is more for heavy-duty background processing, and getting access to the service in the webworker looks tricky

*setTimeout to intersperse the requests with other work - I'm not sure if this is the best way
Thanks in advance!

A: One can chain requests:
$http.get(API+"/initialData")
  .then(function(response) {
    $scope.initialData = response.data;
    return $http.get(API+"/moreData");
}).then(function(response) {
    $scope.moreData = response.data;
});

It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.
The AngularJS framework will render the data as it arrives from the server.


text:
Q: How to properly access an Android java class using Pyjnius I am having a hard time trying to use Pyjnius to access a Android Java class "ContactsContract.Intents.Insert".
I have  been following this example provided here:
Pyjnius: http://kivy.org/planet/2012/08/pyjnius-accessing-java-classes-from-python/
Java class to access: MediaRecorder
But really what I want to access using Pyjnius is the "ContactsContract.Intents.Insert" in Android and get working code to add a new contact to my Android phone.
Android class: https://developer.android.com/reference/android/provider/ContactsContract.Intents.Insert.html
This is what I have so far but I am confused on the arraylist:
from jnius import autoclass

Data = autoclass("ArrayList")
data = Data()

MyContacts = autoclass("ContactsContract.Intents.Insert")

mycontacts = MyContacts()
data.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
data.put(Organization.COMPANY, "Android")
data.add(mycontacts)

A: Intents.Insert is a static class which contains static string constants. I had the same problem when I wanted to add contacts from the app I was building. I ended up writing a class containing a static method which would add a contact in java and adding it into my buildozer.spec file for compilation. I know its not exactly what you are after but it gives you a fair idea when running into these kinds of issues there is a work around. It's actually fairly easy to mix Python code with Java. Kivy is great for prototyping Android apps but like pyjnius the documentation is very limited.
Java code
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents;
import android.app.Activity;
import android.content.Intent;

public class Contact{

    public static void addContact(Activity pyActivity, String name, String phone, String email){
        Intent i = new Intent(Intent.ACTION_INSERT);
        i.setType(Contacts.CONTENT_TYPE);
        i.putExtra(Intents.Insert.NAME, name);
        i.putExtra(Intents.Insert.PHONE, phone);
        i.putExtra(Intents.Insert.EMAIL, email);
        pyActivity.startActivity(i);
    }

}

python script
PythonActivity = autoclass("org.kivy.android.PythonActivity")
Contact = autoclass("Contact")
Contact.addContact(PythonActivity.mActivity, "Steve", "666", "steve666@gmail.com")

and then finally add the Conact.java to the buildozer.spec file
android.add_src = Contact.java


text:
Q: WinAPI Threadpool I've searched in google, but cannot find how can I add my own function to Threadpool. I have a function with signature void MyFunction(void *param);. How I can create Threadpool and add this function for assynchronos execution. I know that exist TrySubmitThreadpoolCallback() function, but I cannot understand how to use it. I'll be very glad to see simple example.

A: In order to be able to use TrySubmitThreadpoolCallback you should change signature of your function to
void CALLBACK MyFunction( PTP_CALLBACK_INSTANCE Instance, void* Context );

And then you can use it without problem. Remember that in windows most callbacks should have the CALLBACK in their definition, because default calling convention in C is __cdecl but in Windows API it is usually __stdcall(read it CALLBACK).


text:
Q: Out of memory in neo4j using periodic commits I'm trying to load a pretty large (~200 million rows) file in neo4j using LOAD CSV like this
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM
'file:///home/manu/citation.csv.gz' AS line
MATCH (origin:`publication` {`id`: line.`cite_from`})
MATCH (destination:`publication` {`id`: line.`cite_to`})
MERGE (origin )-[rel:CITES ]->(destination );

but I keep seeing memory errors such as
raise CypherError.hydrate(**metadata)
neo4j.exceptions.TransientError: There is not enough memory to perform
the current task. Please try increasing 'dbms.memory.heap.max_size' in
the neo4j configuration (normally in 'conf/neo4j.conf' or, if you you
are using Neo4j Desktop, found through the user interface) or if you
are running an embedded installation increase the heap by using '-Xmx'
command line flag, and then restart the database.

when running the code, and in the server
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "neo4j.StorageMaintenance-14"
2018-12-05 15:44:32.967+0000 WARN   Java heap space
java.lang.OutOfMemoryError: Java heap space
2018-12-05 15:44:32.968+0000 WARN  Unexpected thread death: org.eclipse.jetty.util.thread.QueuedThreadPool$2@b6328a3 in QueuedThreadPool[qtp483052300]@1ccacb0c{STARTED,8<=8<=14,i=1,q=0}[ReservedThreadExecutor@f5cbd17{s=0/1,p=0}]
Exception in thread "neo4j.ServerTransactionTimeout-6" Exception in thread "neo4j.TransactionTimeoutMonitor-11" java.lang.OutOfMemoryError: Java heap space
java.lang.OutOfMemoryError: Java heap

Of course I tried setting this dbms.memory.heap.max_size thing (up to 24 GB...above that, my 32-GB machine will not even be able to start neo4j), but am still getting those. The thing I don't quite get is: what's the purpose of the USING PERIODIC COMMIT part if (it seems) neo4j tries to load everything at once? When looking at the manual or, e.g., this thread you would think USING PERIODIC COMMIT is a fix for exactly the problem I'm having.
Any clue? The only workaround that comes to mind is splitting the file in several pieces, but that doesn't look like an elegant solution (also, if that works...couldn't neo4j do that for me transparently?)
EDIT: the query plan using EXPLAIN

Cheers.

A: Probably more a workaround than a "solution" but putting a UNIQUE constraint on the property that is extensively checked for that cypher query did the trick for me:
CREATE CONSTRAINT ON (p:publication) ASSERT p.id IS UNIQUE


text:
Q: mail send but its empty in php i want to send mail and mail is going to send but problem is that mail is empty in mail box. What is the problem in my code?
$afile = $_FILES['myFile'];

//Getting info about above taken file
$fileatttype = $afile['type'];
$fileattname = $afile['name'];
$filesize=$afile['size'];
if($fileatttype=="application/octet-stream" or $fileatttype=="text/plain" or $fileatttype=="application/msword" or $fileatttype=="application/pdf")
{
 $otherData="**********************Personal Details*********************\n

Position Applied For :$Position\n
First Name :$First\n
Last Name:$LastName\n
Date Of Birth :$DD-$MM-$yy\n
Correspondence Address :$Caddress1 $Caddress2 $Caddress2\n
Permanent Address :$Paddress1 $Paddress2 $Paddress2\n
Contact No(HOME):$Home\n
Mobile :$Mobile\n
E-Mail :$EMail\n
**********************Education*********************\n

Quallification :$Quallification\n
OtherCourse:$OtherCourse\n
**********************Previous Working Details*********************\n

Company Name-$WCompany1\n
Title-$WTitle1\n
CTC-$WCTC1\n
Reasons of Leaving-$WReason1\n
Company Name-$WCompany2\n
Title-$WTitle2\n
CTC-$WCTC2\n
Reasons of Leaving-$WReason2\n
Company Name-$WCompany3\n
Title-$WTitle3\n
CTC-$WCTC3\n
Reasons of Leaving-$WReason3\n
Company Name-$WCompany4\n
Title-$WTitle4\n
CTC-$WCTC4\n
Reasons of Leaving-$WReason4\n

Current CTC:$CCTC\n
Expected CTC:$ECTC\n
Notice Period Required :$NoticePeriod\n
Total no of years experience :$TotalExperience Years\n
Current Location :$Clocation\n
Preferred Location:$Plocation\n
Resume:$Resume\n
**********************Family Details*********************\n
Father / Guardian Name :$Fname\n
Father / Spouse: Occupation:$Focc\n
Kids:$Kids\n
Age of Kids:$AOK\n
";
 $to="renu_activa@yahoo.co.in";
 $from=$_POST['First'];
 $subject=$Position;
 $headers = "From: $First";
 if($filesize>0)
    {
    $file = fopen($afile['tmp_name'],'rb');
    $data = fread($file,$afile['size']);
    fclose( $file );
    }
//Making a random number to use afterwards with help of current time
$semi_rand = md5( time() );

//Defining the type of email as Mime email
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//Appending to headers, telling that its multipart message with text and attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

//The text part of message in variable $otherData with other details
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$otherData . "\n\n";
//Encoding all the data read from file to "base64" the standard for email attachments
$data = chunk_split(base64_encode($data));

//Appending the file data to the email including the file name etc
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$sentmail=mail($to, $subject, $message, $headers);
if($sentmail)
{
header('location: career-with-us.php');
}
else
{
 echo "Mail Not Send Successfully....";
}
}
else
{
 echo "Wrong format: Please upload only PDF/DOC/DOCX/TXT file format...";
}

I am not getting why its empty neither textbox value nor file attachment is showing in mail. Its totally empty.

A: You define a new variable for the body of the email.
$mess = 'Please check it';
$messa = '*****...

I'm assuming you meant
$mess = 'Please check it';
$mess .= '*****...


text:
Q: Jest did not exit one second after the test run has completed using express I'm using JEST for unit testing my express routes.
While running the yarn test all my test case are getting passed, but I'm getting an error
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

I used async & done, but still it throws the above error.
Below is my spec code. Please help
routes.spec.ts
const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});

A: My problem was solved by this code:
beforeAll(done => {
  done()
})

afterAll(done => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close()
  done()
})

A: This worked for me
const mongoose = require('mongoose');
    afterAll(async(done) => {
  // Closing the DB connection allows Jest to exit successfully.
  try {
    await mongoose.connection.close();
    done()
  } catch (error) {
    console.log(error);
    done()
  }
  // done()
})

A: Adding
jest.useFakeTimers();

at the beginning of the test suite fixed it for me.
Might come from timers defined in components part of the render (like throttled buttons, mocks etc..).

A: You can try this one
"test": "jest --runInBand --force-exit"

A: For Firebase I had to call cleanup()
import {
    assertFails,
    assertSucceeds,
    initializeTestEnvironment,
    RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
import { doc, setDoc } from "firebase/firestore";

it('creates a new user document in firebase', async () => {
    const testEnv = await initializeTestEnvironment({
        projectId: "appname-test",
        firestore: {
            host: 'localhost',
            port: 8088
        }
    });

    const alice = testEnv.authenticatedContext("alice");

    await assertSucceeds(setDoc(doc(alice.firestore(), "users", "alice"), {
        fname: "Alice",
        lname: "Wonderland",
        dob: "18/01/1999",
        email: "alice@example.com"
    }));

    return await testEnv.cleanup();
});

A: I have added this line to package.json
It worked for me
jest --runInBand --detectOpenHandles --forceExit

A: For me it was a different issue I was using supertest to test routes itself so I had to close the connection to the server itself.
afterAll(done => {
    server.close();
    done();
});

You can start server in beforeAll block and close in after all:
beforeAll(() => {
   server = app.listen(someRandomNumberHere); // Random number is needed to avoid using same port in different tests if you run in parallel
})

afterAll(() => {
   server.close()
})

If this is not the case for you this issue might have something for you

A: I was having the same issue but in my package.json file i added "test": "jest --detectOpenHandles" and ran npm test --detectOpenHandles. I didn't get the error message this time. Maybe you can try doing that.

A: On my side, I just separate app.listen() from my app.
So with express, your app finish with an export.
// index.js
module.exports = app;

And just create another file to listen the port.
// server.js
const app = require('./index')
app.listen(...)

And if you import just the index (app index.js) in your tests, it should work with no extra config.
Of course your need to adjust the start of your express app. It should use now server.js.

A: I was running into the same issue but, I was using the pg module with my NodeJS Express app. I want to post this for those using this stack as well if it helps them.
Essentially, supertest creates a server connection, which some people might get the TCPSERVERWRAP error because it doesn't get closed, regardless whether I use async/await or the jest done callback. So, this has to be closed after each test. On top of that, the database connection remains open so I mocked it.
Closing the server connection and mocking pg together solved the error for me.
products.tests.ts
import request from 'supertest'
import { Pool } from 'pg'
import app from '../app'
import type { Server } from 'http'

jest.mock('pg')

const { ROUTE_VERSION = '/v1' } = process.env
const route = (path: string) => [ROUTE_VERSION, path].join('')
const pool = new Pool()
let server: Server

beforeEach(() => {
   server = app.listen(4000)
})

afterEach(() => {
   server.close()
})

describe('GET /products', () => {
   it('returns array of products', async () => {
      await request(server)
         .get(route('/products'))
         .expect(200)
         .expect((res) => {
            expect(pool.query).toBeCalledTimes(1)
            expect(res.body).toBeInstanceOf(Array)
            expect(res.body).not.toHaveLength(0)
         })
   })
})

UPDATE: Meant to use beforeEach and afterEach to close the server after EACH test, otherwise, it still remains open like before.
UPDATE 2: Using async/await otherwise, it will always pass because request is asynchronous and doesn't complete unless you wait for it to finish.

A: Your app.listen block can just be wrapped into this condition:
if (require.main === module) {
  // ...
}

Example:
// index.js

import express from "express";

const app = express();

app.get("/", (req, res) => {
  res.status(200).json({});
});

app.get("/toppings", (req, res) => {
  res.status(200).json({});
});

if (require.main === module) {
  app.listen(5050, () => {
    console.log("Server is listening on port 5050");
  });
}

export default app;

// index.test.js

import request from "supertest";
import app from "./index";

let server;

describe("test server", () => {
  beforeEach(async () => {
    server = await app.listen(4040); // Can be any port
    global.agent = request.agent(server);
  });
  afterEach(async () => {
    await server.close();
  });

  describe("connection", () => {
    it("responds with status 200", () => {
      return request(server)
        .get("/")
        .then((response) => {
          expect(response.statusCode).toBe(200);
        });
    });
  });
});

A: In NestJs apps, where you have something like
app = moduleFixture.createNestApplication();
await app.init();

Just add this in your test file
afterAll(done => {
    app.close()
    done()
})

You can as well use async
afterAll(async() => {
    await app.close()
})

A: My problem is that I use Sequilize ORM and I forgot to close it at the end of testing inside the afterAll function callback.
This is my code:
afterAll((done) => {
    MatrixTableHeaderCol.destroy({
        where: {},
        force: true
    }).then(() => {
        done();
    });
});


text:
Q: How much of the surface of these equilateral triangles would be lit? Consider an equilateral triangle $\Delta ABC$ in 3D with $A=(1,0,0)$, $B=(0,1,0)$ and $C=(0,0,1)$ as well as its mirror image $\Delta A'B'C'$ with $A'=-A$, $B'=-B$ and $C'=-C$. We assume that these triangles are "filled in" such that they can cast shadows under the light of a sun. Let the sun be infinitely far away in the direction $s\in\mathbb R^3$ such that it casts rays parallel to $-s$.
Depending on $s$, how much surface area of the triangles is lit and how much is shadowed?
I can, for a given $s$, project the triangles onto the plane $H_s$ through the origin with normal $s$, choose a coordinate system on it, use the Sutherland-Hodgman algorithm to clip both triangles with respect to each other and compute the area of the resulting convex polygon. Unfortunately, I have trouble finding an analytical expression for the area of this polygon depending on $s$.


text:
Q: inline editing table / grid for for MVC What is the easiest way to create a table where users can edit data directly (excel like) with minimum effort?
There are a lot of libraries and custom control but I am looking for something that is easy to implement and does not require a lot of coding.

A: In the controller create method for adding where you pass the parameter to with GET:
public bool EditData(int pkId, int statusID,  string Comments)
{
    // logic to edit
}

In your view add a table of data with your controls add the primary key to the ID of the control so that you can use it in jquery

      Status
      Comments

    @foreach (var item in Model)
    {

                @Html.DropDownList("StatusID" + @Html.DisplayFor(modelItem => item.pkID), new SelectList(ViewBag.Status, "StatusID", "StatusTitle", item.StatusID), htmlAttributes: new { @class = "form-control", style = "width:100px" })

                <textarea id="Comments_@Html.DisplayFor(modelItem => item.pkID)" rows="5" cols="20">@Html.DisplayFor(modelItem => item.Comments)</textarea>

                <input type="button" class="btn btn-default" value="save" onclick='updateData("@Html.DisplayFor(modelItem => item.pkID)" )' />

   }

In the javascript add a call to the the edit method
function updateData(pkID) {
    // the id of the drop down list is AssetEffectiveness + effectivnessid
    var Status = $("#StatusID" + pkID).val();
    var Comments= $("#Comments_" + pkID).val();
    $.ajax({
        url:  "YOU_CONTROLLER_URL/EditData?pkId=" + pkID + "&statusID=" + Status + "&Comments=" + Comments,
        cache: false
    })
    .done(function (data) {
        if (data == 'True') {
            // change bg of the tr
            $("#Commects_" + pkID).closest('tr').css('background-color', '#eeffee');
            // animate to indicate the save
            $("#Commects_" + pkID).closest('tr').fadeOut(500).fadeIn(500);
            // return color back after 2 seconds
            setTimeout(function () { $("#Commects_" + pkID).closest('tr').css('background-color', ''); }, 1000);
        }
        else {
            alert('not saved');
            $("#Commects_" + pkID).closest('tr').css('background-color', '#ffcccc');
        }
    });
}


text:
Q: Ruby on Rails - Access Children Relation from has_and_belongs_to I'm having a problem with this one, and I cannot find the answer anywhere on the Internet.
Here is the error I'm getting:
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "region_translations"
LINE 1: ...ions"."id" = "orders_regions"."region_id" WHERE ((region_tra...

So I have the class Order, that has this relation:
has_and_belongs_to_many :regions, :trough => :regions_orders

Then, I have this method in the rails admin section:
rails_admin do
    parent Booklet

    list do

      field :first_name
      field :last_name
      field :sent
      field :address
      field :state
      field :city
      field :postal_code

      field :booklets_orders
      field :regions
      field :language

      field :regions do
          searchable ({Region::Translation => :title})
          sortable({:region_translations => :title})
          filterable true
          queryable true
      end

Then, I see the region appearing in the possible filter, but if I try a request, I get the error mentionned above. From what I understand, it's because it is not doing a left join between the table orders_regions.region_id and the region_translation. But I am honestly not sure how to access it, the relation is properly set between region and region_translation (it works everywhere in the site), so I'm stucked there... Any clues ?

A: Here is how you can set this up explicitly:
class Order < ApplicationRecord
  has_many :regions_orders
  has_many :regions, through: :regions_orders
end

class RegionsOrder < ApplicationRecord
  belongs_to :order
  belongs_to :region
end

class Region < ApplicationRecord
  has_many :regions_orders
  has_many :orders, through: :regions_orders
end

The regions_orders table is the join table and will have the order_id and region_id columns, along with any other columns you wish to put in it. These additional columns should reflect some entity that is a combination of the region and order for that row. For example, you may have an additional column called quantity, which would represent the quantity of units sold for the order in that region. So one row of your join table could look like this for order_id, region_id and quantity respectively: 22, 12, 1000. Which means that 1000 units were sold in region 12 (this is the id for the region in the regions table) for order 22 (this is the id for the order in the orders table). I don't know what you are trying to model, but I hope this helps.