text:
Q: Differentiating the binomial coefficient I took a lecture in combinatorics this semester and the professor did the following step in a proof:
He showed that function $f: x \mapsto \binom{x}{r}$ is convex for $x > r - 1$ (in order to use Jensen's inequality on $f$) and did this in the following way:
"By the product-rule we have $$f''(x) = \frac{2}{r!} \sum_{0 \leq i < j \leq r - 1} \prod_{l = 0}^{r - 1} ( x - l) \frac{1}{(x - i ) (x - j)} \geq 0$$ for all $ x > r - 1$." I am a bit confused on his definition: How would one extend the binomial coefficient to $x \notin \mathbf{N}$? I first thought about piecewise linear interpolation, but then I can't differentiate it. I also thought of plugging in the Gamma-function for the factorials, but I doubt that this is the definition he used here.
Can anyone explain to me what's happening here?
Thanks!

A: As small supplement:

A generalisation of the binomial coefficient is used in the binomial series representation
  \begin{align*}
(1+x)^\alpha=\sum_{r=0}^\infty\binom{\alpha}{r}x^r\qquad\qquad |x|<1, \,\alpha\in\mathbb{C}
\end{align*}
  where the binomial coefficient
  \begin{align*}
\binom{\alpha}{r}=\frac{1}{r!}\alpha(\alpha-1)\cdots(\alpha-r+1)
\end{align*}
  can be defined even for complex $\alpha$. This implies that we can consider the binomial coefficient as real-valued (or complex-valued) polynomial of degree $r$
  \begin{align*}
&f:\mathbb{R}\rightarrow\mathbb{R}\\
&f(x)=\binom{x}{r}\\
&\qquad=\frac{1}{r!}x(x-1)\cdots(x-r+1)
\end{align*}
  which is so accessible to analytical operations (differentiation, etc.).

And you're right, it's not necessary to involve the Gamma-function here.

A: A way to write the (usual) binomial coefficient is
$$\binom{n}{r}= \frac{\prod_{i=0}^{r-1}(n-i)}{r!}.$$
In this expression $n$ does not have to be an integer for it to make sense.
This is the (or at least one) way to extend the definition.
So
$$\binom{x}{r}= \frac{\prod_{i=0}^{r-1}(x-i)}{r!}.$$


text:
Q: How to get collection of objects from table I have to retrieve a collection of objects from table using loop. But I got an error that

The model item passed into the dictionary is of type 'ThaniyamBank.Models.Board', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[A.Models.Board]'

Why this error is coming ? How can I solve this error ?Should I need to change my query ?
controller
public ActionResult Board()
{
    var res = db.Boards.Select(t => new
    {
        Id = t.Id,
        Name = t.Name,
        Designation = t.Designation,
        Phone = t.Phone
    }).ToList();
    return View(res);
}

view
@model List

@for (var j = 0; j < Model.Count(); j++)
{

            @Html.HiddenFor(m => m[j].Id)
            @Html.HiddenFor(m => m[j].Name)
            @Html.DisplayFor(m => m[j].Designation)
            @Html.DisplayFor(m => m[j].Phone)

}

model class
public partial class Board
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
    public string Phone { get; set; }
    public string PhotoUrl { get; set; }
}

I need to get the name , designation, and phone of all the peoples in the Board but i am getting an error that .
How can I fix this error?
How to retrieve a collection of data from table ??

A: You passing anonymouse object to View but expecting strongly typed class.
Your controller side should be:
public ActionResult Board()
{
    var res = db.Boards
           .Select(t => new A.Models.Board //note this
           {
               Id = t.Id,
               Name = t.Name,
               Designation = t.Designation,
               Phone=t.Phone
           }).ToList();
    return View(res);
}

Or event simplier, if you using DB model on View:
public ActionResult Board()
{
    var res = db.Boards.ToList();
    return View(res);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement angular $watch function in core javascript As i know that angular watches are evaluated in every digest loop. So, i need such kind of function in core javascript for watch http response json object.
Somethings like this:-
var oldResponseData='{"name":"Ram","age":"45"}';
function myCustomeWatch(httpResponseData){
  if(httpResponseData===oldResponseData){
     return false;
  }else{
     oldResponseData=httpResponseData;
  }
}
.
.
.
 httpResponseData='{"name":"Ram","age":"46"}';//'{"name":"Ram","age":"45"}' != '{"name":"Ram","age":"46"}'
setInterval(function(){
   myCustomeWatch(httpResponseData);
},3000);

A: You can also use Object.watch. More info is available here
And here is the polyfill for ES5 compatible browsers


text:
Q: File comparison, one-to-many I need a program that allows comparing one text file to many others without having to open each one manually.
This is how it would work:
1) select the file which all others will be compare with
2) drag and drop the other files to start the comparison
3) the first pair with be displayed and as soon as that first comparison is dismissed the second would be displayed, and so on until every comparison is done
More details:
every file contains only text, there aren't any binary files
there are in different folders, some even in different drives
a clone/duplicate finder is not the solution, content of the files is what's important
I'm using windows 7
thank you.

A: You have the comp and fc command line tools as a part of Windows 7. You could potentially script around them to achieve what you want.


text:
Q: "= default" about constructor in c++ struct Sale{
Sale () = default;//I got nothing about those cod
Sale(std::istream &input);
Sale(const std::string &s):book(s) {}
//and so on......
}

What did the second code mean?
Is that mean that doing nothing ?Or we must write those default code to tell the compiler we made a default constructor which doing nothing.
And what about the "= default" mean in the C++11?

A: = default specifies compiler generted code for that function.


text:
Q: Find the next prime number using the logic in the prewritten code? Still relatively new to Python and I currently have one function that identifies prime numbers as a bool of true or false. If the input value is prime then I will have a second function identify the next prime number after it. Here is what I have so far:
def is_prime(n):
>if n in range(0, 2):
>>n = False

>for i in range(2, n):
>>if n % i == 0:
>>>n = False

>>else:
>>>n = True

>return n

def find_next_prime(n):

*Use the first function is_prime to run this second function*

A: Try this :
def find_next_prime(n):
    n += 1
    while not is_prime(n):
        n += 1
    return n

A: def is_prime(n):
    if n in range(0, 2):
        return True

    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def find_next_prime(n):
    if is_prime(n):
        print("{} is prime".format(n))
        n += 1
        while not is_prime(n):
            n += 1
        print("{} is next prime".format(n))
    else:
        print("{} is not prime".format(n))

You can then run it
find_next_prime(4)  \\ output --> 4 is not prime

find_next_prime(53) \\ output --> 53 is prime \n 59 is next prime


text:
Q: exploring google maps API for android Iam developing an android app.about google maps API for android i want to ask that
i have override ontap method so that i'll be getting coordinates of the tapped location on googlemap but know i want to show a marker or pin on the taaped location coordinates. please tell me how i can modify my below code:
public boolean onTap(GeoPoint point, MapView mapView)
       {
         Context contexto = mapView.getContext();
         String msg = "Lat: " + point.getLatitudeE6()/1E6 + " - " +
                      "Lon: " + point.getLongitudeE6()/1E6;

         Toast toast = Toast.makeText(contexto, msg, Toast.LENGTH_SHORT);
         toast.show();
        return true;
       }

Best Regards,
Muhammad Tahir Ashraf

A: Check Answers below.

*

*Yes

*Yes

*Yes

Every thing is possible.
Check the below link for complete information about the Google Maps.
http://developer.android.com/resources/tutorials/views/hello-mapview.html


text:
Q: How do I execute a sed command from a Bash variable? I have a sed command that works when executed directly.
echo foo > /home/user/bar
sed -i 's/foo/zoo/' /home/user/bar

It also works when directly embedded in $(...) or `...`.
However, if I try to execute it from a Bash variable, I get an error:
CMD="sed -i 's/foo/zoo/' /home/user/bar"
$CMD

Error:

sed: -e expression #1, char 1: unknown command: `''

It also works if I echo it out and source the file:
echo $CMD > file
source file

What's going on here, and how do I get the sed command to run from a Bash variable?

A: Don't store full command a string variable to avoid word splitting. Use an array or shell function:
# store command in an array
cmd=(sed -i 's/foo/zoo/' /home/user/bar)

# execute the command
"${cmd[@]}"

Or else use a shell function:
fn() {
   sed -i 's/foo/zoo/' /home/user/bar
}

#call it as:
fn

Read this BASH FAQ: I'm trying to put a command in a variable, but the complex cases always fail!

A: use eval : I am not sure why you want to do it. Note that using eval is a fragil solution and can cause your script to broke.
eval $CMD


text:
Q: Barracuda Quarantine - Externally Accessible? I manage several Barracuda Spam filters.  When an e-mail is sent through the barracuda to somebody and it seems to have spammy charactertistics but is not clearly spam, the barracuda will place it in the user's quarantine.  Once a day it sends an HTML e-mail notification of all the messages the user currently has in spam, with links to the barracuda applicance.
My question is to those of you who have a Barracuda Spam filter out there... do you make this quarantine page accessible from outside your network?  So if a user clicks on the links in the e-mail from outuside of your network (such as at home) they are still able to access their quarantine?

A: Yes, when we were using the quarantine feature we made this available externally.  We used LDAP authentication and made only the SSL site available, so that the connection was encrypted and not sending login credentials cleartext.


text:
Q: BAD ACCESS error when running SwiftUI app with environment variables I'm trying to make a simple app with authentication. However, when I run the app, I get a thread one bad access code as shown in the first image. I dont know if it has to do with the environment variable that I've declared, or there is another problem.
I would appreciate any help!
The thread error im getting:

View with an environment object:

A: You need to hold AppViewModel as a @StateObject instead of creating it for each view individually each time the app's root view gets rendered:
struct VendorHub: App {
    @StateObject var appViewModel = AppViewModel()
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some View {
        WindowGroup {
            NavigationView {
                ContentView()
                UserSelection()
            }
            .environmentObject(appViewModel)
        }
    }
}

You have 2 views - ContentView and UserSelection view. In your code, you assign to each of them a separate instance of AppViewModel constructed during the execution of body.
Now, to understand where the issue is coming from, you should ask yourself:

*

*when does the code inside body of VendorHub and the code inside the body of ContentView and UserSelection view gets executed?

*is the environment object kept in memory in between these body invocations?
To research this, you can implement deinit method in AppViewModel and log from it when the view model gets deallocated. Also you can log when each body method is executed.
If view model is deallocated in between body invocations, that's the reason why you get the crash.
That means that you have to keep somehow the instance of view model in between body invocations. That's where you need @StateObject.


