text:
Q: Counting the sudden change in the points Python I would like to count how many times the graph suddenly decreases and comes back to normal.
For example, here the graph suddenly decreases for 4 times.

Here, I only need to detect the detect sudden change(circled in red) and not the small changes(circled in black).
I actually tried with slope but it doesn't seem to work correctly
The above picture was only a small scale, the below picture shows the entire graph

It would be a great help for me if you answer my question. Thank you

A: I got answer to my own question.
Initially, I reversed the array.
array = numpy.max(array) - array

By, reversing the array all my valley points are converted to peaks. Thus, it became easy to find peaks using scipy.signals module.
find_peaks(array, prominence=(30 ,np.max(array)))

This returned all the peak points, the length of peak points is required for me..
Hope this question helped you.. Thank you..


text:
Q: How to set semantic-ui-ember dropdown value? I have a model, called assessmentTestModel, that is a list of assessmentTests. Each assessmentTest contains a unique identifier id, and form that is a reference to another object called form. Form also has a unique identifier, id.
For every assessmentTest in assessmentTestModel, I want to render a drop-down on the screen that's menu-items are all of the forms (I've already accomplished this). I also want them to have the selected default value of assessmentTest.form (This is the issue). Currently, when each drop-down is rendered, it displays the default text 'Select an Assessment Test'.
Here's an example of assessmentTestModel:
{ assessmentTestModel: [
      {
          id: '1029',
          form: '85'
      },
      {
          id: '1030',
          form: '87'
      },
      {
          id: '1031',
          form: '85'
      }
 ]
}