text:
Q: Eclipse CDT setup for remote build Is there a better way to setup Eclipse CDT for local editing and remote building?
I am working on a C++ project that uses GNU make in Linux. The code is under CVS on a Linux server.
When I'm in the lab, I use Eclipse CDT on a Linux-x64 PC. The project is built on a Linux-x86 PC. All the computers in the lab (including the CVS server) have NFS mounts.
When I'm at home, I use Eclipse CDT on a Windows 7 PC. The Windows PC connects to the Linux CVS server via SSH tunnel. To edit source, I rsync the C++ project under the Linux Eclipse workspace back to my Windows Eclipse workspace. (I can also do a remote CVS checkout on the Windows PC.) To build from home, I use a custom build command that

*

*SSH's to the Linux-x86 PC,

*rsync's the C++ project from my Windows Eclipse workspace to my Linux Eclipse workspace,

*and then runs make on the Liunx-x86 PC, specifying the correct path for the Makefile.

In order to go back and forth between lab and home without committing my changes to CVS every time, I use rsync. When I transition from lab to home, I rsync sources to my Windows Eclipse workspace. When I build from home, the sources get rsync'd back to the Linux Eclipse workspace.
Is there a better, less wonky way to do this?
(I'm NOT interested in remote debugging.)

A: Netbeans has good support for this. I've tried to get it working in Eclipse, but Netbeans was much easier with built in support.

A: One solution is to use Eclipse RSE (Remote System Explorer). It allows to "mount" a remote subfolder directly into the workspace (via FTP or SSH). CDT has some issues with the virtual file system used by RSE, but it ... well, more or less works.
There's some discussion on that on my question:
Work on a remote project with Eclipse via SSH

A: I need to do similar things, and I took a look at Synchronized Projects:
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.ptp.doc.user%2Fhtml%2FlocalVsRemote.html
Synchronized projects support multiple build configurations, so the build can happen either locally or on one or more remote systems. The user can select which system will be used to build the project. A launch configuration can then be created to to run the application on the target machine.
To build on remote machine, follow Working with a Synchronized Project: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.ptp.doc.user%2Fhtml%2Fsync.html

A: How about using vnc and remotely logging in, using eclipse ON your unix box in the lab?
The only thing to go across the link is your editing, and vnc is pretty efficient about that.

A: This post seems quite old. But in case this might help somebody, I'd like to post a solution that works both on Linux and windows machines, which is really easy.
Now there is an Eclipse parallel version and you can just install that and change few lines in your remote machine's bash_profile to load few git functions. I'm even connecting from behind a gateway which is a little tricky. It is easier without. See this link:
http://umayanganie.blogspot.com/2017/05/build-debug-cc-projects-via-remote.html


text:
Q: PostgreSQL subquery specification I am working on several SQL queries for practice and was having some trouble with this one.
I am trying to find the distinct courses that 'SYS' track students in 'CptS' major are enrolled in and then return the courseno and credits for those courses. The results should be sorted based on the courseno.
The tables can be created from this file. It is a zip file containing the SQL to create the tables.
The order they need to be created is like so:  course, tracks, student, enroll, prereq,trackrequirements
I am having trouble getting the count of the courses which are just in the the trackrequirements rather than all of the courses enrolled.
Here is my SQL statement thus far:
SELECT student.sname, student.sid, student.major FROM enroll, student, trackrequirements
WHERE student.trackcode = trackrequirements.trackcode AND student.major = trackrequirements.major AND enroll.sid = student.sid AND enroll.courseno = trackrequirements.courseno
GROUP BY student.sname, student.sid, student.major
HAVING COUNT(trackrequirements.courseno) = COUNT(enroll.courseno)
ORDER BY student.sname

If someone could give me some advice or  help it would be much appreciated.
Here are the Schemas:
CREATE TABLE Course (
courseno VARCHAR(7),
credits INTEGER NOT NULL,
 enroll_limit INTEGER,
 classroom VARCHAR(10),
PRIMARY KEY(courseNo),
);
CREATE TABLE Tracks (
major VARCHAR(7),
trackcode VARCHAR(10),
title VARCHAR(30),
PRIMARY KEY(major, trackcode)
);
CREATE TABLE Student (
sID CHAR(8),
sName VARCHAR(30),
major VARCHAR(10),
trackcode VARCHAR(10),
PRIMARY KEY(sID),
FOREIGN KEY (major,trackcode) REFERENCES Tracks(major,trackcode)
);
CREATE TABLE Enroll (
courseno VARCHAR(7),
sID CHAR(8),
grade FLOAT NOT NULL,
PRIMARY KEY (courseNo, sID),
FOREIGN KEY (courseNo) REFERENCES Course(courseNo),
FOREIGN KEY (sID) REFERENCES Student(sID)
);
CREATE TABLE Prereq (
courseNo VARCHAR(7),
preCourseNo VARCHAR(7),
PRIMARY KEY (courseNo, preCourseNo),
FOREIGN KEY (courseNo) REFERENCES Course(courseNo),
FOREIGN KEY (preCourseNo) REFERENCES Course(courseNo)
);
CREATE TABLE TrackRequirements (
major VARCHAR(7),
trackcode VARCHAR(10),
courseNo VARCHAR(7),
PRIMARY KEY (major,trackcode,courseNo),
FOREIGN KEY (major,trackcode) REFERENCES Tracks(major,trackcode),
FOREIGN KEY (courseNo) REFERENCES Course(courseNo)
);

Here is how some of the data looks:
Thank you for reading
Course:
('CptS121',4,24,'Sloan175'),                                                                      ('CptS122',4,25,'Sloan175'),                                                                    ('CptS223',3,25,'Sloan150'),                                                                    ('CptS260',3,3,'Sloan150'),                                                                     ('CptS322',3,20,'Sloan169'),                                                                    ('CptS323',3,19,'Sloan169')

Enroll:
('MATH115','12584189',3),
('MATH115','12534189',2),
('MATH115','12524189',4),
('CE211','12584189',3.5),
('CE211','12534189',2.5)

Prereq:
('CptS122','CptS121'),
('CptS223','CptS122'),
('CptS322','CptS223'),
('CptS323','CptS322')

Student:
('12584489','Aaron','ME',NULL),

('12584189','Macy','CE',NULL),

('12583889','John','MATH',NULL)

('12583589','Alice','CptS','SYS')

TrackRequirements:
('CptS','SE','CptS121'),
('CptS','SE','CptS122'),
('CptS','SE','CptS223'),
('CptS','SE','CptS260')

Tracks:
('CptS','SE','Software Engineering Track'),
('CptS','SYS','Systems Track'),
('CptS','G','General Track'),
('EE','CE', 'Computer Engineering Track'),
('EE','ME', 'Microelectronics Track'),
('EE','POW','Power Track');

This is my current output:
 sname sid major
 Ali 12582389 CptS
 Alice 12583589 CptS
 Bill 12581189 CptS
 Jack 12584789 CptS

This is the desired output:
sid sname major
12584789 Jack CptS

The data shown is only a piece of the total data, if you want to see the full data please let me know.
Any help is appreciated, please let me know if I have to change anything else.
Thank you for reading

A: I had to tweak your data to keep the relational integrity under check. With that what you need is something like the query below. Of course, you would need to replace the where class with the condition relevant to your problem. You can go to this  DBFiddle  to see a live run of the below query. The rule of thumb for building such queries is to follow basic steps like:

*

*Isolate what you need as output

*Find out the tables that provide the needed output

*Look for any relationship between the tables.

*If the relationship is missing find the tables that can complete the joins.

*Add your filter criteria to the where clause.

*Complete the final output demands like sorting, grouping.

This is absolutely a very layman way of explaining Query Building, but having a flow in mind helps. Let me know if you have questions.
select distinct s.sname, c.courseno, c.credits from trackrequirements t
JOIN enroll e ON e.courseno = t.courseno
JOIN student s ON s.sID = e.SID AND t.major = s.major AND t.trackcode = s.trackcode
JOIN course c ON c.courseno = t.courseno
where t.major = 'CptS'  AND t.trackcode = 'SE'
ORDER BY c.courseno;


text:
Q: How can I implement Priority Queue without using any built-in functions? this is my first question here ever, so formatting and such might be a little off. Please don't hate me :)
So what I am doing is making a class called PQUEUE and what I have already is:
class qNode:
    def __init__(self,data=None, next=None):
        self.data = data
        self.next = next
    def __str__(self):
        return str(self.data)

class PQUEUE:

    def __init__(self):
        self.head = None
        self.foot = None

    def push(self, value=None, priority=0):
        #This is what I want to make

    def pop(self):
        x = self.front.data
        self.front = self.front.next
        return x

    def clear(self):
        self._head = None
        self._foot = None

I am trying to make make a Priority Queue class (as you can see) without using heapq/queue classes or the built-in list methods.
What I can't figure out is how I would go on about doing this. I've tried searching everywhere online but everywhere I look people are doing this by either importing or using the built-in list methods.
Help very appreciated ! :)

A: It depends on what your definition of priority is, but you're going to have to iterate over your collection yourself, looking for the place to insert the next node:
node = self.head
while node.next and node.next.priority > priority:
    node = node.next

if node.next is None:
    node.next = qNode(value=value, next=None, priority=priority)
    self.foot = node.next
else:
    new_node = qNode(value=value, next=node.next, priority=priority)
    node.next = new_node

You'll have to add a priority to your qNode, of course, and you may have to adjust exactly where you're going to insert, but this should get you most of the way there.

A: Here is the implementation of priority queue in python using linked list:-
# Python code to implement Priority Queue using Linked List
# Node class
class Node:
    def __init__(self, item, priority):
        self.item = item
        self.next = None
        self.priority = priority

class PriorityQueue:
    def __init__(self):
        self.front = self.rear = None

    # Returns a boolean value indicating whether the queue is empty
    def isEmpty(self):
        return self.front == None

    # Adds the given item to the queue by inserting it in the proper
    # position based on the given priority. The new node is appended to
    # the end of the linked list
    def enqueue(self, item, priority):
        newNode = Node(item, priority)
        if not self.rear:
            self.front = self.rear = newNode
            return
        if self.front.priority < newNode.priority:
            newNode.next = self.front
            self.front = newNode
            return
        previous = None
        current = self.front
        while(current and newNode.priority < current.priority):
            previous = current
            current = current.next

        if current:
            previous.next = newNode
            newNode.next = current
        else:
            self.rear.next = newNode
            self.rear = newNode

    # Removes and returns the next item from the queue, which is the
    # item with the highest priority. If two or more items have the
    # same priority, those items are removed in FIFO order. An item
    # cannot be dequeued from an empty queue.
    def dequeue(self):
        if self.isEmpty():
            print('Queue is empty')
            return
        temp = self.front
        self.front = self.front.next
        if self.front == None:
            self.rear = None
        return temp.item


text:
Q: Deploy spfx webpart without using cdn I am currently developing some spfx webpart and i have deployed the webpart and using a SharePoint library as cdn. My question is: Can i deploy the webpart without using a cdn?

A: Yes, you can do that without having to enable CDN.
In your config > write-manifests.json file, there is a cdnBasePath property.
Modify that value to a document library path as below:
{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
  "cdnBasePath": "https://<tenant>.sharepoint.com/sites/test/DocLib"
}

After that, you need to upload the package in app catalog and then separately upload the files in the temp > deploy folder to document library.

A: Yes and if you are using a SharePoint Library to serve your static assets - you've deployed without an CDN :)
However, there is no way to include your assets into the .sppkg-file - it's not its purpose. Assets can be stored anywhere as long as it's accessible by the users.
[Edit]
Since SharePoint Framework v1.4 assets can be included into the .sppkg-file!
Waldek Mastykarz has a great post about this.
https://blog.mastykarz.nl/should-you-use-office-365-cdn/

A: i found the answer here
. It works from sharepoint framework 1.4 and is crucial to use includeClientSideAssets


text:
Q: Laravel 419 unknown status I am making an AJAX request from a subdomain to main domain. I have set up CORS so that subdomain is attached automatically to the allowed domain listing. I am getting a 419 (unknown status) error and upon dumping the error I found out that I am getting TokenMissmatchException.
I noticed also that that is infact true because I also saw:
"_token" => "h7I07Iv0m4sF7XHhXjtygnfCtITgzCi3Ml8lfT7Z" // <-- sent
"_token" => "N118Izko7j5uf851MpijBXInFLaUVicRdf9uw3h4" // <-- in session

I am obviously sending token with my AJAX request as I see it in the headers section when inspecting the request.
I suppose there is some missmatch going on because I am traversing from my subdomain to my domain.
How can I align tokens across my main domain and all subdomains so that I don't get an exception?
NOTE
All AJAX routes are receiving a token from
<meta name="csrf-token" content="{{ csrf_token() }}">

Attaching it to every request in
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

EDIT
I have placed this under session.php
"domain" => "." . env('APP_URL'),

because of the cookies, even though honestly I'm not sure what it does

A: Session sharing across multiple domain.....
There can be tweaks to do it. To make a cookie available in all the sub-domains you need to assign it to the root domain.
 session.cookie_domain = ".example.com"

Personally I would recommend a different approach (but it also depends on other factors upon which I don't have full visibility from your question....)
Perform the ajax call from/to the same subdomain  (CSRF middleware protected, standard CSRF usage)
On the controller perform a server to server backend call to your main domain (e.g. a curl_exec )
The server to server call is not visible and you can protect it... e.g. at network level or by adding an Oauth server if the two domain communicates through internet.


text:
Q: Changed activity to java class properly? I have a database handler that I accidently made an activity and I deleted the code to just make it like a java class but I noticed in my manifest file it says
'com.something.MyDBHandler' has no default constructor less... (Ctrl+F1)
Validates resource references inside Android XML files.
 'com.something.MyDBHandler' is not assignable to 'android.app.Activity' less... (Ctrl+F1)
Validates resource references inside Android XML files.
when I hover over "MyDBHandler" (sixth line from bottom).
and also I get
Unresolved class 'HighScore' less... (Ctrl+F1)
Validates resource references inside Android XML files.
when I hover over ".HighScore" (fourth line from bottom).
Manifest
<application
    android:allowBackup="true"
    android:icon="@mipmap/gamebutton"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".GameScreen"
        android:label="@string/app_name" />

    <activity android:name="MyDBHandler" />

    <activity android:name=".HighScore"></activity>
</application>

MyDBHandler class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
    onCreate(db);
}

//add a new row to the database
public void addProduct(Products product){
    ContentValues values = new ContentValues();
    values.put(COLUMN_PRODUCTNAME, product.get_productname());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_PRODUCTS, null, values);
    db.close();
}

/*//delete a product from the database
public void deleteProduct(String productName){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
*/

//print out the database as a string
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor point to location in your results

    Cursor c = db.rawQuery(query, null);
    //Move to the first row in your results
    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("productname")) != null){
            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
        }
        c.moveToNext();
    }

    db.close();
    return dbString;

}

}

A: Remove <activity android:name=".HighScore"></activity> if you don't want it.
From your AndroidManifest

A: Delete your MyDBHandler activity property from android manifest
<application android:allowBackup="true" android:icon="@mipmap/gamebutton" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".GameScreen" android:label="@string/app_name" /> <activity android:name=".HighScore"></activity> </application>


text:
Q: Too much slowliness on the syncfusion's gantt initial display We are having performance issues when trying to display the gantt chart in our app.
I made the following couple of stackblitzs showing it.
the first one with an active rows grouping on it : https://stackblitz.com/edit/react-pgu8va-ycxhtl?file=index.js
the second without any row grouping : https://stackblitz.com/edit/react-pgu8va-sfkyjn?file=index.js
Notice the timer in the dataBound in both these demos which shows that the time span between the moment that gantt is instantiated (and receiving the data) and the moment when the dataBound event triggers can be up to 6 seconds and may reach 15 seconds sometimes https://i.imgur.com/XJ8QqqL.png


text:
Q: mod_rewrite to remove SSO(single sign on) - junction name in URL I have  a SSO url -
http://<server>/<junction>/<application_context>/ssoLogin.do
e.g. http://pingu.intranet.com/tms/mint/ssoLogin.do

Once user hits this url. SSO junction appends headers and redirects to Apache webserver. My goal is to remove the SSO junction name once the request reaches Apache(where I am using ProxyPass and AJP to connect to Tomcat App).
Issue is mod_rewrite is picking the URI - /mint/ssoLogin.do. so I can not remove the junction name /tms. e.g. rewrite.log says
init rewrite engine with requested uri /mint/js/jquery/jquery.min.js

My conf file looks like
    ProxyPreserveHost On

# define the balancer, with http and/ or ajp connections
<Proxy balancer://application_cl>
    BalancerMember ajp://pingu01.intranet.com:8009 route=node1 disablereuse=on retry=0
    BalancerMember ajp://pingu02.intranet.com:8009 route=node2 disablereuse=on retry=0
</Proxy>

# Vendor Product ProxyPass Settings
ProxyPass /mint balancer://application_cl/mint stickysession=JSESSIONID|jsessionid nofailover=On
ProxyPassReverse /mint balancer://application_cl/mint

# Custom settings to remove junction name for proper javascript loading

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/tms/
RewriteRule ^/tms/(.*)  /$1
</IfModule>

# RequestHeader settings(as per Product documentation)
SetEnvIf X-Forwarded-Proto .+ HAVE_X_FORWARDED_PROTO
RequestHeader set X-Forwarded-Proto "http" env=!HAVE_X_FORWARDED_PROTO


text:
Q: How does null assertion work in dart and when can I use it? Can someone simply explain to me how null assertion (!) works and when to use it?

A: The ! operator can be used after any expression, e!.
That evaluates the expression e to value v, then checks whether v is the null value. If it is null, an error is thrown. If not, then e! also evaluates to v.
The static type of an expression e! is (basically) the static type of e with any trailing ?s remove. So, if e has type int?, the type of e! is int.
You should not use e! unless e can be null (the type of e is potentially nullable).
The ! operator is dynamically checked. It can throw at runtime, and there is no static check which can guarantee that it won't. It's like using a value with type dynamic in that all the responsibility of preventing it from throwing is on the author, the compiler can't help you, and you need good tests to ensure that it won't throw when it's not supposed to.
It's called an assertion because it should never throw in production code.
So, use e! when you know (for some reason not obvious to the compiler, perhaps because of some invariant guaranteeing that the value is not null while something else is true) that e is not null.
Example:
abstract class Box<T extends Object> {
  bool hasValue;
  T? get value;
}
...
  Box<int> box = ...;
  if (box.hasValue) {
    var value = box.value!;
    ... use value ...
  }

If you are repeatedly using ! on the same expression, do consider whether it's more efficient to read it into a local variable just once.
Also, if (like this Box example) the value being null is equivalent to the other test you just did, maybe just check that directly:
  Box<int> box = ...;
  var value = box.value;
  if (value != null) {
    ... use value ...
  }

This code, with an explicit != null check on a local variable, is statically guaranteed to not throw because the value is null.
The code using ! above relies on the author to maintain whichever invariant allowed them to write the !, and if something changes, the code might just start throwing at runtime. You can't tell whether it's safe just by looking at the code locally.
Use ! sparingly, just like the dynamic type and late declarations, because they're ways to side-step the compiler's static checking and ensure it that "this is going to be fine". That's a great feature when you need it, but it's a risk if you use it unnecessarily.


text:
Q: Selenium C#: Is there a way to wait for loading overlay to hide before proceeding? So I've been creating different explicit waits after doing tasks like updating contact info, submitting forms, etc because every time I do this, a loading overlay will pop up for a few seconds. I just realized it's the same exact loading code on each page. Instead of waiting for results to show on the page or something else to appear, I just want to wait for this loading overlay to hide. Is it possible to write some reusable code to wait for this overlay to hide before proceeding?
The overlay code:

When the loading display is present, the div attributes will become:

A: If your version of .net supports ExpectedConditions, you can straight away use the below solution
var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.XPath("//div[@id='progress']")));

If it does not support then the below solution may work.
//returns as soon as element is not visible, or throws WebDriverTimeoutException
protected void WaitUntilElementNotVisible(By searchElementBy, int timeoutInSeconds)
{
    new WebDriverWait(_driver, TimeSpan.FromSeconds(timeoutInSeconds))
                    .Until(drv => !IsElementVisible(searchElementBy));
}

private bool IsElementVisible(By searchElementBy)
{
    try
    {
        return _driver.FindElement(searchElementBy).Displayed;

    }
    catch (NoSuchElementException)
    {
        return false;
    }
}

and use it like this :
WaitUntilElementNotVisible(By.Id("progress"), 10);


text:
Q: Presentation of an object in an Eilenberg Moore category by generators and relations Let $\cal C$ be a category and let $T \colon \cal C \longrightarrow C$ be a monad. An $T$-algebra $A$ is presented by generators $G \in \cal C$ and relations $R \in \cal C$ if it is the coequaliser of two morphisms $TR \longrightarrow TG$. See here for more information. Unfortunately, the site does not go into much detail.
I am a bit confused about how this works in practice though. For example, consider the group
$$
A = \langle x,y,z \mid xy=yx \rangle
$$
Let $G = \{x,y,z\}$ and let $R = \{ * \}$ be a singleton. Let $F \colon \mathsf{Set} \longrightarrow \mathsf{Set}$ be the free group monad. Define $s(*) = xy \in FG$ and $t(*) = yx \in FG$. Then $s,t$ extend to group homomorphisms $FR \longrightarrow FG$, and I think that $A$ is the coequaliser of these.
Is that the correct way to think of this?


text:
Q: Set encryption per parameter i'm new to T-SQL and i got the following question:
Is it possible to set the encryption per parameter? Something like this: (pseudo code)
create or alter procedure [db].[my_new_proc]
   @Parameter1 int
   @Parameter2 int
   @ParEncryptYN bit