Here is my current .hbs file. I've tried setting the value attribute of the ui-dropdown to the id of the form, and the form object itself. Neither have worked.

    Assessment Tests

        {{#each assessmentTestModel as |assessment|}}

                {{#ui-dropdown value=assessment.form class="selection" onChange=(action 'selectForm' assessment)}}

Select an Assessment Test

All Items

                        {{#each formModel as |form|}}

                                {{form.name}}

                        {{/each}}

                {{/ui-dropdown}}

        {{/each}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are succesive SVG's sized after the first one? I'm trying to build a dashboard with overview of a series of build jobs from Azure.
The badges provided by Azure are rendered differently depending on the sequence of the badges.
It can be boiled down to a very simple piece of HTML, which is available in this jsfiddle
If you change the order of the three div's it is obvious that the first div is limiting the width of the successive div's.
I have tried with Chrome, Edge, Edge Beta, FireFox and IE, all with the same (mis)behaviour.

  <svg width="135.0" height="20.0" xmlns="http://www.w3.org/2000/svg">
          <linearGradient id="a" x2="0" y2="100%">
            <stop offset="0.0" stop-opacity="0.0" stop-color="#000" />
            <stop offset="1.0" stop-opacity="0.2" stop-color="#000" />
          </linearGradient>
          <clipPath id="c">
            <rect width="135.0" height="20.0" rx="3.0" />
          </clipPath>
          <g clip-path="url(#c)">
            <rect width="135.0" height="20.0" fill="#555555" />
            <rect width="70.8" height="20.0" fill="#4da2db" x="64.2" />
            <rect width="135.0" height="20.0" fill="url(#a)" />
          </g>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" x="5" y="4">
            <g>
              <path fill-rule="evenodd" clip-rule="evenodd" d="M0 9H1V11H3L3 12H0V9Z" fill="#fff" />
              <path fill-rule="evenodd" clip-rule="evenodd"
                d="M0.666656 4H3.7352L6.20309 0.444336C6.38861 0.166992 6.70068 0 7.03479 0H11.5C11.7762 0 12 0.224609 12 0.5V4.96484C12 5.29883 11.8332 5.61133 11.5553 5.79688L8 8.26465V11.333C8 11.7012 7.70154 12 7.33334 12H5L4 11L5.25 9.75L4.25 8.75L2.99997 10L1.99997 9L3.25 7.75L2.25 6.75L1 8L0 7V4.66699C0 4.29883 0.298462 4 0.666656 4ZM10.5 3C10.5 3.82812 9.82843 4.5 9.00003 4.5C8.1716 4.5 7.50003 3.82812 7.50003 3C7.50003 2.17188 8.1716 1.5 9.00003 1.5C9.82843 1.5 10.5 2.17188 10.5 3Z"
                fill="#fff" />
            </g>
          </svg>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="41.1" y="15.0" fill="#000" fill-opacity="0.3">Short</text>
    <text x="41.1" y="14.0" fill="#fff">Short</text>
    <text x="98.6" y="15.0" fill="#000" fill-opacity="0.3">never built</text>
    <text x="98.6" y="14.0" fill="#fff">never built</text>
  </g>
  </svg>

  <svg width="155.9" height="20.0" xmlns="http://www.w3.org/2000/svg">
          <linearGradient id="a" x2="0" y2="100%">
            <stop offset="0.0" stop-opacity="0.0" stop-color="#000" />
            <stop offset="1.0" stop-opacity="0.2" stop-color="#000" />
          </linearGradient>
          <clipPath id="c">
            <rect width="155.9" height="20.0" rx="3.0" />
          </clipPath>
          <g clip-path="url(#c)">
            <rect width="155.9" height="20.0" fill="#555555" />
            <rect width="70.8" height="20.0" fill="#4da2db" x="85.1" />
            <rect width="155.9" height="20.0" fill="url(#a)" />
          </g>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" x="5" y="4">
            <g>
              <path fill-rule="evenodd" clip-rule="evenodd" d="M0 9H1V11H3L3 12H0V9Z" fill="#fff" />
              <path fill-rule="evenodd" clip-rule="evenodd"
                d="M0.666656 4H3.7352L6.20309 0.444336C6.38861 0.166992 6.70068 0 7.03479 0H11.5C11.7762 0 12 0.224609 12 0.5V4.96484C12 5.29883 11.8332 5.61133 11.5553 5.79688L8 8.26465V11.333C8 11.7012 7.70154 12 7.33334 12H5L4 11L5.25 9.75L4.25 8.75L2.99997 10L1.99997 9L3.25 7.75L2.25 6.75L1 8L0 7V4.66699C0 4.29883 0.298462 4 0.666656 4ZM10.5 3C10.5 3.82812 9.82843 4.5 9.00003 4.5C8.1716 4.5 7.50003 3.82812 7.50003 3C7.50003 2.17188 8.1716 1.5 9.00003 1.5C9.82843 1.5 10.5 2.17188 10.5 3Z"
                fill="#fff" />
            </g>
          </svg>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="51.6" y="15.0" fill="#000" fill-opacity="0.3">Longer title</text>
    <text x="51.6" y="14.0" fill="#fff">Longer title</text>
    <text x="119.5" y="15.0" fill="#000" fill-opacity="0.3">never built</text>
    <text x="119.5" y="14.0" fill="#fff">never built</text>
  </g>
  </svg>

  <svg width="255.9" height="20.0" xmlns="http://www.w3.org/2000/svg">
          <linearGradient id="a" x2="0" y2="100%">
            <stop offset="0.0" stop-opacity="0.0" stop-color="#000" />
            <stop offset="1.0" stop-opacity="0.2" stop-color="#000" />
          </linearGradient>
          <clipPath id="c">
            <rect width="255.9" height="20.0" rx="3.0" />
          </clipPath>
          <g clip-path="url(#c)">
            <rect width="255.9" height="20.0" fill="#555555" />
            <rect width="68.9" height="20.0" fill="#4EC820" x="187.0" />
            <rect width="255.9" height="20.0" fill="url(#a)" />
          </g>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" x="5" y="4">
            <g>
              <path fill-rule="evenodd" clip-rule="evenodd" d="M0 9H1V11H3L3 12H0V9Z" fill="#fff" />
              <path fill-rule="evenodd" clip-rule="evenodd"
                d="M0.666656 4H3.7352L6.20309 0.444336C6.38861 0.166992 6.70068 0 7.03479 0H11.5C11.7762 0 12 0.224609 12 0.5V4.96484C12 5.29883 11.8332 5.61133 11.5553 5.79688L8 8.26465V11.333C8 11.7012 7.70154 12 7.33334 12H5L4 11L5.25 9.75L4.25 8.75L2.99997 10L1.99997 9L3.25 7.75L2.25 6.75L1 8L0 7V4.66699C0 4.29883 0.298462 4 0.666656 4ZM10.5 3C10.5 3.82812 9.82843 4.5 9.00003 4.5C8.1716 4.5 7.50003 3.82812 7.50003 3C7.50003 2.17188 8.1716 1.5 9.00003 1.5C9.82843 1.5 10.5 2.17188 10.5 3Z"
                fill="#fff" />
            </g>
          </svg>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="102.5" y="15.0" fill="#000" fill-opacity="0.3">Very very very very long title</text>
    <text x="102.5" y="14.0" fill="#fff">Very very very very long title</text>
    <text x="220.5" y="15.0" fill="#000" fill-opacity="0.3">succeeded</text>
    <text x="220.5" y="14.0" fill="#fff">succeeded</text>
  </g>
  </svg>

A: Badges from Azure are not intended to be displayed alongside other badges in the same context, as they make use of Id's that are not unique.
I am building a C# Razor page app, so I load the SVG's before inserting them in the Razor page.
To solve this issue, I run the SVG through this ReplaceIds method, before passing them to the Razor page:
    private static string ReplaceIds(string text)
    {
        string pattern = " id=\"(\\w)\"";
        while (true)
        {
            var res = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
            if (res.Success && res.Groups.Count > 0)
            {
                var id = res.Groups[1];
                Guid g = Guid.NewGuid();
                text = Regex.Replace(text, $" id=\"{id}\"", $" id=\"{g}\"");
                text = Regex.Replace(text, @$"url\(#{id}\)", $"url(#{g})");
            }
            else
                return text;
        }
    }


text:
Q: Hahn Banach type extension of a Lipschitz map The problem that I posted was a much generalized form of what I had in my mind. All I want to know the literature of Hahn-Banach type extension of Lipschitz map. I know only about the result by Kirszbrzun and very few of its development. The main problem is:

Let $X$ be a real Banach space, $Y$ a subspace of it and $f$ a $1$-Lipschitz map from $Y$ to $\mathbb{R}$. Is it possible to get an extension of $f$ from $X$ to $\mathbb{R}$ with Lipschitz constant $1$?

The case when $X$ is a metrizable tvs  and $Y$ a finite dimensional subspace follows from MR0737400(86a:46018). But can we say anything about a infinite dimensional $Y$? Let us assume $X=C(K)$, $K$ is compact, $T_2$ (assume metrizable too if you want) and $Y=\{f\in X:f|_D=0\}$ (i.e. an M-ideal) of $X$. Now can a real valued $1$-Lipschitz map from $Y$ necessarily have a similar extension? Will it be unique ?

A: If $X$ is any metric space, $Y$ any subset of $X$, and $f: Y \to \mathbb{R}$ a Lipschitz function, then there is an extension $\tilde{f}: X \to \mathbb{R}$ of $f$ with the same Lipschitz constant. This easy result (just extend the function one point at a time) has been rediscovered many times. See Theorem 1.5.6 of my book Lipschitz Algebras.
The result does not follow from the paper of Johnson and Lindenstrauss that you mention. The case when $X$ is "metrizable" is meaningless as you need an actual metric to have a notion of Lipschitz map. The answer by MKO is basically unrelated to the question as far as I can tell.


text:
Q: Display table in php from mysql I'm doing a search engine, where after the student id is inserted in the text field, it will display the data about the student. I want to display it in the table form using the php code. But it doesn't work. Below is my code.

    <title>MrBool Development Article</title>

    <form action="search.php" method="GET">
        Enter Search Term:
        <input type="text" name="term" size="50">
        <input type="submit" value="Search">
    </form>

    <?php
        mysql_connect("localhost", "root", "");
        mysql_select_db("attendance_system");
        $sql = mysql_query("SELECT * FROM studentAttendance WHERE student_stud_matric LIKE '%$_GET[term]%'");
        while ($ser = mysql_fetch_array($sql)) {
            echo "

                            Student Matric
                            Subject Name

";

            echo "

                    ".$ser[student_stud_matric]."
                    ".$ser[course_course_code]."

";

            echo "

";
        }
    ?>

    Go Back

A: DO not create table inside while loop it would be like this

        <title>MrBool Development Article</title>

        <form action="search.php" method="GET">
            Enter Search Term:
            <input type="text" name="term" size="50">

            <input type="submit" value="Search">
        </form>
        <?php
        mysql_connect("localhost", "root", "");
        mysql_select_db("attendance_system");
        $sql = mysql_query("SELECT * FROM studentAttendance WHERE student_stud_matric LIKE '%$_GET[term]%'");
        ?>

                    Student Matric
                    Subject Name

                <?php while ($ser = mysql_fetch_array($sql)) { ?>

                        <?php echo $ser['student_stud_matric']; ?>
                        <?php echo $ser['course_course_code'] ?>

                <?php }
                ?>

        Go Back

A: Replace the following with your while loop, and it's done. However, seriously consider avoiding from mostruous mysql_* :)
$table = "

Student Matric	Subject Name

";
while($ser = mysql_fetch_array($sql)) {
    $table .= "
{$ser['student_stud_matric']}	{$ser['course_course_code']}
";
}
$table .= "

";
echo $table;


text:
Q: Using promises in string replace I'm relatively new to promises and I'm having issues.
I have a function that I want to be able to do a bunch of string replacements to the given text, a few which include a value returned from an api call.
parseText(text) {
  text.replace(/\n|\r\n|\r/g, ' ')
  .replace(/&/g, '&')
  .replace(/</g, '<')
  .replace(/>/g, '>')
  .replace(/<#(C\w+)\|?(\w+)?>/g, (match, id, read) => {
    return apiMethod(id).then(resp => resp.name)
  })
  .then(newText => {
    return newText.replace(/(-\w+)>/g, (match, id) => {
      apiMethod(id).then(resp => resp.name)
    }
  });
}

How do I get the replace to work with the returned value of apiMethod promise?

A: One option would be to create an array of Promises for each request, call Promise.all on the array, and then create an object indexed by the id (the first group in your regex). Then, call .replace again, and substitute with the the appropriate indexed key. Because you have to asynchronously replace more than once, put it into its own function to make your code DRY:
const asyncReplace = async (str, regex) => {
  const promises = [];

  // does not actually replace anything, just builds the promises:
  str.replace(regex, (match, id, read) => {
    promises.push(apiMethod(id).then(resp => [id, resp.name]));
  });
  const results = await Promise.all(promises);
  const replacements = results.reduce((a, [id, name]) => {
    a[id] = name;
    return a;
  }, {});
  return str.replace(regex, (match, id, read) => replacements[id]);
}

parseText(text) {
  const str = text.replace(/\n|\r\n|\r/g, ' ')
  .replace(/&/g, '&')
  .replace(/</g, '<')
  .replace(/>/g, '>');
  return asyncReplace(str, /<#(C\w+)\|?(\w+)?>/g)
    .then((str2) => asyncReplace(str2, /<#(C\w+)\|?(\w+)?>/g))
}

Live snippet:

// encloses the match in underscores
const apiMethod = substr => Promise.resolve('_' + substr + '_');

const asyncReplace = async (str, regex) => {
  const promises = [];

  // does not actually replace anything, just builds the promises:
  str.replace(regex, (match, id, read) => {
    promises.push(apiMethod(id).then(resp => [id, resp]));
  });
  const results = await Promise.all(promises);
  const replacements = results.reduce((a, [id, name]) => {
    a[id] = name;
    return a;
  }, {});
  return str.replace(regex, (match, id, read) => replacements[id]);
}

function parseText(text) {
  // put underscores around every space...
  return asyncReplace(text, /( )/g)
  // ...twice:
    .then((str2) => asyncReplace(str2, /( )/g))
}
parseText('foo bar baz')
  .then(res => console.log(res));


text:
Q: How to solve error: 'Missing arguments for parameters 'data', 'detailedData' in call' I'm trying to make a detailed view of a contact from a contacts list. This is the WIP of that view. I am getting the error;

Missing arguments for parameters 'data', 'detailedData' in call

on the line with ContactDetail() in the ContactDetail_Previews struct.
I think I understand that this is because something is missing from the variables data and detailedData, but my confusion comes from how I use similar code for the actual list view of all the contacts, with no such error. I have pasted the code for the whole list view below the code for the detailed view.
Any help would be appreciated!
Contact Detail Code:
import SwiftUI

struct ContactDetail: View {
    var data: Response_Detailed.Contact_Detailed
    @ObservedObject var detailedData: getData_Detailed

    var body: some View {
        VStack {
            Text(data.first_name + " " + data.last_name)
            Text(data.phone_number)
            Text(data.birthday)
            Text(data.address)
            Text(data.updated_date)
            Text(data.create_date)
                .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.detailedData.updateDetailed_Data()
                }
            }
        }
    }
}

class getData_Detailed: ObservableObject {
    @Published var data = [Response_Detailed.Contact_Detailed]()
    @Published var id = 1

    init() {
        updateDetailed_Data()
    }

    func updateDetailed_Data() {
        let url = "DATABASE_LINK\(id)"
        let session = URLSession(configuration: .default)

        session.dataTask(with: URL(string: url)!) { (data, _, err) in
            if err != nil {
                print((err?.localizedDescription)!)
                return
            }

            do {
                let json = try JSONDecoder().decode(Response_Detailed.self, from: data!)
                let oldData = self.data

                DispatchQueue.main.async {
                    self.data = oldData + json.data

                    let encoder = JSONEncoder()
                    encoder.outputFormatting = .prettyPrinted
                    let data = try! encoder.encode(json)

                    print(String(data: data, encoding: .utf8)!)
                }
            }
            catch {
                print(error.localizedDescription)
            }
        }.resume()
    }
}

struct ContactDetail_Previews: PreviewProvider {
    static var previews: some View {
        ContactDetail()
    }
}

struct Response_Detailed: Codable {
    struct Contact_Detailed: Codable, Identifiable {
        public let id: Int
        public let first_name: String
        public let last_name: String
        public let birthday: String
        public let phone_number: String
        public let create_date: String
        public let updated_date: String
        public let address: String
    }
    public let data: [Contact_Detailed]
    enum CodingKeys : String, CodingKey {
        case data = "data"
    }
}

Contacts List View Code: (Note the same error comes up on the line with NavigationLink.
import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            HStack {
                ContactsList()
                    .navigationBarTitle("Contacts")
                    .toolbar {
                        ToolbarItem(placement: .navigationBarTrailing) {
                            Image(systemName: "plus")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 20.0)
                    }
                }
            }
        }
    }
}

struct ContactsList: View {
    @ObservedObject var listData = getData()

    var body: some View {
        List(0..<listData.data.count, id: \.self) {i in
            NavigationLink(destination: ContactDetail()) {

                if i == self.listData.data.count - 1 {
                    cellView(data: self.listData.data[i], isLast: true, listData: self.listData)
                }
                else {
                    cellView(data: self.listData.data[i], isLast: false, listData: self.listData)
                }
            }
        }
    }
}

struct cellView: View {
    var data: Response.Contact
    var isLast: Bool
    @ObservedObject var listData: getData

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            if self.isLast {
                Text(data.first_name + " " + data.last_name)
                    .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
                    .font(.title2)
                    .padding(/*@START_MENU_TOKEN@*/[.leading, .bottom, .trailing], 5.0/*@END_MENU_TOKEN@*/)
                    .onAppear {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            self.listData.updateData()
                    }
                }
            }
            else {
                Text(data.first_name + " " + data.last_name)
                    .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
                    .font(.title2)
                    .padding(/*@START_MENU_TOKEN@*/[.leading, .bottom, .trailing], 5.0/*@END_MENU_TOKEN@*/)
            }
        }
        .padding(.top, 10)
    }
}

class getData: ObservableObject {
    @Published var data = [Response.Contact]()
    @Published var limit = 15
    @Published var skip = 0

    init() {
        updateData()
    }

    func updateData() {
        let url = "DATABASE_LINK?skip=\(skip)&limit=\(limit)"
        let session = URLSession(configuration: .default)

        session.dataTask(with: URL(string: url)!) { (data, _, err) in
            if err != nil {
                print((err?.localizedDescription)!)
                return
            }

            do {
                let json = try JSONDecoder().decode(Response.self, from: data!)
                let oldData = self.data

                DispatchQueue.main.async {
                    self.data = oldData + json.data
                    self.limit += 15
                    self.skip += 15

                    let encoder = JSONEncoder()
                    encoder.outputFormatting = .prettyPrinted
                    let data = try! encoder.encode(json)

                    print(String(data: data, encoding: .utf8)!)
                }
            }
            catch {
                print(error.localizedDescription)
            }
        }.resume()
    }
}

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

struct Response: Codable {
    struct Contact: Codable, Identifiable {
        public let id: Int
        public let first_name: String
        public let last_name: String
        public let updated_date: String
    }
    struct Pagination_Data: Codable {
        public let skip: Int
        public let limit: Int
        public let total: Int
    }
    public let data: [Contact]
    public let pagination: Pagination_Data
    enum CodingKeys : String, CodingKey {
        case data = "data"
        case pagination = "pagination"
    }
}

A: Your ContactsList is giving the only variable an initial value.
@ObservedObject var listData = getData()

Not IAW Apple documentation but the = getData() is the initial value
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
BTW you should change it to
@StateObject var listData = getData()

Your ContactDetail View has two variables without an initial value
struct ContactDetail: View {
    var data: Response_Detailed.Contact_Detailed
    @ObservedObject var detailedData: getData_Detailed

No = sign so a struct creates an init that looks like this
init(data: Response_Detailed.Contact_Detailed, detailedData: getData_Detailed)

So in your Preview you need to provide the initial values
ContactDetail(data: /.../, detailedData: /.../)

The /.../ symbolizes where you will provide sample data


text:
Q: Tic Tac Toe Game 2D Array My code runs, but it doesn't print out anything in the board. I'm pretty sure i have done a couple of things wrong, and if someone could point me in the right direction, that would be great.. Thanks for any help!
#include<iostream>
#include<iomanip>

using namespace std;

void drawBoard(char board[][3]);
char checkWinner3by3(char board[][3]);

.
//
// DO NOT MODIFY THE MAIN FUNCTION
//
int main()
{
    // This array of chars represents the game board, and it holds the content
    // of each space. By default all spaces are set to a blank space.
    char board[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};

    // The current player. Because X plays first, initialize to X
    char player = 'X';

    // The winner. either 'X', 'O', or 't' if it's a tie.
    // Or a blank space if the game has not finished.
    char winner = ' ';

    // These variables will hold the number of the row and column selected
    // by the players.
    int row;
    int column;

    // boolean variables used to verify if the move is valid.
    bool is_move;
    bool is_row;
    bool is_column;

    cout<<"************ TIC TAC TOE ************\n";

    // The game loops again and again until the game is over
    while(winner == ' ')
    {
        //set the boolean variables back to false for a new turn.
        is_move = false;
        is_row = false;
        is_column = false;

        //draw the board.
        drawBoard(board);

        // If the game is not yet over show who`s the next player to move
        cout << "Player ";
        if(player == 'X')
        {
            cout << 1;
        }
        else
        {
            cout << 2;
        }
        cout << "'s turn:" << endl;

        // Loop until the player selects a valid space for their move
        is_move = false;
        while(!is_move)
        {
            // Loop until the player selects a valid row
            // Assume the user inputs a valid integer
            is_row = false;
            while(!is_row)
            {
                cout << "Row: ";
                cin >> row;
                if(row == 1 || row == 2 || row == 3)
                {
                    is_row = true;
                }
                else
                {
                    cout << endl << "Invalid row!" << endl;
                }
            } // end of input row loop

            // Loop until the player selects a valid column
            // Assume the user inputs a valid integer
            is_column = false;
            while(!is_column)
            {
                cout << "Column: ";
                cin >> column;
                if(column == 1 || column == 2 || column == 3)
                {
                    is_column = true;
                }
                else
                {
                    cout << endl << "Invalid column!" << endl;
                }
            } // end of input column loop

            // If the space is empty, mark the chosen space and swich players
            if(board[row-1][column-1] == ' ')
            {
                // Mark the space and end the player's turn
                board[row-1][column-1] = player;
                is_move = true;

                // Switch to the other player
                if(player == 'X')
                {
                    player = 'O';
                }
                else
                {
                    player = 'X';
                }
            } // end of marking space and changing players

            // If the space is occupied
            else
            {
                cout<<"The selected space is occupied!" << endl;
                cout << "Select a different space:" << endl << endl;
                drawBoard(board);
            }
        } // end of player's move loop

        cout << endl; // for nice output formatting

        //check if the player won.
        winner = checkWinner3by3(board);

        //If there's a winner
        if(winner == 'X' || winner == 'O')
        {
            drawBoard(board);

            //Display congratulations message
            cout<<"Congratulations! Player ";
            if(winner == 'X')
            {
                cout << 1;
            }
            else
            {
                cout << 2;
            }
            cout<<" is the winner!"<<endl;
        }
        else if(winner == 'T')
        {
            drawBoard(board);

            //Display a message if it`s tie
            cout << "It's a tie!" << endl;
        }

    } // End of player's turn loop

    system("pause");
    return 0;
}

//
// Prints the game board
// We know the board is 3 by 3 so we don't need to have the number of rows as
// a parameter.
//
// WRITE THIS FUNCTION
//
void drawBoard(char board[][3])
{
    char print[][3] = {{' ',' ',' '},
                        {' ',' ',' '},
                        {' ',' ',' '}};

    cout << "     1   2   3" << endl;
    cout << "   +---+---+---+" << endl;

    cout << " 1" << " | " << print[0][0] << " | " << print[0][1] << " | " << print[0][2] << " | " << endl;
    cout << "   +---+---+---+" << endl;

    cout << " 2" << " | " << print[1][0] << " | " << print[1][1] << " | " << print[1][2] << " | " << endl;
    cout << "   +---+---+---+" << endl;

    cout << " 3" << " | " << print[2][0] << " | " << print[2][1] << " | " << print[2][2] << " | " << endl;
    cout << "   +---+---+---+" << endl;

}
//
// Checks the whole board if there is a winner.
// We know the board is 3 by 3 so we don't need to have the number of rows as
// a parameter.
//
// WRITE THIS FUNCTION
//
char checkWinner3by3(char board[][3])
{

    for(i=0; i<3; i++)  /* check rows */
    {
        if(board[i][0]==board[i][1] && board[i][0]==board[i][2])
        {
            return board[i][0];
        }
    }

    for(i=0; i<3; i++)  /* check columns */
    {
        if(board[0][i]==board[1][i] && board[0][i]==board[2][i])
        {
            return board[0][i];
        }
    }
       /* test diagonals */
    if(board[0][0]==board[1][1] && board[1][1]==board[2][2])
    {
        return board[0][0];
    }

    if(board[0][2]==board[1][1] && board[1][1]==board[2][0])
    {
       return board[0][2];
    }

    return ' ';
}

A: Drawboard doesn't use its board argument.

A: for(i=0; i<3; i++)  /* check rows */
    {
        if(board[i][0]==board[i][1] && board[i][0]==board[i][2])
        {
            return board[i][0];
        }
    }

You'll get an error here. If this is a homework assignment try to figure out exactly what the error is yourself.
In addition, I don't see anything in the draw board function that actually lets it use your board array.
Those are the two biggest problems I can see. Good luck on the assignment.

A: // If the space is occupied
else
{
    cout<<"The selected space is occupied!" << endl;
    cout << "Select a different space:" << endl << endl;
    drawBoard(board);
}

This portion is also a problem. based on you're loop it'll run forever.
You need to end the while(!is_move) loop in order to get new input for the player's turn if the space they chose is occupied.


text:
Q: Yellow trianlges on every reference in asp .net project I have a new project for a new job. The project will not build on my computer. It has yellow triangles under every reference that isn't a project in the solution. It even has a yellow triangle for microsoft.csharp. I have been digging and tried many things online and on stack overflow. Anyone have an ideas, would love to keep this job. Thanks.

A: you need to restore the nuget packages

A: Like @Dai and @Michael suggest, you need to re-install the references. I just provide the detail.
There are many ways to do it. This is what I usually do.
Step 1: Enable NuGet package restore.

Step 2: go to the packages folder of your project: C:\path\your project\packages\
Step 3: delete everything in that folder
Step 4: open the project again in VS and Build the project (Build > Build Solution). NuGet will download and re-install all required packages

A: *

*try to do a build first

*if that doesn't fix it then restore the nuget packages

*if that doesn't work then clear your local nuget cache and rebuild the project


text:
Q: JavaScript Library for Posing/Rigging Figures Can anyone recommend a JavaScript+HTML5 library that supports "posable figures"?   Think about those wooden dolls that artists use to practice drawing, I would like functionality something like that for the browser.  Essentially, the user should be able to pose a virtual doll.

A: Check out Box2DJS. It's a JavaScript port of the popular Box2d physics engine.


text:
Q: Compare values within list of rows in R I've identified a list of row numbers in a large data frame using the following:
brownturkey_rows <- grep("brown",Dataframe$color)

For which I get
brownturkey_rows int [1:5] 3 6 7 8 9

Now I need to check a certain condition in each of those rows and return which rows fail. For example looking at row 6:
Dataframe$age[6] < Dataframe$limit[6]

In perl, I would have used a foreach loop. What is the best way to do this in R?

A: Here's one way to do it:
subset(Dataframe[grep("brown", Dataframe$color),], age < limit)

That is, you use the output of the grep as a filter on Dataframe,
and then you further filter the results using subset.
As @moody-mudskipper pointed out, an even better way:
subset(Dataframe, grepl("brown", color) & age < limit)

Here grepl is used to get logical values of the filtering instead of the values themselves,
and combine that directly with the other logical condition that you're interested in (age < limit).
Another way:
d2 <- Dataframe[grep("brown", Dataframe$color),]
d2[with(d2, age < limit),]


text:
Q: How can I switch Python Tkinter GUI camera source? First of all, I wanted to put a camera switch option on a piece of code found here. First, I found the possible camera indexes and tried to change the camera sources with the push of a button. Even though the function worked, the camera source was not changed. I am looking for a solution for this.
In other words, how can I change the camera indexes through the function. The "returnCameraIndexes ()" function that I wrote before starting the 'main' section in this topic creates the total camera indexes. The "ChangeCam(" function is the function that performs the exchange between all the resources I have acquired.
import numpy as np
from multiprocessing import Process, Queue
from Queue import Empty
import cv2
from PIL import Image, ImageTk
import time
import Tkinter as tk

#tkinter GUI functions----------------------------------------------------------
def quit_(root, process):
   process.terminate()
   root.destroy()

def update_image(image_label, queue):
   frame = queue.get()
   im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
   a = Image.fromarray(im)
   b = ImageTk.PhotoImage(image=a)
   image_label.configure(image=b)
   image_label._image_cache = b  # avoid garbage collection
   root.update()

def update_all(root, image_label, queue):
   update_image(image_label, queue)
   root.after(0, func=lambda: update_all(root, image_label, queue))

#multiprocessing image processing functions-------------------------------------
def image_capture(queue,change_camera_flag):
   vidFile = cv2.VideoCapture(change_camera_flag)
   while True:
      try:
         flag, frame=vidFile.read()
         if flag==0:
            break
         queue.put(frame)
         cv2.waitKey(20)
      except:
         continue

#check all camera Sources
def returnCameraIndexes():
    # checks the first 10 indexes.
    index = 0
    arr = []
    i = 10
    while i > 0:
        cap = cv2.VideoCapture(index)
        if cap.read()[0]:
            arr.append(index)
            cap.release()
        index += 1
        i -= 1
    return arr

camera_list = returnCameraIndexes()
change_camera_flag = 0

# Switch camera sourcess
def ChangeCam():
    global change_camera_flag,cap_1
    if(len(camera_list)-1 == change_camera_flag):
        change_camera_flag = 0
    else:
        change_camera_flag = change_camera_flag + 1
    print(change_camera_flag)

if __name__ == '__main__':
   queue = Queue()
   print ('queue initialized...')
   root = tk.Tk()
   print ('GUI initialized...')
   image_label = tk.Label(master=root)# label for the video frame
   image_label.pack()
   print ('GUI image label initialized...')
   p = Process(target=image_capture, args=(queue,change_camera_flag))
   p.start()
   print ('image capture process has started...')
   change_source_button = tk.Button(master=root, text='ChangeCamera',command=lambda: ChangeCam())
   change_source_button.pack()
   # quit button
   quit_button = tk.Button(master=root, text='Quit',command=lambda: quit_(root,p))
   quit_button.pack()
   print ('quit button initialized...')
   # setup the update callback
   root.after(0, func=lambda: update_all(root, image_label, queue))
   print ('root.after was called...')
   root.mainloop()
   print ('mainloop exit')
   p.join()
   print ('image capture process exit')


text:
Q: Wrap function call with macro Is it possible to wrap only function call with macro?
When I'm trying
#define foo(x) bar(x)

it wraps both function call and definition.
I know about wrapping function with linker, but in this case I can't use this solution.
Lets assume some code
#define foo(x) bar(z)

int foo(int z){
//some code
}

int bar(int x){
//some code
}

int function(){
int a = foo(2);
}

I want to int a = foo(2); after preprocessing become int a = bar(2).
Currently I only receive "redefinition" error.
Edit: my example shows, what I want to achieve, but I in real code I have to put this macro to project via cmake file and I also can't modify source code in destination file. Sorry for not mention about it earlier.

A: use undef to manage the lifetime of your macros and not to screw with sections of code that aren't aware of your macros' existence.
int foo(int z){
//some code
}

int bar(int x){
//some code
}

int function(){
    #define foo(x) bar(z)
    int a = foo(2);
    #undef foo
}

This trick extends to things like header options, often things like Windows.h are included and the header's defines depend on defines defined outside of the header as follows:
#define WIN32_LEAN_AND_MEAN // used in ifdef checks to not define/include rarely used stuff
#define NO_STRICT // used to allow HANDLE types to be used as void * without type errors
#define NO_MINMAX // used to avoid errors because MIN/MAX are already defined
#include <Windows.h>

this pollutes scope with macros that have no use after the header finished parsing, so you can clean up by undefing them after include:
#define WIN32_LEAN_AND_MEAN // used in ifdef checks to not define/include rarely used stuff
#define NO_STRICT // used to allow HANDLE types to be used as void * without type errors
#define NO_MINMAX // used to avoid errors because MIN/MAX are already defined
#include <Windows.h>
#undef NO_MINMAX
#undef NO_STRICT
#undef WIN32_LEAN_AND_MEAN

This makes it easier for people reading your code, especially beginners to C to know that these are options and don't have any use after the include occurs. This also allows you to do interesting C++-like behaviors like templating based on defines defined before include, without conflicts of including headers multiple times.

A: Not sure if this is what you want, but you could try putting the macro after the function declarations. So
foo(...){}
bar(...){}
#ifdef REPLACE_FOO
#define foo(x) bar(x)
#endif
main(){
    foo(1);
}

A: That's because the preprocessor does not care about which string to replace.
It also replaces your original function definition foo, which means that the function bar is defined twice.
You should be able to solve that by something like that:
#if !defined(foo)
int foo(int z){
   //some code
}
#endif

Of course, it depends on what you actually want to do.


text:
Q: Dynamic start-up circuit Many circuits have two possible states: one state is that in which every current and voltage is zero, the other state is the "correct" state. In order to avoid the trivial state and force the circuit in the correct state, a start-up circuit is required. This circuit injects a current in a transistor in order to force a current to flow. Let's consider the following dynamic start-up circuit:

M4 is the diode-connected transistor of a current mirror belonging to the circuit that we want to "activate" (i.e. avoid the trivial state). When the circuit is turned on, Vdd goes from zero to its value ideally like a step. Assuming Cs initially discharged, node B will remain at zero for a while (and thus transistor MS1 is on, producing a glitch of current which "activates" M4) and then will raise to Vdd exponentially (causing MS1 to gradually turn off, which is correct since M4 has already been activated).
The author of my book says:
"The dynamic start-up circuit doesn't monitor the reference current but simply
produces a glitch current in M4 that, hopefully, will bring the circuit in the
desired operative point. Therefore, the circuit works properly only if the off-to-on time of the supply voltage is pretty fast, compared to the time constant Rs*Cs. In addition to this, the parasitic capacitance from node B and Vdd should be small compared to the capacitor Cs. If not the coupling of node B with the Vdd line attenuates the glitch at the gate to source of MS1 eventually preventing
it to exceed the threshold."
What does it mean? The author says that if some conditions (which I don't understand) are not satisfied, then the start-up circuit will not work. But actually it seems to me that the circuit should always work: indeed, if the capacitor is initially discharged, node B must go from zero to Vdd exponentially, thus necessarily turning on (and then, as node B raises, turning off) MS1, which "activates" M4.
Thank you

A: Imagine the Vdd is brought up from 0V to nominal operating voltage very slowly relative to the RC time constant of Rs*Cs so that node B is essentially at Vdd potential at all times. MS1 could then never turn on.
So this is possibly an unreliable start-up circuit because it depends on rapid application of Vdd.
Keep in mind that on-chip resistors are probably (and preferably) relatively low resistance and on-chip capacitors are usually tens of pF or (preferably) less. For example, 100k and 10pF would have a time constant of only 1\$\mu\$s.


text:
Q: Using directive for package added in Visual Studio Code I'm trying trying to build a web app with ASP.NET Core 3.0 and using VS Code to do it. Moreover, I'm using MySQL for my database, and this is where things are getting rough. It seems like there's very little support out there for this particular combination of VS Code and MySQL.
I can't find any tutorials with this particular combination, so I can't figure out how to put it all together. I ran the dotnet add package Mysql command, which installed the package, and I see that it's been added to the .csproj file, except now I don't know how to make use of it in my Model file. I'm trying to find the using directive for it, but I can't find any posts on any forums addressing this issue.


text:
Q: Functions Passing Arrays In/Out Program Fortran 90 I'm working on trying to pass an array into a function to be able to calculate new values that will replace the original values in that array.  However, I keep getting zeroes to be returned and I'm not sure why.  My code is below:
program HW10
    implicit none
    integer :: i
    integer, parameter :: &
    p=38      !lines to read
    real, parameter :: &
    g=9.81    !Value of gravity acceleration
    integer , dimension(p) :: direction, speed, rh, speedconv
    real, dimension (p) :: pressure, height, temp, dewpt, mixr
    real :: average, knots

    open(1,file='HW10input.txt', status='old', action='read')

    10 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)

    do i=1,p
        read(1,10)pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
    end do

    close (1)

    open(2, file='outputfilehw10.txt', status='new', action='write')
    do i=1,p
    write (*, 20) pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
    20 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
    end do
    write (*,*) 'Average= ', average(temp, p)
    do i=1,p
        write (*,*) 'Wind Speeds: ', knots(speed, p)
    end do
end program HW10

The issue comes when I get to the function "knots" at the bottom.  This is what the function looks like:
real function knots (x, n)
integer, intent(in) :: n
real, dimension(n), intent(inout) :: x
integer :: i

do i = 1, n
    x(i) = (x(i) * 0.514444 )
end do
return x
end function knots

The code will read in the data fine, as I have the code displaying it properly.  However when I want to see the changed data within the wind speed array, all of the data points are zeroes.  I'm new to Fortran so I'm not quite sure what to do.  Thanks in advance!

A: If I try to compile the code given in the question (put all in the same file) with gfortran 4.8.3 I get the following two errors:
First error:
return x
      1
Error: Alternate RETURN statement at (1) is only allowed within a SUBROUTINE

Second error:
        write (*,*) 'Wind Speeds: ', knots(speed, p)
                                           1
Warning: Type mismatch in argument 'x' at (1); passed INTEGER(4) to REAL(4)

Let's deal with the first of these - unlike many other programming languages it is not used to set the return value.
So, why did the compiler just complain that you've done this in a function rather than a subroutine instead of the compiler complaining that you've put a value here? There's a historic feature known as alternate return that is a bit like using a goto -- these are only allowed in subroutines.
So let's replace return x with just return -- this avoids the compiler error, but how does the code know what value to return? When defining functions in fortran you can explicitly specify a name for the result, but if you don't do this then it assumes your result is a variable with the same name as the function, so in your case knots. So in your code the variable to be returned is called knots but it never gets set to anything. By "coincidence" it looks like the bit of memory being used to store the result, which is never explicitly set to anything, is either being initialised to zero by the compiler or you're just accessing uninitialised memory that happens to be full of zeros.
So how do we fix this? Let's define the result explicitly
function knots (x, n) result(y)
  implicit none
  integer, intent(in) :: n
  real, dimension(n), intent(inout) :: x
  real, dimension(n) :: y
  integer :: i

  do i = 1, n
     y(i) = (x(i) * 0.514444 )
  end do
  return
end function knots

If we try to compile we now get a new error!
write (*,*) 'Wind Speeds: ', knots(speed, p)
                                    1
Error: The reference to function 'knots' at (1) either needs an explicit INTERFACE or the rank is incorrect

Functions/subroutines with arguments/return values typically need to have an interface defined . There are many ways to achieve this, I'm going to do it by putting the function in a module:
module myknots
  implicit none
  public :: knots
contains
  function knots (x, n) result(y)
    implicit none
    integer, intent(in) :: n
    real, dimension(n), intent(inout) :: x
    real, dimension(n) :: y
    integer :: i

    do i = 1, n
       y(i) = (x(i) * 0.514444 )
    end do
    return
  end function knots
end module myknots

We then need to add use myknots, only: knots to the top of the main program. This now leaves us with just the second error.
What this is telling us is that you've passed an integer array to a function that expects a real value. This is because speed is declared as integer but x in knots is declared as real. To fix this let us create a new knots function in which x is declared as integer. I'll also use an explicit interface to allow us to refer to either version of knots using the name knots. Doing this the myknots module looks like
module myknots
  implicit none
  private
  public :: knots

  interface knots
     module procedure knots_r
     module procedure knots_i
  end interface knots
contains
  function knots_r (x, n) result(y)
    implicit none
    integer, intent(in) :: n
    real, dimension(n), intent(inout) :: x
    real, dimension(n) :: y
    integer :: i

    do i = 1, n
       y(i) = (x(i) * 0.514444 )
    end do
    return
  end function knots_r

  function knots_i (x, n) result(y)
    implicit none
    integer, intent(in) :: n
    integer, dimension(n), intent(inout) :: x
    real, dimension(n) :: y
    integer :: i

    do i = 1, n
       y(i) = (x(i) * 0.514444 )
    end do
    return
  end function knots_i
end module myknots

The main program looks like
Program HW10
  use myknots, only: knots
  implicit none
  integer :: i
  integer, parameter :: &
       p=38      !lines to read
  real, parameter :: &
       g=9.81    !Value of gravity acceleration
  integer , dimension(p) :: direction, speed, rh, speedconv
  real, dimension (p) :: pressure, height, temp, dewpt, mixr
  real :: average

  open(1,file='HW10input.txt', status='old', action='read')

10 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)

  do i=1,p
     read(1,10)pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
  end do

  close (1)

  open(2, file='outputfilehw10.txt', status='new', action='write')
  do i=1,p
     write (*, 20) pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
20   format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
  end do
  write (*,*) 'Average= ', average(temp, p)
  do i=1,p
     write (*,*) 'Wind Speeds: ', knots(speed, p)
  end do
end program HW10

This has fixed all the immediate issues, but you still won't be able to produce an executable as you haven't yet defined the average function. Hopefully the steps above should be enough to allow you to implement this yourself.

A: You have a function knots which has a real result.  Look at the line
write (*,*) 'Wind Speeds: ', knots(speed, p)

The function reference knots(speed, p) is evaluated to return that real result, and that result is then printed.
There are two problems, based on the same misunderstanding: in the function knots the result of the function has the name knots.  This isn't the same thing as the intent(inout) dummy argument x.
Problem 1: you don't defined the value of knots in the function.
Problem 2: the value of knots isn't the value you want.  You want the value (on return) of speed.
You could either define the result knots to be the output array, or you can use a subroutine instead.  I won't go into the details of those two approaches (as there are plenty of resources available there), but I will clearly note: if knots becomes a function with result array there will need to be an explicit interface available when it is referenced.


text:
Q: IIS Access Violation with WCF to connect MQSeries I am using the amqmdnet.dll to connect to an MQSeries Queue.
I am able to put and get messages to and from the queue in a console application, everything is OK in this case.
However I am developing a WCF and in the WCF when creating the MQQueueManeger (this line of code:
MQQueueManager qm = new MQQueueManager(queueManagerName, channel, connName);

) I get this error:
iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
Why everything goes well with a console application and not with an WCF?


text:
Q: Will this query return ALL files modified today? I'm running SharePoint 2010 and SQL Server 2008 R2.
It's hugely important that I create a list of every file within a given content database that has been modified today, 10/31.  Will this query do it or will it leave anything -anything at all- out?
SELECT [DirName],
       [LeafeName],
       [TimeLastModified]
FROM   [WSS_Content_TARGETDB].[dbo].[AllDocs]
WHERE  [TimeLastModified] BETWEEN '20121031' AND '20121101';

I'm crossing my fingers that this will list everything without any gaps.

A: NEVER READ DIRECTLY FROM THE DATABASES
(unless there is no other option)
This will probably work with the current patches it might, but it's not documented or guaranteed and even thought it might work now it might stop working if a patch is applied.
Have you consider using the change log which is meant exactly for getting things like this?
See Using the Change Log


text:
Q: Access to WiFi connection settings on Linux Mint 19.1 Cinnamon I need to connect to my university's WiFi, which is eduroam, through TTLS or PEAP with my credentials.
Linux Mint 19.1 Cinnamon only shows the option after the connection is established, so I can't configure it to connect.  This is what I mean:

Is there another way to configure specific network connections?

A: It turned out the way to configure the connection parameters before connecting was through adding a network with the ssid.
In my case with the "+" button, select wifi connection and SSID "eduroam", and proceed to the security settings.


text:
Q: External WD Drive showing read only I have WD External SSD Drive and macOS Catalina. The drive is formatted in ExFAT
Initially, I used my external drive 2-3 times and it was working fine. Suddenly today I am not able to write anything in my Drive as its showing Read-Only.
output from mount
/dev/disk2s2 on /Volumes/MUKESH (exfat, local, nodev, nosuid, read-only, noowners)

I have tried running following command but it did not work.
sudo chmod -R 777 /Volumes/MUKESH

Here is what I see in disk utility

In Get-Info section I see this.

A: If you can, go into Disk Utility (like you are), and use First Aid on the partition in question.  Depending on the size of your drive, it will take a while, but when it should restore write capability to your disk.
Source: I did the same thing when my MyBook 2TB was randomly showing up as read-only.


text:
Q: Best way to get XPATH and CSS SELECTORS for scraping with Selenium What is the best way you guys know to get the XPATH AND CSS SELECTOR of a scraped website using selenium?
Someone suggested that I use these XPATH and CSS SELECTORS as parameters for an exercise I'm working on:
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[placeholder='Search']"))).send_keys('Tech')
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Cancel']/.."))).click()

These parameters work very well for the exercise. However, I'm unsure on how to get (or "build") those parameters...
If I use Chrome's Inspect > right click > Copy XPATH or Copy Selector, I get some very different parameters that don't seem to work as well, and don't seem to be found by selenium.
#search-bar
//*[@id="app-container"]/div/section/div/div/div[2]/button

Is there a tool or a technique to get better XPATH or CSS SELECTORS as in my first example?

A: I like the resources shared by @JD2775. They are good to get you started understanding how to construct and understand xpaths and css selectors. When you are comfortable with that, you can work on your selector strategy. Hopefully you find at least some of the following helpful.
What makes a "good" xpath or css selector?

*

*The selector should reliably and uniquely identify the targeted element.

*

*For example, if an element's class occurs multiple times on the page, do not use only this class to identify the element. This is the most basic requirement for your selector

*The selector should not be prone to "flakiness" -- ie, false failures that occur as a result of changes that are unrelated to the test.

*

*Accomplish this by relying on as little of the DOM as possible to identify your element. For example, if both work to uniquely identify the element, //*[@id="app-container"]//button should be preferred over //*[@id="app-container"]/div/section/div/div/div[2]/button. Or, as you identify, "//button[text()='Cancel']/.." is the better choice.

*Probably less important, but still worth considering: how easy is it to understand from the selector which element is being grabbed?

Some best practices

*

*If you are working with a development team and thus have access to the source code of the application you are testing, implement a custom HTML attribute that is used ONLY for automation, and which has a value to uniquely identify and describe the element. In your test code you can then identify each of the elements you need with a line like this:

my_field = driver.find_element_by_css_selector('input[data-e2e-attribute="aCertainField"]')`

*

*Organize your selection of elements into a Page Object Model, which abstracts the definition of webelements to one spot. So you can use these elements anywhere in your test without having to locate them, and it's easier to make changes to your selectors when necessary

A: You are correct that right-clicking and Copy Xpath is a bad way to get an Xpath. You are left with a long and brittle selector. It is much better to build your own. Once you get the hang of it, it is pretty simple to start building your own CSS and Xpath selectors.  Some of them get complicated but if you keep practicing and searching for solutions you will get better and better.
The problem is it is very difficult to explain how to do it in a forum like this.  Your best bet is to YouTube some videos on how to create Xpath and CSS selectors for Selenium.  Here is a decent one I just found for Xpath:
https://www.youtube.com/watch?v=3uktjWgKrtI
This follows the approach I use in Chrome Dev Tools and using the built in Find window (no plugins)
Here is a good cheatsheet I have used in the past for Xpath and CSS Selectors
https://www.automatetheplanet.com/selenium-webdriver-locators-cheat-sheet/
Good luck


text:
Q: How to change the system timezone by WMI I want to change the timezone of windows system by WMI.
But most articles about it on google just set the CurrentTimeZone property of Win32_OperatingSystem or Win32_ComputerSystem.
It will just only change the time,the name and others infomations about the timezone are not correct.
Is there a typical sample to show how to set the timezone by WMI(C#/VBScript)?


text:
Q: java decryption rsa from javascript encrypt I Passwork by RSA encryption using javascript string
I use the following pages to create privatekey and publickey
http://travistidwell.com/jsencrypt/demo/
public key and private key
I want to decode using java
I have tried many many times but have problems
Please help me.
thanks
String sprivatekey = "MIICWwIBAAKBgHWiNo/ql4zfT/DA3tr+atZZef01wrwSiPaD3M3efki7/o1NZxvP"
        + "PyjcIrGT/qMrVGE9ncj4+y+vb8C1K2gyegKJwS8vF74Dvlzt2VL/3BZpfmZ1WACt"
        + "5xNzme10lxyH2LERXOrUzr5YHsgraa+wabS90amja02/BrkY9NYi7QqXAgMBAAEC"
        + "gYBAKUQdZ1VWDw+pP2nOhOp9E7zH8aTPtERkQTQUTgEPZwrGw6szrezDOp7pwNEo"
        + "6p9RkqwXTEalkckgkTCl2rJVIcjjGsselQf0RXYAKeLUkojhl+ypVrFbMN6/IYd/"
        + "/FkV57eSY2eYZ2+wRAz18zrEtSS/wWaiRMwV6Tb9ON72IQJBANoqDT0S9R2FoQ0F"
        + "uDvXB6IlGh0/QbewYDs5/An/rLi1ZexAtBTqn9DJ9MjR7Jp2OpYaGWBgE/0J+8Dy"
        + "n+Bow7kCQQCKCNpjeMd3RQc8uQmdSFEK8b1vWxi+phB95oKfsqA1Zf7IJDvxInhJ"
        + "BkAWHK6dzWCwYR23sJrF/shkXPm3YQjPAkBVxmjUFWsIA20RuKj55g5bQukkjKVi"
        + "+larkp20tLCNIs0C+WGUQ7c4GN9EQb0b8dYRBAvsJ3pUZ6Ny9jHDwo0JAkATV2A6"
        + "de8FIE/+SzM0rbBlZzATDWGvPResfIMrG11lfhAwPRuFEz5lhRGvx38UL3Xv4PvI"
        + "BF/7hFLR9VEsR9VzAkEAzAX2TggCaPaYFpLWIZH2NSKjuOrKXLI3zEwIaVjM55dd"
        + "Kcj97JyOzC5vurPpw6TZOWiGJ3bZRswJXcCxWianMw==";

String spublickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS6nsbqyNtrv7dMm9mje98L8So"
        + "W/wgL9CzahjSHq56YcV4qyapuT9HOglCbD12xyM9bi0bvg5wkyJ37oMWNvxsiYh9"
        + "u0eLZlzOIR+2CmjeL2OZDqGqn7HFCdfbbX9mdTkm4mE+pVOsWIuts2ZegMeU9EWz"
        + "M91ZGA0mBug6VaavswIDAQAB";
String plainText="Tacdsfddfdfd";
String cipherText="YlXqYjr+rNUnh9Cta6wMWamqNsVGuRc01NA3qjtazdtcKJoJ5yfPQmq9OJo3Qc9k2JztzmFvSDyV83Bru8fl/xcflFjb/H+IL966lXGVh83QTQaVGTwMkV37iYvz+oCJmOmq6f+O34/0u0qilvgNgfAevYZY2ZWTbaGYvS1pXmQ=";

I use java string key read into PrivateKey
Method read privatekey
 public static RSAPrivateKey getPrivateKeyFromString(String key)
    throws IOException, GeneralSecurityException {
RSAPrivateKey pk;
byte[] encodedPrivateKey = Base64.decodeBase64(key);
try {
    public static final String ALGORITHM = "RSA";
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
            .fromByteArray(encodedPrivateKey);
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException(
                "wrong version for RSA private key");
    }
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement())
            .getValue();
    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus,
            privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    pk = (RSAPrivateKey) kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);
}
return pk;

}
Method decrypt java
public static final String ALGORITHM = "RSA";
public static byte[] encrypt(String text, PublicKey key) {
    byte[] cipherText = null;
    try {
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        // encrypt the plain text using the public key
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipherText = cipher.doFinal(text.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cipherText;
}
public static String decrypt(byte[] text, PrivateKey key) {
    byte[] dectyptedText = null;
    try {
        // SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        // random.nextBytes(text);
        // decrypt the text using the private key
        cipher.init(Cipher.DECRYPT_MODE, key);
        dectyptedText = cipher.doFinal(text);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return new String(dectyptedText);
}

call decrypt
public static void main(String[] args) {
    String sprivatekey = "MIICWwIBAAKBgHWiNo/ql4zfT/DA3tr+atZZef01wrwSiPaD3M3efki7/o1NZxvP"
            + "PyjcIrGT/qMrVGE9ncj4+y+vb8C1K2gyegKJwS8vF74Dvlzt2VL/3BZpfmZ1WACt"
            + "5xNzme10lxyH2LERXOrUzr5YHsgraa+wabS90amja02/BrkY9NYi7QqXAgMBAAEC"
            + "gYBAKUQdZ1VWDw+pP2nOhOp9E7zH8aTPtERkQTQUTgEPZwrGw6szrezDOp7pwNEo"
            + "6p9RkqwXTEalkckgkTCl2rJVIcjjGsselQf0RXYAKeLUkojhl+ypVrFbMN6/IYd/"
            + "/FkV57eSY2eYZ2+wRAz18zrEtSS/wWaiRMwV6Tb9ON72IQJBANoqDT0S9R2FoQ0F"
            + "uDvXB6IlGh0/QbewYDs5/An/rLi1ZexAtBTqn9DJ9MjR7Jp2OpYaGWBgE/0J+8Dy"
            + "n+Bow7kCQQCKCNpjeMd3RQc8uQmdSFEK8b1vWxi+phB95oKfsqA1Zf7IJDvxInhJ"
            + "BkAWHK6dzWCwYR23sJrF/shkXPm3YQjPAkBVxmjUFWsIA20RuKj55g5bQukkjKVi"
            + "+larkp20tLCNIs0C+WGUQ7c4GN9EQb0b8dYRBAvsJ3pUZ6Ny9jHDwo0JAkATV2A6"
            + "de8FIE/+SzM0rbBlZzATDWGvPResfIMrG11lfhAwPRuFEz5lhRGvx38UL3Xv4PvI"
            + "BF/7hFLR9VEsR9VzAkEAzAX2TggCaPaYFpLWIZH2NSKjuOrKXLI3zEwIaVjM55dd"
            + "Kcj97JyOzC5vurPpw6TZOWiGJ3bZRswJXcCxWianMw==";

    String spublickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS6nsbqyNtrv7dMm9mje98L8So"
            + "W/wgL9CzahjSHq56YcV4qyapuT9HOglCbD12xyM9bi0bvg5wkyJ37oMWNvxsiYh9"
            + "u0eLZlzOIR+2CmjeL2OZDqGqn7HFCdfbbX9mdTkm4mE+pVOsWIuts2ZegMeU9EWz"
            + "M91ZGA0mBug6VaavswIDAQAB";

    try {
        PrivateKey privateKey = RSAKey.getPrivateKeyFromString(sprivatekey);
        //PublicKey publicKey = RSAKey.getPublicKeyFromString(spublickey);
        String v = "YlXqYjr+rNUnh9Cta6wMWamqNsVGuRc01NA3qjtazdtcKJoJ5yfPQmq9OJo3Qc9k2JztzmFvSDyV83Bru8fl/xcflFjb/H+IL966lXGVh83QTQaVGTwMkV37iYvz+oCJmOmq6f+O34/0u0qilvgNgfAevYZY2ZWTbaGYvS1pXmQ=";
        //Call method 1
        String plainText1 = decrypt(v.getBytes(), privateKey);
        System.out.println("Decrypted: " + plainText1);
        //Call method 2
        String plainText2 = decrypt(v, privateKey);
        System.out.println("Decrypted: " + plainText2);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Error call Method 1
javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:346)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at com.evnit.futil.security.EncryptionUtil.decrypt(EncryptionUtil.java:146)
at com.evnit.futil.security.EncryptionUtil.main(EncryptionUtil.java:201)

Error call Method 2
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at com.evnit.futil.security.EncryptionUtil.decrypt(EncryptionUtil.java:167)
at com.evnit.futil.security.EncryptionUtil.main(EncryptionUtil.java:204)


text:
Q: How to get SNMP value by MIB name? Analog on bash:
snmpwalk -c SNMP1TV01 -v 2c 127.0.0.1 IF-MIB::ifName | grep bond0
IF-MIB::ifName.8 = STRING: bond0
snmpwalk -c SNMP1TV01 -v 2c 12.0.0.0.1 IF-MIB::ifHCOutOctets | grep 8
IF-MIB::ifHCOutOctets.8 = Counter64: 13775300423919

I can't do it by oid because ethernet interfaces changes often

A: Whilst I'm not familiar with node.js can't it retrieve the table, rather than just walking that part of the tree e.g.
snmptable -M +.  -m +ALL -v 2c -c public -Pu -Ci 127.0.0.1 IF-MIB:ifXTable
SNMP table: IF-MIB::ifXTable

index   ifName ifInMulticastPkts ifInBroadcastPkts ifOutMulticastPkts ifOutBroadcastPkts  ifHCInOctets ifHCInUcastPkts ifHCInMulticastPkts ifHCInBroadcastPkts ifHCOutOctets ifHCOutUcastPkts ifHCOutMulticastPkts ifHCOutBroadcastPkts ifLinkUpDownTrapEnable ifHighSpeed ifPromiscuousMode ifConnectorPresent ifAlias ifCounterDiscontinuityTime
1        lo                 0                 0                  0                  0 3675102238172      2759723359                   0                   0 3675102238172       2759723359                    0                    0                      ?          10             false                  ?                       0:0:00:00.00
2     bond0               959                 0                  0                  0   21395174710        43909149                 959                   0    5835176503         49589529                    0                    0                      ?        1000             false               true                       0:0:00:00.00

<not showing my other interfaces>

Extracting out the relevant value ....
snmptable -M +.  -m +ALL -v 2c -c public -Pu -Ci 127.0.0.1     IF-MIB:ifXTable | grep bond0 | awk '{print $11}'
5835176503


text:
Q: What is this component (probably a shock/vibration sensor)? The other day I received a promotional wrist band from a convention booth -- it has two LEDs that flash when you jostle it. I removed the guts to see how it works, and here is what I found:

Most of this is pretty straight-forward: LEDs, a SOT-23 transistor, some passives -- no uC that I can see (on top, at least) --  but I'm interested in the metal can in the middle, with the refdes K1. I assume this is the sensor that detects when the device has been tapped or shaken. It's a metal cylinder with two leads, and on the inside there is a smaller metal cylinder -- it might be a coil or spring, but it's hard to tell. Here's another picture where you can sort of see it:

Does anybody know what this component is called and how it works? Maybe the spring moves when shaken, changing the capacitance or inductance. Whatever it is, it must be cheap (this is a give-away promotional item). It would also be nice, I imagine, if the mechanical energy it collects is enough to wake-up the rest of the device so that it could have a no-power sleep state.
Note, too the shiny metal pad under the near end of the can, perhaps a ground needed for the operation of the device. It looks like there is some clearance between the can and the pad (and the rest of the pcb, for that matter).
UPDATE: Based on the feedback, it's probably a vibration-induced trigger switch, something like this (datasheet), that is, just a spring in a tube that makes contact with the case when it moves.

A: It's just a spring in a tube. The spring is anchored at only one end. When shaken, the other end of the spring touches the tube and completes the circuit.
The transistor functions as a simple amplifier so that the full LED current doesn't need to pass through the sensor.

A: It might be something similar to what we use in one of our products (SQ-SEN-200 from SignalQuest). It is omni-directional since it has a gold ball inside of it, which makes/breaks contact between the two leads.  It is extremely sensitive, as I can detect someone lightly tapping on the other end of the desk.  A spring is only sensitive in two axes, so you might test for that, although it would be difficult.


text:
Q: Isotope filtering - abnormal spacing on loading only I'm doing some maintenance on a PHP website that uses Isotope filtering, and I'm still learning Javascript.  Because of this, I'm having trouble figuring out how to fix a problem with Isotope.
I have a page with 40 tiles in two separate sections.  One of the sections works fine with no errors.  But in the second section, when I load the page, it displays the last 10-12 tiles on top of each other (it varies, seemingly randomly).
However, whenever I click any of the filters, it works fine, and pushes them out to the proper spacing.  So, the issue is only on the behavior during the initial load of the page.
Does anyone know what might be causing this sort of problem?

A: Try changing document.ready to window.load, which will make it wait for images to download before running isotope.
$(document).ready(function() {
  // executes when HTML-Document is loaded and DOM is ready
  $.isotope();
});

$(window).load(function() {
  // executes when complete page is fully loaded, including all frames, objects and images
 $.isotope();
});

Actually, reading the link 3rror404 posted, you can do
// layout Isotope again after all images have loaded
$container.imagesLoaded( function() {
  $container.isotope('layout');
});


text:
Q: Java: Elegant solution to get a special Date as a long? Edit:
lets say I have the date 11.11.2016 for what I want the Unix timestamp.
At the moment I just use
 final int start = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 5) / 1000L);

for 10.11.2016 it would be
     final int start = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 6) / 1000L);

But it looks somehow so basic :)
Is there maybe a better solution? I couldn't find any function in Date nor LocalTime.
Thanks!

A: It only makes sense to convert a "date" to epoch seconds if you specify a time of day and a time zone that you want the epoch seconds for.
Otherwise, the conversion is undefined, because a "date" is a 24-hour period (usually) in a specific timezone, whereas a unix timestamp is a number of seconds since 1970-1-1 00:00:00 UTC.
LocalDate.of(2016, 5, 10)

    // e.g. LocalTime.of(12, 0) or .atStartOfDay()
    // - *not* midnight, in general, since this does not always exist.
    .atTime(someLocalTime)

    // e.g. ZoneId.of("UTC")
    .atZone(someTimeZoneId)

    .toEpochSecond();


text:
Q: Magento-2 : Add "Use Config Settings" check-box to custom block form I have custom admin form and want to show "Use Config Settings" check-box to just under form field.
For Example,
In product edit page, If you open "Advanced Inventory" link, you will see "Use Config Settings" which is display default system configuration value.
I want to do same thing in my custom admin form.
Any one had did this? Please share your solution here.
Thanks


text:
Q: Splitting business date into Day Month and year into separate columns My business intelligence tool is creating a lot of issues with calculating a variance YOY, instead, I am contemplating creating a view in my Database which will allow me to subtract two columns giving me the variance.
I am trying to wrap my head around the best way to go about this, been testing datepart, convert, cast on the date but I am sure I am going the wrong way about this.
select top 1
Business_date,
CONCAT(DATEPART(MM, Business_Date),'-', DATEPART(DD, Business_Date)) as
DayMonth,
case
when DATEPART(YYYY, Business_Date) = '2019' then 2019
end
from Occupancy_Forecast;

I know the code above does not give me anything where i need to be as I am trying to see the best way to do this, what I am looking for is something like the attached screenshot:
I have also included a screenshot of the current table I am reading from so you understand the current format

A: Using @Larnu statement regarding the pivot I have been able to create a view stored containing the data required using the below to give me the desired output:
select Resort as Resort, Business_Date as Date, [2016], [2017], [2018], [2019],
[2020]
from
(select Resort, business_date, DATEPART(YYYY, Business_Date) as Year, ADR
from Occupancy_Forecast
where Business_Date > '2015-12-31') as SourceTable
PIVOT
(
AVG(ADR)
FOR YEAR IN ([2016], [2017], [2018], [2019], [2020] )
) as PivotTable


text:
Q: Maximum Volume Ring in Android I want change volume of android alarm (STREAM_RING).
I try this:
audioManager.adjustStreamVolume(
   AudioManager.STREAM_RING,
   audioManager.getStreamMaxVolume(AudioManager.STREAM_RING),
   AudioManager.FLAG_PLAY_SOUND
);

But it doesn't work and i have error(Bad direction 7)

A: You need to use setStreamVolume not adjustStreamVolume. AdjustStreamVolume is to adjust 1 level higher or lower.
audioManager.setStreamVolume(
   AudioManager.STREAM_RING,
   audioManager.getStreamMaxVolume(AudioManager.STREAM_RING),
   AudioManager.FLAG_PLAY_SOUND
);

A: Have a look at the documentation of AudioManager.adjustStreamVolume:

public void adjustStreamVolume (int streamType, int direction, int flags)
...
direction   The direction to adjust the volume. One of ADJUST_LOWER, ADJUST_RAISE, or ADJUST_SAME.

Your second parameter is none of these three values. Maybe you wanted to use setStreamValue instead?


text:
Q: number of zeros of the superposition/interference of sine oscillations There is a tricky problem to solve and we ask for your kind help.
In a rather simple version of the problem, we have a set of oscillations of type $f(x)=\sin (\omega x + \phi)$ with different phases and frequencies.
They all start at $f(x_0=0)=0$.
Is there a way to estimate or precise calculate the number of zeros of the superposition of these oscillations: $$F(x_0)= \sum_{i=1}^{m}{\sin (\omega_i x + \phi_i)}=0 $$
up to $m$. To emphasise: it is about finding a counting function $c(m)$ that gives us an estimate or precise number of zeros of the interference/superposition function; what we do NOT look for is to calculate first the roots and then count them.
As this problem resembles near to spectral theory and Fourier, any hint from other research in other disciplines or mathemtical areas that would cross with our problem would be very welcome as well. This includes also any stochastic approaches on how to determine the statistical distribution of the zeros.
Thanks

A: [EDIT 2 this is actually an answer, see below]. Not a complete answer but it's a start. First note that, depending on the properties of the frequencies $\omega_j$ your function $F(x)$ has a very different behavior. When the frequencies are rational numbers, the function $F(x)$ is periodic. To find the number of zeros in an interval $[0,X]$ you will need the explicit form of the frequencies. If the frequencies are rationally independent (i.e. linearly independent over the set of rationals) your function is almost periodic. You can find some information in this wikipedia article.
Now note that you can write the number of zeros of $F(x)$ in $[0,X]$ as
\begin{equation}
N(X) = \int_0^X \delta(F(x)) |F'(x)| dx \tag{1}
\end{equation}
where $\delta()$ is Dirac delta function. Now, with the assumption of rational independence, you can use the theorem of the average of Weyl:
$$
\lim_{X\to\infty} \frac{1}{X} \int_0^X f(x) dx = \langle f \rangle
$$
where $\langle f \rangle$ is the "phase-space" average over an $m$ dimensional torus ($m$ is the number of frequencies). More precisely
$$\langle f \rangle = \left ( \prod_{j=1}^{m} \int_0^{2\pi} \frac{d\theta_j}{2\pi} \right ) f(\theta_1,\ldots,\theta_m) \tag{2}
$$
Now, for large $X$ you can write
$$N(X) \simeq X \langle N \rangle$$
where the average $\langle N \rangle $ can be computed as a phase space average. Now typically phase space average are much easier to compute than "time average" (your $x$) and you should be able to estimate $\langle G \rangle$.
In any case your question is so natural that I would guess that somebody might have already computed the answer.
There is a book by Besicovitch on almost periodic functions that may contain some information. Not surprisingly the title is "Almost periodic functions". If you google "theorem of average", "Weyl", you should get more information on what I just wrote above.
Hope this helps.
EDIT
I guess it should be quite clear that in general your function has an infinite number of zeros, therefore I interpreted your question as: find the number of zeros in a given interval $[0,X]$ (possibly with $X$ large)
EDIT 2: Answer
It turns out that Eq. (1) is basically Rice's formula for counting zeros, and it's a big thing in signal processing (are you an engineer?). You can find some more information in the bible here. There you will basically also find the answer, at least for the case of rationally independent frequencies and large $m$ as in this case your function is a Gaussian random process. In this case the average number of zeros in an interval $[0,T]$ (sorry I switched to time notation, it just makes much more sense) is given by
$$ \langle N(T) \rangle = T \frac{1}{\pi} \sqrt{-\frac{\psi''(0)}{\psi(0)}} $$
where $\psi(\tau)$ is the correlation function:
$$ \psi(\tau) = \lim_{T\to\infty} \frac{1}{T} \int_0^T F(t) F(t+\tau) dt $$
Now you should be able to do the final steps and get the answer.
Hint. If your frequencies $\omega_j$ are reasonably distributed $N(T)$ is basically independent of $m$. For instance, if $\omega_j$ are uniformly distributed in $[0,1]$ then
$$ N(T) \approx \frac{T}{\pi \sqrt{3}} $$


text:
Q: DRF - how to return SerializerMethodField() value in json response How to return SerializerMethodField() field value as a json reponse in APIView?

A: am not sure if i understand the question correctly but
you don't return SerializerMethodField() value as json reponse in APIView directly,
SerializerMethodField() is to be used inside the serializer as it shows in the docs here
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = '__all__'

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

after
you can use the serializer in the view as show here
from snippets.models import Snippet
from users.serializers import UserSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class UsersList(APIView):

    def get(self, request, format=None):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


text:
Q: break a text file into parts/lines and place the parts into text boxes Right now my code takes the entire text file and just places it all into one text box.  What I am trying to figure out how to do is have it place each line of the file into each separate text box.
namespace HomeInventory2
{
    public partial class Form1 : Form
    {
        public Form1(string prepopulated)
        {
            InitializeComponent();
            textBoxAmount.Text = prepopulated;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            CreateInventory create = new CreateInventory();
            create.ItemAmount = textBoxAmount.Text;
            create.ItemCategory = textBoxCategories.Text;
            create.ItemProperties = textBoxValue.Text;
            create.ItemValue = textBoxValue.Text;

            InventoryMngr invtryMngr = new InventoryMngr();
            invtryMngr.Create(create);

        }
    }

A: Assuming that the order of the lines is always the same and that each TextBox belongs to a line:
IEnumerable<String> lines = File.ReadLines(path);
textBoxAmount.Text = lines.ElementAtOrDefault(0);
textBoxCategories.Text = lines.ElementAtOrDefault(1);
textBoxValue.Text = lines.ElementAtOrDefault(2);
...

Enumerable.ElementAtOrDefault<TSource> Method

Returns the element at a specified index in a sequence or a default
  value if the index is out of range (null in this case).

A: You could use System.IO.File.ReadAllLines(string filename).
What this does is reads each line of the file into a String array.
You could then do something like:
using System.IO;

//Namespace, Class Blah Blah BLah

String[] FileLines = File.ReadAllLines("Kablooey");

textBox1.Text = FileLines[0];

textbox2.Text = FileLines[1];

And so on. I hope this helps :)


text:
Q: How to know wifi connection has internet enabled using windows apis I am using Windows XP. I am using wlanapi dll for getting API of wifi. When I connected with any wifi interface, How to know wifi connection has internet connection enabled or not?
Is there any API or way to know??

A: You could try pinging a known server
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366050(v=vs.85).aspx
If not that I'm sure you could find something else in that library


text:
Q: dynamically create uiimageview when BOOL var is true I asked earlier on how to display uiimageview when bool var is true. Now I need to create uiimageview dynamically. How will I able to create an uiimageview consecutively if the app detects that bool var is true?
Sample:
BOOL var1= true;
BOOL var2 = false;
BOOL var3 = true;

if(var1)
    {
        cell.incentive1.hidden = false;
    }
    if(var2)
    {
        cell.incentive2.hidden = false;
    }
    if(var3)
    {
        cell.incentive3.hidden = false;
    }

How will i make uiimageview for var3 to be displayed beside var1's uiimageview?

A: set a your booleans as properties
@property (strong, atomic) BOOL var3;

Implement the setters in order to create the image view when is true
- (void) setVar3:(BOOL)var3
{
    _var3 = var3;
    if (_var3){
        [self createUIImageView];
    }
}

I assume that you already got how to implement createUIImageView


text:
Q: c++ create reference variable inside function Suppose I have the following function:
void myFunc(P& first, P& last) {
    std::cout << first.child.grandchild[2] << endl;
    // ...
}

Now, let's assume that first.child.grandchild[2] is too long for my purposes.  For example, suppose it will appear frequently in equations inside myFunc(P&,P&).  So, I'd like to create some sort of symbolic reference inside the function so that my equations would be less messy.     How could I do this?
In particular, consider the code below.  I need to know what statement I could insert so that not only would the output from line_1a always be the same as the output from line_1b, but also so that the output from line_2a would always be the same as the output from line_2b.  In other words, I don't want a copy of the value of first.child.grandchild, but a reference or symbolic link to the object first.child.grandchild.
void myFunc(P& first, P& last) {
    // INSERT STATEMENT HERE TO DEFINE "g"

    std::cout << first.child.grandchild[2] << endl; // line_1a
    std::cout << g[2] << endl;                      // line_1b

    g[4] = X; // where X is an in-scope object of matching type

    std::cout << first.child.grandchild[4] << endl; // line_2a
    std::cout << g[4] << endl;                      // line_2b
    //...
}

A: Use a pointer - then you can change it in the function.
WhateverGrandchildIs *ptr=&first.child.grandchild[2];

std::cout << *ptr << std::endl;

ptr=&first.child.grandchild[4];

std::cout << *ptr << std::endl;

A: Say that the type of grandchild is T and size is N; then below is the way to create a reference for an array.
void myFunc(P& first, P& last) {
  T (&g)[N] = first.child.grandchild;
  ...
}

I would not prefer pointer here, though it's also a possible way. Because, the static size of array is helpful to a static analyzer for range checking.
If you are using C++11 compiler then auto is the best way (mentioned by @SethCarnegie already):
auto &g = first.child.grandchild;


text:
Q: Conditionally loading Facebook PHP SDK in shortcode Since 3.3 we can enqueue scripts conditionally right in our shortcode functions, but when I tried to do this with some PHP class (uses session_start() in the __construct() function) as you can guess it gives me the headers already sent error.
The problem is (this is using the Facebook PHP SDK in conjunction with the JS SDK), I only want this class to be instantiated if a shortcode is present on the post and if the current post has 2 meta fields filled out already (the class needs these 2 values [App ID and App Secret]).
Is there a simple solution to this? If so, what can I change in the following code to allow this?
public function fb_connect_shortcode( $atts, $content = null ) {
    extract( shortcode_atts( array( ), $atts ) ); /**/ global $post;
    $app_id = get_post_meta( $post->ID, $this->meta_prefix . 'AppID', true );
    $app_secret = get_post_meta( $post->ID, $this->meta_prefix . 'AppSecret', true );

    if( $app_id !== '' && $app_secret !== '' ) {

        /**
         * This is the class I am trying to instantiate conditionally
         * but since it uses session_start(), it can't send out headers
         */
        $facebook = new Facebook( array(
          'appId'  => $app_id,
          'secret' => $app_secret,
        ) );

        // See if there is a user from a cookie
        $user = $facebook->getUser();

        if( $user ) {
            try {
                // Proceed knowing you have a logged in user who's authenticated.
                $user_profile = $facebook->api( '/me' );
                $app_id = $facebook->getAppId();
            } catch( FacebookApiException $e ) {
                echo '
' . htmlspecialchars( print_r( $e, true ) ) . '
';
                $user = null;
            }
        }

        wp_enqueue_script( 'jw-fbsdk', plugins_url( 'jw-fbsdk.js', __FILE__ ), array(), '3.3.1', true );
        wp_localize_script( 'jw-fbsdk', 'jwuc', array(
            'appId' => $app_id,
            'channelUrl' => plugins_url( 'channel.php', __FILE__ )
        ) );

        if( is_null( $content ) )
            $content = 'Connect with Facebook';

        if( isset( $user_profile ) && $user_profile ) {
            return $user_profile['name'];
        } else {
            return '
' . $content . '
';
        }

    } else {

        return "You forgot to add your App ID and/or App Secret! Facebook needs these. :)";

    }

}

A: You can try to use the_posts filter to search for you shortcode and require the sdk, something like this:
function has_my_FB_shortcode($posts) {
    if ( empty($posts) )
        return $posts;
    $found = false;
    foreach ($posts as $post) {
        if ( stripos($post->post_content, '[my_shortcode') ){
            $found = true;
            break;
        }
    }

    if ($found)
        require('path/to/facebook_sdk.php');

    return $posts;
}
add_action('the_posts', 'has_my_FB_shortcode');

A: I ended up solving this myself, but with help from @Bainternet (checking if shortcode is present in the post content).
What I did was created a variable in my class called facebook, where I store the PHP SDK class. I used the wp hook to start the Facebook class if a few things are set and correct, this hook is allowing me to use global $post so that I can grab the meta values.
require 'facebook.php';
$urgent = JW_Urgent::getInstance();

class JW_Urgent {

    private static $instance;
    public $facebook;

    // Construct the class' data
    private function __construct() {

        $this->facebook = null;

        add_action( 'wp', array( &$this, 'define_facebook' ) );
        add_shortcode( 'jw-connect', array( &$this, 'fb_connect_shortcode' ) );

    }

    public static function getInstance() {
        if ( is_null( self::$instance ) )
            self::$instance = new JW_Urgent();

        return self::$instance;
    }

    public function define_facebook() {
        global $post;

        $app_id = get_post_meta( $post->ID, $this->meta_prefix . 'AppID', true );
        $app_secret = get_post_meta( $post->ID, $this->meta_prefix . 'AppSecret', true );

        if( !is_null( $post ) && ( $app_id !== '' && $app_secret !== '' ) && $post->post_type == $this->post_type ) {

            if( strpos( $post->post_content, '[jw-connect' ) !== false ) {

                $this->facebook = new Facebook( array(
                    'appId' => $app_id,
                    'secret' => $app_secret
                ) );

            }

        }

    }

    public function fb_connect_shortcode( $atts, $content = null ) {
        extract( shortcode_atts( array( ), $atts ) ); /**/ global $post;
        $app_id = get_post_meta( $post->ID, $this->meta_prefix . 'AppID', true );
        $app_secret = get_post_meta( $post->ID, $this->meta_prefix . 'AppSecret', true );

        if( $app_id !== '' && $app_secret !== '' && !is_null( $this->facebook ) ) {

            // See if there is a user from a cookie
            $user = $this->facebook->getUser();

            if( $user ) {
                try {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $this->facebook->api( '/me' );
                    $app_id = $this->facebook->getAppId();
                } catch( FacebookApiException $e ) {
                    echo '
' . htmlspecialchars( print_r( $e, true ) ) . '
';
                    $user = null;
                }
            }

            wp_enqueue_script( 'jw-fbsdk', plugins_url( 'jw-fbsdk.js', __FILE__ ), array(), '3.3.1', true );
            wp_localize_script( 'jw-fbsdk', 'jwuc', array(
                'appId' => $app_id,
                'channelUrl' => plugins_url( 'channel.php', __FILE__ )
            ) );

            if( is_null( $content ) )
                $content = 'Connect with Facebook';

            if( isset( $user_profile ) && $user_profile ) {
                return $user_profile['name'];
            } else {
                return '
' . $content . '
';
            }

        } else {

            return "You forgot to add your App ID and/or App Secret! Facebook needs these. :)";

        }

    }

}


text:
Q: Remove duplication in new fangled case with patterns This works but is ugly. But I can't find how to make optional keys in a pattern. I am probably missing somehting obvious:
post '/api/users' do
  args = JSON.parse(request.body.read, {symbolize_names: true})
  case args
  in {name: name, email: email, bio: bio, password: password}
    User.create(args)
    200
  in {email: email, bio: bio, password: password}
    User.create(args)
    200
  in {email: email, password: password}
    User.create(args)
    200
  else
    400
  end
end


text:
Q: How to rewrite SQL joins into window functions? Database is HP Vertica 7 or PostgreSQL 9.
create table test (
id int,
card_id int,
tran_dt date,
amount int
);

insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);

Of the payment cards used in the last 1 day, what is the maximum amount charged on that card in the last 90 days.
select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;

Results are correct
card_id    max
-------    ---
1          30

I want to rewrite the query into sql window functions.
select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;

But result set does not match, how can this be done?
Test data here:
http://sqlfiddle.com/#!17/db317/1

A: I can't try PostgreSQL, but in Vertica, you can apply the ANSI standard OLAP window function.
But you'll need to nest two queries: The window function only returns sensible results if it has all rows that need to be evaluated in the result set.
But you only want the row from '2017-07-06' to be displayed.
So you'll have to filter for that date in an outer query:
WITH olap_output AS (
  SELECT
    card_id
  , tran_dt
  , MAX(amount) OVER (
      PARTITION BY card_id
      ORDER BY tran_dt
      RANGE BETWEEN '90 DAYS' PRECEDING AND CURRENT ROW
    ) AS the_max
  FROM test
)
SELECT
  card_id
, the_max
FROM olap_output
WHERE tran_dt='2017-07-06'
;

card_id|the_max
      1|     30

A: As far as I know, PostgreSQL Window function doesn't support bounded range preceding thus range between '90 days' preceding won't work.  It does support bounded rows preceding such as rows between 90 preceding, but then you would need to assemble a time-series query similar to the following for the Window function to operate on the time-based rows:
SELECT c.card_id, t.amount, g.d as d_series
FROM generate_series(
  '2017-04-06'::timestamp, '2017-07-06'::timestamp, '1 day'::interval
) g(d)
CROSS JOIN ( SELECT distinct card_id from test ) c
LEFT JOIN test t ON t.card_id = c.card_id and t.tran_dt = g.d
ORDER BY c.card_id, d_series

For what you need (based on your question description), I would stick to using group by.


text:
Q: Laravel 4, Retrive morphed Parent Model, querying child I didn't know how to ask the question so, the question is not as clear as the description. But here it goes.
I want to query the parent Model, by quering the child Model. Here is the basic Models:
    //Gig.php
    class Gig extends Eloquent
{
    public function gigable()
    {
        return $this->morphTo('profile');
    }
}

//Band.php

class Band extends Eloquent {
public function gigs()
    {
        return $this->morphMany('Gig','profile');
    }
}
//Musician.php

class Musician extends Eloquent {
public function gigs()
    {
        return $this->morphMany('Gig','profile');
    }
}

Now, I know I can do something like this:
Gig::find(1)->gigable

Is there a way that I can retrieve gigables in one query
and for example for my api I can return all the gigable at once.
Something like:
Gig::where('id','>',1)->gigable

I know thats doesn't work.
Such as in reverse of this I can do something like,
Band::with('gigs')->where('created_at','<',Carbon::now())->get();

A: Use as follows
//Gig.php
class Gig extends Eloquent {
    public function gigable()
    {
        return $this->morphTo();
    }
}

//Band.php
class Band extends Eloquent {
public function gigs()
    {
        return $this->morphMany('Gig','gigable');
    }
}

//Musician.php
class Musician extends Eloquent {
public function gigs()
    {
        return $this->morphMany('Gig','gigable');
    }
}

Then you will be able to get the gigs this way:
$band = Band::with('gigs')->where('created_at','<',Carbon::now())->get();
$gigs = $band->gigs;

If this is what you wanted... your question is unclear


text:
Q: Best way to use Xcode with 2 Firebase projects - 2 GoogleService-Info.plist I have a Xcode project which builds an app which is used in two parts of the world. We currently have a Firebase Project for each project which translates to two GoogleService-Info.plist for each file. What is the best way to manage this inside Xcode project? The way I was thinking of was having 2 targets named appropriately and have the files be in the Target membership for the appropriate target.
Is there a better way?

A: You don't have to create another target. You can just create another Scheme for the same target. Product > Scheme > New Scheme
With your new scheme created you can go into the Build Settings > Info.plist File and set each configuration to their respective GoogleService-Info.plist.