if @ParEncryptYN = 1
  AS
else
  WITH ENCRYPTION AS
end
begin
...
end

I know that i can't use if there, thats why i'm asking.
Any help is appreciated. Thanks.

A: Following OP's explanation that they are looking for a way to protect the T-SQL in their SPs when deployed in client environments, the problem can be clarified.
There is no way to control whether a SP is encrypted using a parameter to the SP.  This is because the SP is encrypted when it is created not when it is executed.
A simple approach that allows SPs to be altered in development but protected in production is to simply create the SPs without encryption in development, and with encrytpion in production.
For example, in your development environment:
CREATE PROCEDURE [db].[my_new_proc]
   @Parameter1 int
   @Parameter2 int
AS
BEGIN
    ...
END

In your production environment:
CREATE PROCEDURE [db].[my_new_proc]
   @Parameter1 int
   @Parameter2 int
  WITH ENCRYPTION
AS
BEGIN
    ...
END


text:
Q: How does PIP determine the version of a dependency of multiple dependents Let's assume we have the following dependency tree in Python using PIP as package installer:
A==1.2.1:
|  - B==1.5.4
|  - C==?.?.?

D==1.3.0:
|  - C==?.?.?

Let's also assume that the existing versions of package C are the followings:
- 0.0.8
- 1.0.2

As we know, PIP will not install different versions of the same package into an environment. Which means it has to pick one suitable version for all dependents.
What I simply cannot understand how PIP determines the suitable version.
If package A depends on C==0.0.8 and package D depends on C==1.0.2, this situation cannot get easily handled, unlike other package managers such as NPM could do.

A:
When pip installs a package, it automatically installs any dependent Python packages without checking if these conflict with previously installed packages. It will install a package and any of its dependencies regardless of the state of the existing installation. Because of this, a user with a working installation of, for example, Google Tensorflow, can find that it stops working having used pip to install a different package that requires a different version of the dependent NumPy library than the one used by Tensorflow. In some cases, the package may appear to work but produce different results in detail.

Anaconda (Python distribution) - Wikipedia

A: On this topic, things will change relatively soon. Since pip's developers are currently working on a new dependency resolver:

*

*https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html

To test it today, you might want to install pip 20.2b1 and enable the unstable feature "resolver", with for example either one of the following:

*

*PIP_UNSTABLE_FEATURE=resolver python -m pip install SomeProject

*python -m pip --unstable-feature=resolver install SomeProject
See the following link for more details:

*

*https://discuss.python.org/t/announcement-pip-20-2b1-release/4242

Other references:

*

*http://www.ei8fdb.org/thoughts/2020/05/test-pips-alpha-resolver-and-help-us-document-dependency-conflicts/

*https://pradyunsg.me/blog/2020/03/27/pip-resolver-testing/

*https://www.pythonpodcast.com/pip-resolver-dependency-management-episode-264/

Update pip 20.2

*

*https://pythoninsider.blogspot.com/2020/07/upgrade-pip-20-2-changes-20-3.html


text:
Q: MATLAB Make Matrices same size In MATLAB, I have five single matrices representing joint skeletal data I have collected from a Kinect sensor. Each matrice is roughly 240-270 x 3 in size (each contains x,y,z data for that joint). I am trying to combine all these joints into one matrix, so I can filter the results.
X = [J1 J2 J3 J4 J5]
The trouble is each matrix is not the same size so at the moment I get an error trying to combine the data.
I want to be able to combine these matrices but make them the same size. I cannot remove the first few lines as they are time synced, and so the first coordinate of each joint was captured at the same time. I would like to, however, calculate the size of the smallest matrix and reshape the others to that size, by removing the last rows in the matrices so that I don't lose important data.
Is this possible to do?

A: Yes it's possible.  Do exactly as you said.  Find the matrix that has the smallest amount of rows and make sure that you extract up to this row index for each of the other matrices, then piece them all together:
You have 5 separate matrices and so finding the row size of each then finding the minimum is a lot of code.  I would place all of the matrices in a cell array, then make a call to cellfun to find the size of each row in one go, then do what I said above:
%// Build cell array of all matrices
J = {J1, J2, J3, J4, J5};

%// Find rows of all matrices
rows = cellfun(@(x) size(x,1), J);

%// Find the smallest amount of rows
min_row = min(rows);

%// Create a new matrix that ensures that we only sample up to that many
%// rows for each matrix
X = cell2mat(cellfun(@(x) x(1:min_row,:), J, 'uni', 0);

The last cellfun call is different from the first one because what is being output is a set of matrices instead of a set of singular values.  Therefore, you have to set the 'uni=0' flag to let MATLAB know that the output won't be singular values anymore.  Instead, each truncated matrix will be in its own cell and so to piece all of the cells together, you need to use cell2mat to finish things off.


text:
Q: Get the external IP address in shell without dig in 2016? This question:  "How can I get my external IP address in bash?"
Solves the question with a call to dig:
dig +short myip.opendns.com @resolver1.opendns.com;

that is the fastest resolution possible, as it involves a single udp packet.
However, that is only one site: OpenDNS, Is there any alternative?
And, makes use of dig, that is not available by default.
Again, Is there an alternative?

Note: I needed to solve this problem as the OpenDNS service didn't work locally due to a (also local) redirect of port 53. I finally found out the reason (I had forgotten about the redirect). First, by using this command to find if dnssec is working (locally missing ad flag):
dig pir.org +dnssec +multi

And also using this command to find out if your ISP is redirecting OpenDNS resolutions:
host -t txt which.opendns.com 208.67.220.220

If being redirected, you will get an answer of: "I am not an OpenDNS resolver."

A: I've concluded that many of these items are beacons that can identify you to somebody sniffing your network traffic and/or the service you are requesting this information from.
I recommend an HTTPS query to a service that preserves your privacy:
wget -qqO- 'https://duckduckgo.com/?q=what+is+my+ip' \
  | grep -Pow 'Your IP address is \K[0-9.]+'

(In the event you're on an embedded or other limited system and don't have grep -P (libpcre), use … | grep -ow 'Your IP address is [0-9.]*[0-9]' | grep -ow '[0-9][0-9.]*'  instead).
If you (and/or others on your IP) don't use the privacy-conscientious DuckDuckGo search engine, then perhaps even that is a beacon (though your query is itself indecipherable to a third party, perhaps the fact that there was any query is too much?).  You can do the same thing with Google, though Google expressly denies access to wget and similar utilities, so you have to forge your User Agent:
wget -U Mozilla/5.0 -qqO- 'https://www.google.com/search?q=what+is+my+ip' \
  | grep -Po '>\K[0-9.]{7,}(?=<.{0,99}>Your public IP)'

This may violate Google's terms of use.
Presumably, you'll have to change the regex class from [0-9.] to [0-9a-f:] for IPv6.  I don't know what it'll look like if you're dual-stack.

A: An alternative is Google DNS:
myip(){   dig @8.8.8.8 -t txt o-o.myaddr.l.google.com |
          grep "client-subnet" |
          grep -o "\([0-9]\{1,3\}\.\)\{3\}\([0-9]\{1,3\}\)" ;   }

If your system does not have dig, then host will be exactly equivalent:
myip(){   host -t txt o-o.myaddr.l.google.com 8.8.8.8 |
          grep -oP "client-subnet \K(\d{1,3}\.){3}\d{1,3}";   }

Both GNU grep (Perl-like -P) and basic (BRE) regex are shown.
And, of course the original site, will also work.
With dig:
myip(){   dig myip.opendns.com @208.67.220.222  |
          grep "^myip\.opendns\.com\."             |
          grep -o "\([0-9]\{1,3\}\.\)\{3\}\([0-9]\{1,3\}\)"  ; }

And with host:
myip(){   host myip.opendns.com 208.67.220.222  |
          grep -oP "^myip\.opendns\.com.* \K(\d{1,3}\.){3}(\d{1,3})" ; }

The two snippets above will work with any of this four OpenDNS resolver addresses:
echo 208.67.22{0,2}.22{0,2}

If the direct DNS solution fails in the future, use curl to one of this sites (urls):
IFS=$'\n' read -d '' -a urls <<-'_end_of_text_'
api.ipify.org
bot.whatismyipaddress.com/
canhazip.com/
checkip.dyndns.com/
corz.org/ip
curlmyip.com/
eth0.me/
icanhazip.com/
ident.me/
ifcfg.me/
ifconfig.me/
ip.appspot.com/
ipecho.net/plain
ipof.in/txt
ip.tyk.nu/
l2.io/ip
tnx.nl/ip
wgetip.com/
whatismyip.akamai.com/
_end_of_text_

Call an array address like this:
$ i=5; curl -m10 -L "http://${urls[i]}"
116.132.27.203

In some sites https may also work.

A: I use the following:
dig @1.1.1.1 TXT whoami.cloudflare.com +short | tr -d \"

Or, with host:
$ host=whoami.cloudflare.com
$ host -t TXT "$host" 1.1.1.1 | sed -En "s/^$host.+"'"([^"]*)"/\1/p'


text:
Q: module.exports object instance for the rest of the app to use In Node, I have the following function/class which instantiates a logger object that I'd like to use in other functions/classes.
In server.js,
var loggerUtil = require('./utils/logger'),
    logger;

module.exports = function(appInitCb, options) {
    start: function() {
        // Load .env
        dotenv.config({
            silent: true
        });

        // Merge the app configuration with default
        options = _.merge({}, cfgDefaults, options);

        // Create a logger
        logger = loggerUtil.createLogger(options.logger).getLogger();
    },

    logger: logger
};

In main.js,
var server = require('./server');
var logger = require(./server').logger;

server.start({}, {});
logger.info('Hello World');

However, it results in the error TypeError: logger.info is not a function. Im guessing theres something wrong with the way I export. Any help is appreciated.

A: You need to export it like so
module.exports = function(appInitCb, options) {
   return({
     start: ...
     log: ...
   })

}
In your example you are not returning an object which unifies both functions.
You can then require this module like so (thanks @Nivesh):
var server = require('./server')();
server.start();

Update
A better approach would be to create an object and assign it directly to the module without the function:
var server = {
   start: function(){...},
   log: function(){...},
}

module.exports = server;

That way you can:
var server = require('./server');
server.start()
server.log()


text:
Q: packets transmitted, 0 received (no internet connection) on centos 6.6 vps I have centos 6.6 vps server.
When I use command: yum update get error:
Error: Cannot find a valid baseurl for repo: base

when I check for ping and use command: ping -c4 google.com get error:
ping: unknown host google.com

or use ping -c4 62.212.252.84 command get :
4 packets transmitted, 0 received, 100% packet loss, time 12999ms

and
/etc/sysconfig/network-scripts/ifcfg-eth0 is:
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=***.***.***.72
NETMASK=255.255.255.255

/etc/sysconfig/network is:
NETWORKING=yes
NETWORKING_IPV6=yes
HOSTNAME=mohsenvps
GATEWAY=37.59.19.254
IPV6_AUTOCONF=no

also change NETWORKING_IPV6=yes to no but get same result.
and /etc/resolv.conf is
nameserver 8.8.8.8
nameserver 8.8.4.4

**Edit: **
and iptables:
target     prot opt source               destination
ACCEPT     icmp --  0.0.0.0/0            202.54.10.20         icmptype 0 state RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 0
ACCEPT     icmp --  202.54.10.20         0.0.0.0/0            icmptype 8 state NEW,RELATED,ESTABLISHED

A: Okay so let's try to find whats going on :

*

*You can ping external IP address

*You cannot ping Domain name

My guess : DNS issue.
Maybe you should check whats inside /etc/resolv.conf to check nameserver ?
Another technique can be traceroute to find where packet is dropped ?
You should use TCPdump to get deeper information about DNS request and other things ?


text:
Q: Pegar data de inicio e de fim de uma semana do mês Boa tarde, pessoal.
Hoje estou com um problema em pegar a data inicial e final de uma semana do mês. Vamos por partes:
Eu tenho uma combo que me traz as semanas de um mês postado. Pra saber quantas semanas eu tenho em Janeiro de 2015, por exemplo, eu uso o seguinte SQL:
SELECT theLast - theFirst + 1 AS Semanas
FROM (
    SELECT 1 + Number AS theMonth,
    DATEDIFF(DAY, -1, DATEADD(MONTH, Number, DATEADD(YEAR, 2015 - 1900, 0))) / 7 AS theFirst,
    DATEDIFF(DAY, -1, DATEADD(MONTH, Number, DATEADD(YEAR, 2015 - 1900, 30))) / 7 AS theLast
    FROM master..spt_values
    WHERE Type = 'P' AND Number < 12
) AS d
WHERE d.theMonth = 01

Até este ponto ok, bem tranquilo. Retornou 5 semanas. O problema está em encontrar o início e o fim de uma semana. Por exemplo, se eu postar semana = 03 e mês = 01, deverá me mostrar '2015-01-11' como inicial e '2015-01-17' como final.
Alguém tem ideia de como fazer isso?

A: No fórum da Microsoft, me deram uma solução:
declare @MêsAno varchar(7), @Dia1 DATE, @Id INT = 1;

set @MêsAno = '1/2015';  --< mês/ano, sem espaços

set @Dia1= Convert(date, '1/' + @MêsAno, 103);

set DateFirst 7;

declare @InicioSemana date, @FinalSemana date;

set @InicioSemana= DateAdd(day, 1 - DatePart(weekday, @Dia1), @Dia1);

set @FinalSemana= DateAdd(day, +6, @InicioSemana);

while Month(@InicioSemana) = Month(@Dia1) or Month(@FinalSemana) =
Month(@Dia1)
  begin
    SELECT @Id, @InicioSemana, @FinalSemana;
    set @InicioSemana= DateAdd(day, +7, @InicioSemana);
    set @FinalSemana= DateAdd(day, +6, @InicioSemana);
    set @Id = @Id+1;
  END;

A: O seguinte comando pega a primeira segunda-feira do mês:
SELECT @PrimeiraSegundaFeira = DATEADD(WEEK, DATEDIFF(WEEK, 0,
    DATEADD(DAY, 6 – DATEPART(DAY, GETDATE()), GETDATE())), 0)

A segunda-feira da terceira semana pode ser obtida assim:
SELECT @TerceiraSegundaFeira = DATEADD(WEEK, 2, @PrimeiraSegundaFeira)

A sexta-feira da terceira semana pode ser obtida assim:
SELECT @TerceiraSextaFeira = DATEADD(DAY, 5, @TerceiraSegundaFeira)


text:
Q: Getting error 'Compile error in hidden module: CTDConn' when opening and closing Excel Whenever I am opening or closing MS Excel I get the following error

Compile error in hidden module: CTDConn

I tried the suggestions listed in this link but it didn't work.

*

*Pdfmaker.dot/Pdfmaker.xla is not present in my AppData

*I have McAfee

I don't get this error on other MS Office programs like Word or PowerPoint. I am using MS Office Professional Plus 2010.
How can I get rid of this error?

A: From this link (thanks duDE) I discovered that this issue is because of ALM. I unistalled ALM and the error is gone.


text:
Q: django development server, how to stop it when it run in background? I use a Cloud server to test my django small project, I type in manage.py runserver and then I log out my cloud server, I can visit my site normally, but when I reload my cloud server, I don't know how to stop the development server, I had to kill the process to stop it, is there anyway to stop the development?

A: Try this
lsof -t -i tcp:8000 | xargs kill -9

A: well it seems that it's a bug that django hadn't provided a command to stop the development server . I thought it have one before~~~~~

A: Ctrl+c should work.  If it doesn't Ctrl+/ will force kill the process.

A: One liner..
pkill -f runserver

A: As far as i know ctrl+c or kill process is only ways to do that on remote machine.
If you will use Gunicorn server or somethink similar you will be able to do that using Supervisor.

A: We can use the following command.

-> netstat -ntlp

then we will get number of process running with PID, find our python server PID and Kill process.

-> kill -9 PID

For example:

A: The answer is findable via Google -- and answered in other forums. Example solution is available on the Unix & Linux StackExchange site.
To be explicit, you could do:
ps auxw | grep runserver

This will return the process and its respective PID, such as:
de        7956  1.8  0.6 540204 55212 ?        Sl   13:27   0:09 /home/de/Development/sampleproject/bin/python ./manage.py runserver

In this particular case, the PID is 7956. Now just run this to stop it:
kill 7956

And to be clear / address some of the comments, you have to do it this way because you're running the development server in the background (the & in your command). That's why there is no "built-in" Django stop option...

A: From task manager you can end the python tasks that are running.
Now run python manage.py runserver from your project directory and it will work.

A: This worked for me on windows.
Use the below command to list all connections and listening ports (-a) along with their PID (-o).
netstat -a -o

Find the PID of the process
Then use this to kill the process
taskkill /PID PUT_THE_PID_HERE /F

A: Programmatically using a .bat script in Command Prompt in Windows:
@ECHO OFF
SET /A port=8000
FOR /F "tokens=5" %%T IN ('netstat -ano ^| findstr :%port%') DO (
    SET /A processid=%%T
    TASKKILL /PID %%T /F
)

gives
SUCCESS: The process with PID 5104 has been terminated.

A: You can Quit the server by hitting CTRL-BREAK.


text:
Q: Cannot get a user function to co-operate with a subquery in mariadb The following is a demo of an issue we are having with a function and a subquery. I'm interested to know if it is a bug or if there is a reasonable explaination why it is failing.
Notes:

*

*Problem only in MariaDB, not in MySQL.

*We are using version 10.3.13 of MariaDB.

*Issue shows in both Gentoo and Debian distros.

*If a constant is used instead of the function, it behaves.

*If a list is used instead of the subquery, it behaves.

*In our testing on the real application, multiple JOINs (with or without LEFT) also broke the query.

Why is the JOIN affecting the result at all?
USE `test`;
DROP FUNCTION IF EXISTS `pastPosition`;
DELIMITER $$
USE `test`$$
CREATE FUNCTION `pastPosition`(`who` INT(11), `when` DATE) RETURNS int(11)
BEGIN
    DECLARE `result` int(11);
    SELECT `position_id` INTO `result`
        FROM `position_history`
        WHERE `when`>=`from` AND `when`<=`to` AND `employee_id`=`who`;
    RETURN `result`;
END$$
DELIMITER ;

CREATE TEMPORARY TABLE `employee` (
    `id` INT(11) UNSIGNED NOT NULL,
    `name` VARCHAR(50) NOT NULL,
    `division_id` INT(11) UNSIGNED NOT NULL
);
INSERT INTO `employee` VALUES
    (1, 'Mrs Robinson', 2),
    (2, 'Joe DiMaggio', 2),
    (3, 'Paul Simon', 1),
    (4, 'Art Garfunkel', 1)
;

CREATE TEMPORARY TABLE `position` (
    `id` INT(11) UNSIGNED NOT NULL,
    `position_name` VARCHAR(50) NOT NULL,
    `is_management` TINYINT(1) NOT NULL
);
INSERT INTO `position` VALUES
    (1, 'Grand Poobah', 1),
    (2, 'Average Poobah', 1),
    (3, 'Serf', 0)
;

CREATE TEMPORARY TABLE `position_history` (
    `from` DATE NOT NULL,
    `to` DATE NOT NULL,
    `employee_id` int(11) NOT NULL,
    `position_id` int(11) NOT NULL
);
INSERT INTO `position_history` VALUES
    ('1972-01-01','1988-12-31', 3, 1),
    ('1972-01-01','1988-12-31', 4, 1),
    ('1972-01-01','1988-12-31', 1, 2),
    ('1972-01-01','1988-12-31', 2, 3)
;

CREATE TEMPORARY TABLE `division` (
    `id` INT(11) UNSIGNED NOT NULL,
    `name` VARCHAR(50) NOT NULL
);
INSERT INTO `division` VALUES
    (1, 'Songwriter'),
    (2, 'Song Character')
;

SELECT '  employees in management in 1980:' AS 'WITH_LEFT_JOIN';
SELECT *
    FROM `employee`
    LEFT JOIN `division` ON `employee`.`division_id` = `division`.`id`
    WHERE pastPosition(`employee`.`id`, '1980-01-01') IN
        (SELECT `id` FROM `position` WHERE `is_management`=1);

SELECT '  employees in management in 1980:' AS 'WITH_JOIN';
SELECT *
    FROM `employee`
    JOIN `division` ON `employee`.`division_id` = `division`.`id`
    WHERE pastPosition(`employee`.`id`, '1980-01-01') IN
        (SELECT `id` FROM `position` WHERE `is_management`=1);

results on mysql, (working):
WITH_LEFT_JOIN
  employees in management in 1980:
id      name    division_id     id      name
1       Mrs Robinson    2       2       Song Character
3       Paul Simon      1       1       Songwriter
4       Art Garfunkel   1       1       Songwriter
WITH_JOIN
  employees in management in 1980:
id      name    division_id     id      name
1       Mrs Robinson    2       2       Song Character
3       Paul Simon      1       1       Songwriter
4       Art Garfunkel   1       1       Songwriter

results on mariadb, (not working):
WITH_LEFT_JOIN
  employees in management in 1980:
WITH_JOIN
  employees in management in 1980:
id      name    division_id     id      name
1       Mrs Robinson    2       2       Song Character
3       Paul Simon      1       1       Songwriter
4       Art Garfunkel   1       1       Songwriter

Here is the EXPLAIN SELECT outputs:
LEFT JOIN
MySQL (working):
+----+--------------------+----------+------+---------------+------+---------+------+------+-------------+
| id | select_type        | table    | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+--------------------+----------+------+---------------+------+---------+------+------+-------------+
|  1 | PRIMARY            | employee | ALL  | NULL          | NULL | NULL    | NULL |    4 | Using where |
|  1 | PRIMARY            | division | ALL  | NULL          | NULL | NULL    | NULL |    2 | Using where |
|  2 | DEPENDENT SUBQUERY | position | ALL  | NULL          | NULL | NULL    | NULL |    3 | Using where |
+----+--------------------+----------+------+---------------+------+---------+------+------+-------------+

Maridb (non-working):
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+
| id   | select_type  | table       | type   | possible_keys | key          | key_len | ref  | rows | Extra                                           |
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+
|    1 | PRIMARY      | employee    | ALL    | NULL          | NULL         | NULL    | NULL |    4 |                                                 |
|    1 | PRIMARY      | <subquery2> | eq_ref | distinct_key  | distinct_key | 4       | func |    1 | Using where                                     |
|    1 | PRIMARY      | division    | ALL    | NULL          | NULL         | NULL    | NULL |    2 | Using where; Using join buffer (flat, BNL join) |
|    2 | MATERIALIZED | position    | ALL    | NULL          | NULL         | NULL    | NULL |    3 | Using where                                     |
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+

{
  "query_block": {
    "select_id": 1,
    "table": {
      "table_name": "employee",
      "access_type": "ALL",
      "rows": 4,
      "filtered": 100
    },
    "table": {
      "table_name": "<subquery2>",
      "access_type": "eq_ref",
      "possible_keys": ["distinct_key"],
      "key": "distinct_key",
      "key_length": "4",
      "used_key_parts": ["id"],
      "ref": ["func"],
      "rows": 1,
      "filtered": 100,
      "attached_condition": "pastPosition(employee.`id`,'1980-01-01') = position.`id`",
      "materialized": {
        "unique": 1,
        "query_block": {
          "select_id": 2,
          "table": {
            "table_name": "position",
            "access_type": "ALL",
            "rows": 3,
            "filtered": 100,
            "attached_condition": "position.is_management = 1"
          }
        }
      }
    },
    "block-nl-join": {
      "table": {
        "table_name": "division",
        "access_type": "ALL",
        "rows": 2,
        "filtered": 100
      },
      "buffer_type": "flat",
      "buffer_size": "256Kb",
      "join_type": "BNL",
      "attached_condition": "trigcond(pastPosition(employee.`id`,'1980-01-01') = position.`id`) and trigcond(division.`id` = employee.division_id)"
    }
  }
}

JOIN
MySQL (working):
+----+--------------------+----------+------+---------------+------+---------+------+------+--------------------------------+
| id | select_type        | table    | type | possible_keys | key  | key_len | ref  | rows | Extra                          |
+----+--------------------+----------+------+---------------+------+---------+------+------+--------------------------------+
|  1 | PRIMARY            | division | ALL  | NULL          | NULL | NULL    | NULL |    2 |                                |
|  1 | PRIMARY            | employee | ALL  | NULL          | NULL | NULL    | NULL |    4 | Using where; Using join buffer |
|  2 | DEPENDENT SUBQUERY | position | ALL  | NULL          | NULL | NULL    | NULL |    3 | Using where                    |
+----+--------------------+----------+------+---------------+------+---------+------+------+--------------------------------+

MariaDB (working):
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+
| id   | select_type  | table       | type   | possible_keys | key          | key_len | ref  | rows | Extra                                           |
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+
|    1 | PRIMARY      | division    | ALL    | NULL          | NULL         | NULL    | NULL |    2 |                                                 |
|    1 | PRIMARY      | employee    | ALL    | NULL          | NULL         | NULL    | NULL |    4 | Using where; Using join buffer (flat, BNL join) |
|    1 | PRIMARY      | <subquery2> | eq_ref | distinct_key  | distinct_key | 4       | func |    1 | Using where                                     |
|    2 | MATERIALIZED | position    | ALL    | NULL          | NULL         | NULL    | NULL |    3 | Using where                                     |
+------+--------------+-------------+--------+---------------+--------------+---------+------+------+-------------------------------------------------+

{
  "query_block": {
    "select_id": 1,
    "table": {
      "table_name": "division",
      "access_type": "ALL",
      "rows": 2,
      "filtered": 100
    },
    "block-nl-join": {
      "table": {
        "table_name": "employee",
        "access_type": "ALL",
        "rows": 4,
        "filtered": 100
      },
      "buffer_type": "flat",
      "buffer_size": "256Kb",
      "join_type": "BNL",
      "attached_condition": "employee.division_id = division.`id`"
    },
    "table": {
      "table_name": "<subquery2>",
      "access_type": "eq_ref",
      "possible_keys": ["distinct_key"],
      "key": "distinct_key",
      "key_length": "4",
      "used_key_parts": ["id"],
      "ref": ["func"],
      "rows": 1,
      "filtered": 100,
      "attached_condition": "pastPosition(employee.`id`,'1980-01-01') = position.`id`",
      "materialized": {
        "unique": 1,
        "query_block": {
          "select_id": 2,
          "table": {
            "table_name": "position",
            "access_type": "ALL",
            "rows": 3,
            "filtered": 100,
            "attached_condition": "position.is_management = 1"
          }
        }
      }
    }
  }
}

A: This has been confirmed as a bug:
Unrelated JOINs corrupt usage of 'WHERE function() IN (subquery)'


text:
Q: Using style of EXT JS buttons for basic HTML button I'm using an HTML basic button in an EXT JS application.
For a specefic need, i was forced to use an HTML basic button. My problem is that i want to use the same style of EXTJS button (The component Ext.button.Button with all 'special' style events like : on click, on hover ...)
Is there any way to do it like this : tired some think like :
<input type="button" class="myEXTJSButtonStyle" value="Chargement" id="id"/>

A: In Google Chrome, right click thee ExtJS button and select Inspect Element. From there you will see all the styles that had been applied to it. You can then copy them to your own stylesheet.


text:
Q: Can $\frac{\csc \alpha +\cos \alpha}{\cos \alpha - \tan \alpha - \sec \alpha}$ be simplified? I am trying to simplify the following but I cannot.
$$
\frac{\csc \alpha +\cos \alpha}{\cos \alpha - \tan \alpha - \sec \alpha}
$$
Can it be simplified?
Edit
My last result is
$$
- \frac{\cos \alpha \left( 1 + \sin \alpha \cos \alpha\right)}
{\sin^2 \alpha \left(1+\sin \alpha\right)}
$$
I am wondering it might be a wrong question given by my student's teacher.

A: If you multiply the numerator and denominator of your last expression by $4(1-\sin\alpha)$ and use the identity $\sin2\alpha=2\sin\alpha\cos\alpha$, you can rewrite your result as $$(1-\csc\alpha)(2\csc2\alpha+1).$$ This reduces the original 24 symbols to 17.

A: First, let us state of the fundamentals.
$$\csc \alpha = \frac{1}{\sin \alpha};\ \tan \alpha = \frac{\sin \alpha}{\cos \alpha};\ \cot \alpha = \frac{\cos\alpha}{\sin \alpha};\ \sec \alpha = \frac{1}{\cos \alpha};\ \sin^2\alpha + \cos^2\alpha = 1;$$
So,
$$\frac{\csc \alpha +\cos \alpha}{\cos \alpha - \tan \alpha - \sec \alpha} \cdot 1= \frac{\frac{1}{\sin \alpha} + \cos \alpha}{\cos \alpha - \frac{\sin\alpha}{\cos\alpha} - \frac{1}{\cos\alpha}} \cdot\frac{\cos \alpha}{\cos \alpha} = \frac{\cot \alpha + \cos^2\alpha}{\cos^2\alpha - \sin\alpha - 1} = \frac{\cot\alpha + 1 -\sin^2\alpha}{1-\sin^2\alpha - \sin\alpha - 1} = \frac{\cot\alpha + 1 -\sin^2\alpha}{\left(0-\sin\alpha\right)\cdot\left(1+\sin\alpha\right)}\cdot\frac{\sin\alpha}{\sin\alpha} = \frac{\cos\alpha + \sin\alpha - \sin^3\alpha}{- \sin^2\alpha\left(1+\sin\alpha\right)} = -\frac{\cos\alpha + \sin\alpha\cos^2\alpha}{\sin^2\alpha\left(1+\sin\alpha\right)} = - \frac{\cos\alpha\left(1 + \sin\alpha\cos\alpha\right)}{\sin^2\alpha\left(1+\sin\alpha\right)}$$
Alright, a great number of further simplifications are possible from here, but what do you think will eliminate the denominator and bring the order down to one without changing the inner $\alpha$. There are 4 terms and various manipulations left.
You'll see this is actually the simplest you can get it to. It is not trivial to prove this though.


text:
Q: htaccess rewrite logout url I have a url like this
http://example.com/wp-login.php?action=logout&_wpnonce=ab720d18d2

Can someone help me to rewrite like this
http://example.com/logout/ab720d18d2

Thanks

A: We are here to answer question. Not to write code for you.
But because it is almost christmas:
RewriteRule ^logout/(.*) /wp-login.php?action=logout&_wpnonce=$1


text:
Q: GRASS iterate over multiple shapefiles using g.region I have a shapefile called Ahmednagar. I have daily rainfall data from 1997 till 2008. I want to sum total rainfall from 152 till 273 day for each year for 1997 till 2008. This is how I do it.
g.region vect=Ahmednagar  #first set g.region as Ahmednagar
j=1997
while [ $j != 2008 ]
do
    r.mapcalc "tmpsum=0.0"
    i=152                   #start from 152 day of the year
    while [ $i != 274 ]     # till the 273 day of the year
    do
            g.copy rast=prec$j.$i,tmp #copies rainfall of jth year and ith day
            r.mapcalc "tmpsum2 = tmpsum+ tmp"
            r.mapcalc "tmpsum=tmpsum2"
            g.remove rast=tmp
            i=`expr $i + 1`
    done
    g.rename rast=tmpsum,precAhmednagar$j   #rename the tmpsum as the shapefile
    j=`expr $j + 1`
done

This will give me a raster files for each year from 1997 till 2007 called precAhmednagar$j where j is the year.
Now I have many more shapefiles (215 exactly). For each of them I want to do the same thing. But I am not sure how to go about it. Basically set a shapefile using g.region, do all the calculation and most importantly rename the final raster tmpsum as the precXXXX$j where XXXX is the name of the shapefile.
I have imported all the 215 shapefiles in GRASS the list which I can get using g.list vect but that's it.

A: I found a shortcut way to do this. I rename all my 215 shapefiles as numbers appneded with a text (x1.shp, x2.shp, x3.shp...x215.shp) and imported them in GRASS. Than I used this loop to change my g.region:
k=1
while [ $k != 216 ]
do
     g.region vect=x$k
     j=1997
     while [ $j != 2008 ]
     do
          ..............   #rest of the code here
     done
     k=`expr $k + 1`
done

A: You answered yourself quickly, but I'd like to add two comments:
1.To do the loop you asked for, I would just replace the shapefile name with a variable, then go thru all shapefile names and run the script with each. For example (based on your first solution above:
V=$1
g.region vect=${V}  #first set g.region to shapefile
j=1997
  while [ $j != 2008 ]
  do
    r.mapcalc "tmpsum=0.0"
    i=152
      while [ $i != 274 ]
      do
      g.copy rast=prec$j.$i,tmp #copies rainfall of jth year and ith day
      r.mapcalc "tmpsum2 = tmpsum+ tmp"
      r.mapcalc "tmpsum=tmpsum2"
      g.remove rast=tmp
      i=`expr $i + 1`
    done
  g.rename rast=tmpsum,prec${V}${j}
  j=`expr $j + 1`
done

Now put the above into a shell script (i.e. sum_precip.sh) then do
for v in `g.list vect`; do
sum_precip.sh $v
done

*BUT: when you set the region to a shapefile, the region settings cover the whole bounding box of the vector. Consider, for example, the country of Croatia. Since it is "curved" the bounding box will be much larger than the polygon boundary of the country. Then the new raster that is created for that region will also be much larger than the polygon. In the above process you will certainly be getting total precip twice or more for some areas where the rasters are overlapping.

If you have daily rainfall in each shapefile, why do you need to create some intermediate raster at all? I would just import the precip data from all shapefiles into a spatial database, then do a query to total all precip for day numbers between your 152 and 273 interval, for each polygon.


text:
Q: Como Alterar H1 usando Javascript? Eu tenho uma galeria de produtos e o lado existe alguns botões que são as categorias desses produtos (botões: gabinete, monitores, mouse, cadeiras, etc), quando eu clicar nessa categoria, um toggle ativa somente os produtos daquela categoria específica.
No entanto, eu quero que acima desses produtos contenha um título que inicialmente será assim: "Produtos" (esse é o padrão), mas quando eu clicar na categoria Gabinete, por exemplo, esse título será alterado para "Gabinetes". Deu pra entender?
Pois bem, eu quero que isso aconteça com todos os outros botões sempre alterando o título em tempo de execução.
Eu até tentei criar uma function ao clicar usando GetElementById junto com uma IF ELSE, mas ele aplica a primeira validação apenas.
Alguém que já fez algo parecido poderia me ajudar?
Importante: Eu estou pegando os botões do banco de dados, simplesmente eu fiz uma instrução WHILE que vai repetir os botões de acordo com a quantidade de categorias cadastradas no banco de dados, então não tem assim logo de cara, como adicionar uma função diferente para cada botão. Tem como, mas não tão facilmente.

A: Veja se isto é o que você precisa:

Produtos

Nonononononono nonono nonono.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

<select id="s" onchange="esse_mudou(this.value)">
  <option>Produtos</option>
  <option>Gabinetes</option>
  <option>Sabonete líquido</option>
  <option>Ração para cágados</option>
  <option>Buzina de calhambeque</option>
</select>

<button onclick="botao_clicado(this)">Produtos</button>
<button onclick="botao_clicado(this)">Gabinetes</button>
<button onclick="botao_clicado(this)">Sabonete líquido</button>
<button onclick="botao_clicado(this)">Ração para cágados</button>
<button onclick="botao_clicado(this)">Buzina de calhambeque</button>

A: Uma alternativa usando Jquery

$(".btn").click(function(){
    var name = $(this).text();
    $("#meuh1").html(name);
});

Produtos

<button class=btn>Gabinetes</button>

<button class=btn>Processadores</button>

<button class=btn>Discos Rígidos</button>

<button class=btn>Memórias RAM e ROM</button>

text()- retorna o texto do elemento
$(this)

*

*$() é a função construtora do jQuery.

*this é uma referência ao elemento DOM invocado.

*Então em $(this) você está passando this para a função $() como parâmetro, no caso em questão o texto do elemento text()

Mudando o H1 e apresentando o texto correspondente

$(".btn").click(function(){
    $('div[id^="div_"]').hide();
    var name = $(this).text();
    $("#meuh1").html(name);
    var id = $(this).attr('id');
    $("#div_"+id).show();
});

Produtos

<button id="bt1" class=btn>Gabinetes</button>

<button id="bt2" class=btn>Processadores</button>

<button id="bt3" class=btn>Discos Rígidos</button>

<button id="bt4" class=btn>Memórias RAM e ROM</button>

Gabinetes de várias marcas e modelos

Processadores de última geração

Discos Rígidos de até 4MB, rs :)

Memórias RAM e ROM


text:
Q: Correct way to add references to C# project such that they are compatible with version control When adding either 3rd party libraries or internally developed ones to a C# project, I usually just add the reference in the Visual Studio solution browser. However, this creates an absolute path reference to the library. When another developer on a different computer checks out the code, they probably won't have those libraries in those exact folder locations.
Where do you put your 3rd party libraries? suggests that 3rd party libraries should be kept in a folder inside the solution folder (i.e. the repository folder). This makes sense to me. However, when I add the references they are still absolute path references. Changing C# .dll references from absolute to relative offers a solution to this, however, is manually editing the .csproj file really the way to go? I've read that it is not recommended to mess around with the .csproj file. Also, I see in the comments to that question that if your library is not above the project folder (so in my case I created a dependencies folder inside the project folder, not the solution folder), then VS should make the path reference relative by default but that did not happen in my case.
Then there is the question about internally developed libraries. In my case I have a utilities project that has functions I need to use across multiple solutions. I would prefer not to have to manually update the library in each project that relies on it. This is not a problem if I use absolute paths to the reference but then what happens with using version control? In the first question I linked to, one of the lower down answers suggests using a program called Sync Toy to make sure that the library gets copied into all the projects that reference it's dependencies folder. Is that a sensible way to go?
Lastly, and this last point may be too unrelated to fit in the same question, when I add the reference, but default it coies the library to the output directory on building. But that means when I deploy the project I have to copy all those additional dll files. Is there a way to avoid this and embed the library into the output .exe?

A: Reference path, absolute or relative?
When you add a reference through References > Add Reference > Browse > Browse… Visual Studio will save the relative path to the library in the .csproj.
However, if you look at the reference properties in the Properties window Visual Studio will show you the absolute path to the library (I don't know why someone thought it would be a good idea to do it):

This has been tested in Visual Studio 2008 and 2015.
Common library, how can I share it?
If you have a common library you need to share between solutions (not projects) I recommend, if possible, to create your own NuGet feed and leverage that.
You probably want a Remote Feed, not a Local Feed; there are many tools to create and maintain one (e.g. TeamCity).
The library is updated? Push it to your internal NuGet server and enjoy the updates.
Moving assemblies around

when I add the reference, but default it coies the library to the output directory on building

Well, that's how it works in .NET.

that means when I deploy the project I have to copy all those additional dll files. Is there a way to avoid this and embed the library into the output .exe?

While merging everything is possible (check ILMerge), I don't recommend it, it's not worth the hassle, because:
If you have to manually copy things around to deploy, you're doing it wrong. You should create a script or an installer (depending on the project type and what you have to do) to move the deployed application around as a whole.


text:
Q: getClass() returning java.lang.Class [Reflection] So upon getting the parameter(s) for a method via Reflection:
Class<?>[] params = m.getParameterTypes();

And assuming I'm looping through methods and looking for a method with only one parameter:
if(params.length > 1) {
     continue;
}

Then getting that parameter if the length of the params array is 1:
Class<?> par = params[0];

When I try printing out the parameter's class with the getClass() method, it returns java.lang.Class.
However, when I get the superclass with the getSuperclass() method, it returns the superclass.
So for example:
System.out.println(par.getClass());
System.out.println(par.getSuperclass());

Assume the parameter of the method we have is a class called "PlayerDeathEvent", which extends the abstract "Event" class.
That being said, the output would be:
java.lang.Class
org.mypackage.Event

Is there a reason why this is occurring? I found a way around this with getCanonicalName, but I'm very curious as to why this occurs.

A: The getClass() method is a method in Object that returns the Class object for the instance.  You have a Class object, so getClass() returns the Class object for the Class class -- a different Class than what par is an instance of.
However, the getSuperclass() method, defined in Class, returns the Class object for the superclass of the class, not of the Class returned by getClass().
To get PlayerDeathEvent, call getName() instead.
System.out.println(par.getName());

A: par is a object of Class here:
Class<?> par = params[0];

getClass is from java.lang.Object. It returns the class (type) of the object.
So if s is a String
String s = "test";

s.getClass returns String".
By the same logic, par.getClass() returns Class.
getSuperClass, on the other hand, is defined java.lang.Class which returns the superclass of the class being represented.
So if s is a String, and c is a class that holds the reflective Class:
String s = "test";
Class c = s.getClass();

s.getClass returns String
c.getSuperClass returns Object because Object is Strings super class
c.getName returns String and
c.getClass returns Class

You are probably looking for
getName()


text:
Q: Optimise billing on app engine for continual polling I'm creating a service on appengine that feeds back measurements to the user. The measurements are collected by polling another server every fifteen minutes (the user needs four measurements over the last hour). The other sever replies with the data immediately so this isn't a "long poll request". I don't expect there to be a high load on the server because there aren't a lot of users (maybe 20 requests a day or so) so there won't be many requests coming in for the data, but because the user needs data over the last hour I am forced to poll continuously. This makes me concerned about billing because the new billing system charges per instance hour at a 15 min granularity and this would mean I'd have an instance actively running 24/7 (as far as I can tell).
Question
So, I expect a low request rate and am not too concerned about latency etc. How can I optomise this setup for the lowest possible billing?
What I had planned
What I was planning to do was try and get away with the free quota for now by setting max idle instance to 1 and only using the frontend to do both polling and serving (I'm guessing site responsivness will suffer a fair amount) because the frontend has far more free instance hours (28) than the backend (9). Can the frontend even be set up to poll every 15 mins?

A: There's nothing you can really tweak here for this. You'll want to use cron or the task queue for the polling anyway; these use frontend instances, not backend instances. As long as you have multithreading enabled, frontend latency will not be affected, and you'll likely remain within your free quota as long as you don't do enough polling or get enough traffic to require more than one concurrent instance.


text:
Q: Serial communication and reading byte arrays with Arduino I am establishing a serial connection with my Arduino. In order to get data from it I have to send data in the form of byte arrays. I am able to send the command and read the ACK. But I can't figure out how to get the data after the ACK.
The developer documentation for the protocol I am using says it goes:
command to access data -> ACK REPONSE ->DATA
I can't figure out how to get the data after the ack response. It should be a byte array of 14 hex values.
This is my code
byte GetData[] = {0x02,0x12,0x00}
byte GetDataACK[] = {0x02,0x06,0x06,0x06,0x06,0x06};

void setup(){

  Serial.begin(9600);
  Serial.write(GetData,sizeof(GetData)); //Send the byte array
  delay(200);
  if(Serial.available() > 5) {
    for(int i=0;i<6;i++){
      if(ackmodule[i]!=Serial.read()){
        // Do something
      }
    }
  }

}

void loop(){

}

A: Shouldn't some of that code be inside of loop()? Specifically, everything but Serial.begin(9600)? Anyway, this code won't work because ackmodule is not defined. Is it supposed to be GetDataACK? It's also a good idea to implement error handling, especially when having to debug, like this:
  if(Serial.available() > 0) {
    received_byte[i] = Serial.read();
    if(received_byte[i++] == -1) {  // no data available
      // error handling
    }
  }

I'm not sure what types the Arduino sketch libraries support, but i can just be an unsigned char (I would call it uint8_t) instead of a full singed 16-bit number (int). As Chris Stratton mentioned, there are better ways to wait for characters; for example the error handling example, or this:
while(Serial.available() < 5) {}; // 5 can be 0 to fetch 1 char at a time

This can be implemented without the library in this form:
char rx()
{
        while ((UCSRA & (1<<RXC)) == 0) {};
        return UDR;
}

... Calling it with something like char nextbyte = rx(). Arduino serial tutorial is here.

A: If you just want to send the command once at startup, and then read the response you want to do this:
byte GetData[] = {0x02,0x12,0x00}
byte GetDataACK[] = {0x02,0x06,0x06,0x06,0x06,0x06};

void setup(){
  Serial.begin(9600);
  Serial.write(GetData,sizeof(GetData)); //Send the byte array
}

void loop(){
  if(Serial.available() > 5) {
    for(int i=0;i<6;i++){
      if(GetDataACK[i]!=Serial.read()){
        // Do something
      }
    }
  }
}

Now I'm not sure what you're trying to accomplish with the inner if statement of loop, but it seems kind of backwards to me. Wouldn't you only want to "do something" after you have successfully read the data Ack? I think what you really want is a little state machine:
#define DATA_LENGTH           14 // or whatever the length of your data segment is

#define STATE_IDLE            0
#define STATE_SEND_COMMAND    1
#define STATE_WAITING_FOR_ACK 2
#define STATE_GET_DATA        3

byte GetData[] = {0x02,0x12,0x00}
byte GetDataACK[] = {0x02,0x06,0x06,0x06,0x06,0x06};
byte RxData[DATA_LENGTH] = {0};
byte state = STATE_SEND_COMMAND;

void setup(){
  Serial.begin(9600);
  state = STATE_SEND_COMMAND;            // redundant
}

void loop(){
  switch(state){
  case STATE_IDLE: break;
  case STATE_SEND_COMMAND:
     Serial.write(GetData,sizeof(GetData)); //Send the byte array
     state = STATE_WAITING_FOR_ACK;
     break;
  case STATE_WAITING_FOR_ACK:
     if(Serial.available() > 5) {
        for(int i=0;i<6;i++){
           if(GetDataACK[i]!=Serial.read()){
           // ACK doesn't match what you expect
           // you should go to some other state at this point
           // i'll just send you to idle
              state = STATE_IDLE;
              break;
           }
        }
     }
     break;
  case STATE_GET_DATA:
     if(Serial.available() > DATA_LENGTH) {
        for(int i = 0; i < DATA_LENGTH; i++){
           RxData[i] = Serial.read();
        }

        // congratulations you have data in your array
        // presumably now you want to something with it

        // and then switch back to some other state
        // i'll send you back to IDLE :)
        state = STATE_IDLE;
        break;
     }
  }
}


text:
Q: Display Popup from script executed as System user I've a scheduled task, executed by System user. It's can sometimes display a popup to interacts with the user. This work fine if I launch the script myself, but not displaying when launched by the scheduled task with system user.
I use Start-Job as the current user to display the popup, but isn't working.
How can I display a popup/msgbox (need to be topmost window) for interacts with user (need to know the pushed button) from a script launched by system account ?

A: You'll need two processes. One for the task, setup with system permissions, and one for the popup, setup with user permissions. When a popup is needed, the task process creates a popup process and they open communications with each other (to pass the popup results if necessary).


text:
Q: Capturing text body within repeated header-footer pattern using C# .NET I am trying to parse a string from a script using C# .NET that appears as such (bolded below are fixed syntax ie SOMEHEADER and END_SOMEHEADER):
Start of script:

SOMEHEADER header1
//some syntax to be added here
END_SOMEHEADER

SOMEHEADER header2
//some syntax to be added here
END_SOMEHEADER

...(and the above pattern will be repeated)...

End of script

"header1" and "header2" in the above example are the names (any alphanumeric characters) for the respective SOMEHEADER. I am actually interested to capture the text body (refer italicized text above) and store them in a collection with header names (ie in this example would be "header1" and "header2") as the key.
I believe that Regex is able to solve the above problem, but I have been struggling to come up with an appropriate regex pattern, and I only managed to come up with this
(?:SOMEHEADER)\s*(?<someheadername>[a-zA-Z0-9._]+)(?<body>(?:.|\n)*)(?:END_SOMEHEADER)

which does not fix the problem.
Appreciate some kind help.

A: ^SOMEHEADER\s*([0-9A-Z._]+)\n*(.+)\n*END_SOMEHEADER
Group 1 gives the header and Group 2 gives the textblock. You can name the groups if you want


text:
Q: J Language for learning math - "Math for the Layman" Working programmer looking for a math refresher or just developing mathematical thinking. Saw J Language http://www.jsoftware.com/jwiki/Books
The book "Math for the Layman" claims that the J language makes math easier to learn by providing interactive tools and simpler notation than conventional math. Can someone confirm this from experience, specifically for learning mathematical thinking? I thought I'd try a programming approach and maybe pick up a new language along the way. If not, I have my text books ready.
Is this worth my time?
Thank you.

A: Learning can never be a waste of time.  I'd say go for it, without knowing anything about J.
The math that I learned was acquired without the benefit of computers.  I have no experience with J, so I can't comment on that.
I personally don't think that a computer language will make you a mathematician.  If you've never taken calculus I don't see how a language or different notation will necessarily make it better or worse.  It needs to have complementary sources to really learn it well.
It may help since you're literate with computers, but the math will still take as long as it takes.  It's one thing to program a Bessel function; it's another to understand the differential equation it comes from, the problems it solves, orthogonality and relationships to other functions, etc.
Linear algebra is one area that greatly benefits from computer analysis.  The rules aren't too difficult, and computers save on the repetitive grunt work.
Another important bit is motivation.  I found that studying something for the sake of solving a particular problem was always important, especially with math.  Knowing how it would help me understand a problem in physics or engineering was a great motivator.  What will your motivation be?


text:
Q: OnClicklistener in RecyclerView I'm trying to get an OnClickListener in my RecyclerView but I can't get it to work.
I try to access the method "setOnItemClickListener" from my Activity.
The method is created in my Adapter:
public class HauptgerichteAdapter extends RecyclerView.Adapter<HauptgerichteAdapter.HauptgerichtViewHolder> {
    private ArrayList<HauptgerichtItem> mHauptgerichtList;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }

and I try to acces it in my Activity in OnCreate :
        mRecyclerView = findViewById(R.id.recyclerViewHauptgerichte);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new HauptgerichteAdapter(Hauptgerichte.this,hauptgerichtList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(Hauptgerichte.this);

But it just marks the setOnItemClickListener red and it says "Cannot resolve method 'setOnItemClickListener' in 'Adapter'".
Heres the full Adapter if that helps anything
package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class HauptgerichteAdapter extends RecyclerView.Adapter<HauptgerichteAdapter.HauptgerichtViewHolder> {
    private ArrayList<HauptgerichtItem> mHauptgerichtList;
    private OnItemClickListener mListener;
    private Context mContext;
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }

    public class HauptgerichtViewHolder extends RecyclerView.ViewHolder{

        public ImageView mImageView;
        public TextView mtitleView;
        public TextView mVegetarischView;
        public TextView mVeganView;
        public TextView mTimeView;

        public HauptgerichtViewHolder(View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.imageViewGericht);
            mtitleView = itemView.findViewById(R.id.textViewtitle);
            mVegetarischView = itemView.findViewById(R.id.textViewTag1);
            mVeganView = itemView.findViewById(R.id.textViewTag2);
            mTimeView = itemView.findViewById(R.id.textViewTime);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mListener != null){
                        int position = getAdapterPosition();
                        if (position!=RecyclerView.NO_POSITION){
                            mListener.onItemClick(position);
                        }
                    }
                    // RecyclerView Tutorial Part 6 2:56
                }
            });
        }
    }
    public HauptgerichteAdapter(Context context,ArrayList<HauptgerichtItem> hauptgerichtList){
        mHauptgerichtList = hauptgerichtList;
        mContext = context;
}
    @NonNull
    @Override
    public HauptgerichtViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.hauptgericht_item,parent,false);
        HauptgerichtViewHolder hvh = new HauptgerichtViewHolder(v);

        return hvh;
    }

    @Override
    public void onBindViewHolder(@NonNull HauptgerichtViewHolder holder, int position) {
    HauptgerichtItem currentItem = mHauptgerichtList.get(position);

    holder.mImageView.setImageResource(currentItem.getmImageResource());
    holder.mtitleView.setText(currentItem.getmTitle());
    holder.mVegetarischView.setText(currentItem.getmTagVegetarisch());
    holder.mVeganView.setText(currentItem.getmTagVegan());
    holder.mTimeView.setText(currentItem.getmTime());

    }

    @Override
    public int getItemCount() {
        return mHauptgerichtList.size();
    }

}

If you need anything else, let me know. Thanks in advance!


text:
Q: PHP function - Shuffling / making a special word to always be the first in a string I have a list of dozens of simple sentences/strings. Each sentence contains a special keyword. My task is to make sure this special keyword is ALWAYS as the first word of the sentence.
Let's assume my special keyword is: dog.
Example sentences BEFORE:
$string1='my dog is eating soup';
$string2='where have you seen my dog last time';
$string3='this little dog barks a lot';
$string4='most cats are better than my dog';

Sentences that should be AFTER:
dog my is eating soup
dog where have you seen my last time
dog this little barks a lot
dog most cats are better than my

I see there is str_shuffle PHP function but it shuffles words in a string randomly; I need to make sure that my special keyword (dog) is always first in sentence. And ideally this function should be as fast as possible since there are lots of such operations to complete.
NOTE - I only need an example on how to do it on one sentence, not all..

A: This should work for you:
Just simply remove the keyword in the string with str_replace() and append it at the start of the string, e.g.
<?php

    $str = "my dog is eating soup";
    $keyword = "dog";

    echo $newString = $keyword . " " . str_replace($keyword, "", $str);

?>

output:
dog my is eating soup