text:
Q: How to compare similar related keys in array of hashes in Ruby? I have an array of hashes, let's say
arr = [
  {:country=>"Portugal", :rating=>"Great", :rating2=>"Average", :city1=>"Lisbon", :city2=>"Porto"},
  {:country=>"USA", :rating=>"Good", :rating2=>"Great", :city1=>"NYC", :city2=>"Birmingham"},
  {:country=>"UK", :rating=>"Dismal", :rating2=>"Poor", :city1=>"Birmingham", :city2=>"London"}
]

I'm trying to check through this array for key:value matches between hashes based on the linked columns (rating1/rating2, city1/city2) and give the matches an id as a new key:value pair. I also trying to search for multiple search terms.
E.g. if searching for "city", it should return:
{:country=>"Portugal", :rating=>"Great", :rating2=>"Average", :city1=>"Lisbon", :city2=>"Porto", :match=>"0"},

{:country=>"USA", :rating=>"Good", :rating2=>"Great", :city1=>"NYC", :city2=>"Birmingham", :match=>"1"},

{:country=>"UK", :rating=>"Dismal", :rating2=>"Poor", :city1=>"Birmingham", :city2=>"London", :match=>"1"}

If searching for "city" and "rating" together, it should return:
{:country=>"Portugal", :rating=>"Great", :rating2=>"Average", :city1=>"Lisbon", :city2=>"Porto", :match=>"1"},

{:country=>"USA", :rating=>"Good", :rating2=>"Great", :city1=>"NYC", :city2=>"Birmingham", :match=>"1"},

{:country=>"UK", :rating=>"Dismal", :rating2=>"Poor", :city1=>"Birmingham", :city2=>"London", :match=>"1"}

(Because Portugal's rating1 matches with USAs rating2, and USA's city2 matches with UK's city1)
So far I can match on a single column and with a single attribute, but I'm having trouble when trying to work with the similar columns and multiple attributes:
def search_id(elements, search_key)
  # Get rid of elements with nil values.
  target_elements = elements.reject {|e| e[search_key].nil?}

  result = []
  id = 0

  # Iterate through target_elements
  target_elements.each do |currentElement|

    # Check for elements with same value in the result array
    match = result.find {|previousElement| currentElement[search_key] == previousElement[search_key]}

    if match
      currentElement[:id] = match[:id]
    else
      currentElement[:id] = id
      id += 1
    end

    # Add element to result
    result << currentElement
  end

  result
end

A: I have assumed that the keys :rating should be :rating1.
Based on my understanding of the question, you could obtain the desired return values by executing add_counts below.
def add_counts(arr, *key_matches)
  arr.map { |h| h.merge(match: count_matches(arr, key_matches, h).to_s) }
end

def count_matches(arr, key_matches, h)
  arr.count { |g| match_either_pair?(key_matches, h, g) } - 1
end

def match_either_pair?(key_matches, h, g)
  key_matches.any? { |key_pair| match_either_key?(h, g, key_pair) }
end

def match_either_key?(h, g, key_pair)
  (h.values_at(*key_pair) & g.values_at(*key_pair)).any?
end

Let's try it.
arr = [
  {:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
   :city1=>"Lisbon", :city2=>"Porto"},
  {:country=>"USA", :rating1=>"Good", :rating2=>"Great", :city1=>"NYC",
   :city2=>"Birmingham"},
  {:country=>"UK", :rating1=>"Dismal", :rating2=>"Poor",
   :city1=>"Birmingham", :city2=>"London"}
]

add_counts(arr, [:city1, :city2])
  #=> [{:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #     :city1=>"Lisbon", :city2=>"Porto", :match=>"0"},
  #    {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #     :city1=>"NYC", :city2=>"Birmingham", :match=>"1"},
  #    {:country=>"UK", :rating1=>"Dismal", :rating2=>"Poor",
  #     :city1=>"Birmingham", :city2=>"London", :match=>"1"}]

add_counts(arr, [:rating1, :rating2], [:city1, :city2])
  #=> [{:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #     :city1=>"Lisbon", :city2=>"Porto", :match=>"1"},
  #    {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #     :city1=>"NYC", :city2=>"Birmingham", :match=>"2"},
  #    {:country=>"UK", :rating1=>"Dismal", :rating2=>"Poor",
  #     :city1=>"Birmingham", :city2=>"London", :match=>"1"}]

Let's examine each of the methods in reverse order. I assume arr is as above and
key_matches = [[:rating1, :rating2], [:city1, :city2]]

match_either_key?
Suppose
h = arr[0]
  #=> {:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #    :city1=>"Lisbon", :city2=>"Porto"}
g = arr[1]
  #=> {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #    :city1=>"NYC", :city2=>"Birmingham"}

First,
key_pair = [:rating1, :rating2]

a = h.values_at(*key_pair)
  #=> ["Great", "Average"]
b = g.values_at(*key_pair)
  #=> ["Good", "Great"]
c = a & b
  #=> ["Great"]
c.any?
  #=> true

As c.any? => true there is no need to test for
key_pair = [:city1, :city2]

but had we done so,
a = h.values_at(*key_pair)
  #=> ["Lisbon", "Porto"]
b = g.values_at(*key_pair)
  #=> ["NYC", "Birmingham"]
c = a & b
  #=> []
c.any?
  #=> false

match_either_pair?
As before, assume
h = arr[0]
  #=> {:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #    :city1=>"Lisbon", :city2=>"Porto"}
g = arr[1]
  #=> {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #    :city1=>"NYC", :city2=>"Birmingham"}

then
key_pair = key_matches[0]
  #=> [:rating1, :rating2]
match_either_key?(h, g, key_pair)
  #=> true

The latter was computed above. Since it was found to return true there is no need to compute the value for key_matches[1].
count_matches
Again, we assume
h = arr[0]
  #=> {:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #    :city1=>"Lisbon", :city2=>"Porto"}

The first value passed to the block is h:
g = arr[0]

As h == g #=> true both pairs obviously match:
match_either_pair?(key_matches, h, g)
  #=> true

Next
g = arr[1]
  #=> {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #    :city1=>"NYC", :city2=>"Birmingham"}

and, as previously determined,
match_either_pair?(key_matches, h, g)
  #=> true

Lastly,
g = arr[2]
  #=> {:country=>"UK", :rating1=>"Dismal", :rating2=>"Poor",
  #    :city1=>"Birmingham", :city2=>"London"}
match_either_pair?(key_matches, h, g)
  #=> false

(Trust me on the last calculation.)
As arr[0] matches itself and arr[1], count returns 2.
We subtract 1 to obtain the number of matches with other elements of arr.
add_counts
h = arr[0]
n = count_matches(arr, key_matches, h)
  #=> 1
s = n.to_s
  #=> "1"
h.merge(match: s)
  #=> {:country=>"Portugal", :rating1=>"Great", :rating2=>"Average",
  #    :city1=>"Lisbon", :city2=>"Porto", :match=>"1"}

h = arr[1]
n = count_matches(arr, key_matches, h)
  #=> 2
s = n.to_s
  #=> "2"
h.merge(match: s)
  #=> {:country=>"USA", :rating1=>"Good", :rating2=>"Great",
  #    :city1=>"NYC", :city2=>"Birmingham", :match=>"2"}

h = arr[2]
n = count_matches(arr, key_matches, h)
  #=> 1
s = n.to_s
  #=> "1"
h.merge(match: s)
  #=> {:country=>"UK", :rating1=>"Dismal", :rating2=>"Poor",
  #    :city1=>"Birmingham", :city2=>"London", :match=>"1"}

If the key :match is to be interpreted as a boolean, where '1' and '0' represent true and false respectively, change add_counts to the following.
def add_if_match(arr, *key_matches)
  arr.map { |h| h.merge(match: [count_matches(arr, key_matches, h), 1].min.to_s) }
end


text:
Q: How is a query used in a crystal report? I would really like to know if the query field will update on the report just as it does on the query itself. In other words, when I update a material price on the query, will it also update when the report is run?

A: If you refresh the report (F5), the field's values will be refreshed.
If you select Databae | Verify Database, the field's definition will be updated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php if return == false echo something I'm using a include file to translate my text. it works pretty good, but now I need to on button click translate some mor words, and return doesn't work anymore, but echo does.
so what I'm searching is a way of know if return is possible or not, code example
for ($i = 0; $i < count($palavras); $i++) {
    if ($palavras[$i] == $palavra) {
        if($lingua == 1) {
            return $traducao_1[$i];
        }
        if($lingua == 2) {
            return $traducao_2[$i];
        }
    }
}

this one works good first time page is executed, since this is included file.
how to make this?
if(!return $traducao_1[$i]) {

thanks
ok, tryed to answer, but always got an error, so I'm editing this as answer
Thank you all for help, I manage a way of make it work like adding one action to the function and checking if action == , then do something, like this
function test($palavra, $lingua, $accao) {
for ($i = 0; $i < count($palavras); $i++) {
    if ($palavras[$i] == $palavra) {
        if($lingua == 1) {
            if($accao != "2_chamada") {
                return $traducao_1[$i];
            } else {
                echo $traducao_1[$i];
            }
        }
    }
}

}
Again, thanks for help

A: maybe check to see if it's set first before returning
for ($i = 0; $i < count($palavras); $i++) {
    if ($palavras[$i] == $palavra) {
        if($lingua == 1) {
            $return = $traducao_1[$i];
            if($return != false) {
                return $return;
            } else {
                echo 'something';
            }
        }
        if($lingua == 2) {
            $return = $traducao_2[$i];
            if($return != '') {
                return $return;
            }
        }
    }
}

A: return can only be used in functions
i reccommend this for you
function test($palavras,$palavra,$traducao_1,$traducao_2){
    for ($i = 0; $i < count($palavras); $i++) {
        if ($palavras[$i] == $palavra) {
            if($lingua == 1) {
                return $traducao_1[$i];
            }
            if($lingua == 2) {
                return $traducao_2[$i];
            }
        }
    }
}

if(!test($palavras)) {


text:
Q: How to select word in TextBox with given screen coordinates? I have an image of arrow, which follow the finger. When I lift finger I want to select a word in the TextBox under the end of arrow. So I have a screen coordinates in
imgArrow_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)

event and have to fire
TextBox_Tap(object sender, System.Windows.Input.GestureEventArgs e)

to get right position for cursor in TextBox.
The question is how to TextBox_Tap() fired with given coordinates, because I can't construct GestureEventArgs e myself.
Thank you!

A: Try to do this:
input.getWordUnderPosition(x, y);


text:
Q: How do client certificates work? I am working with a REST service provider and they want me to use a client certificate provided by them when making HTTP call.
How does a client cert achieve authentication?
If someone has a copy of the client cert, they too can be authenticated right?
Does a client cert offer anything else beside authentication?
How are they different from a username/password authentication?

A:
How does a client cert achieve authentication?

By being either signed by someone the peer trusts (including self-signing), or signed by someone that is trusted by someone the peer trusts, etc.

If someone has a copy of the client cert, they too can be authenticated right?

Wrong. They would also need the private key.

Does a client cert offer anything else beside authentication?

No.

How are they different from a username/password authentication?

Much more secure. No password-guessing is possible.
However There is no such thing as a 'client certificate provided by them'. The process of generating a client certificate starts with you. You generate a key pair and a Certificate Signing Request (CSR) and you have it signed by a CA. Or you generate a self-signed certificate. You then provide your certificate to them. If they are proposing to carry out all these steps and provide the resulting key pair and certificate to you, they do not know what they are talking about and should be severely chastised for security breaches. A private key is only private if no-one else has a copy.


text:
Q: Firebase configuration I'm developing an iOS application and my pod file looks like
platform :ios, '8.0'
use_frameworks!

target 'MYAPP' do
    pod 'Google-Mobile-Ads-SDK'
    pod 'Google/SignIn'
    pod 'Alamofire', '~> 4.0'
    pod 'AlamofireImage', '~> 3.1'
end

target 'MYAPPTests' do
    pod 'Google-Mobile-Ads-SDK'
    pod 'Google/SignIn'
    pod 'Alamofire', '~> 4.0'
    pod 'AlamofireImage', '~> 3.1'
end

target 'MYAPPUITests' do
    pod 'Google-Mobile-Ads-SDK'
    pod 'Google/SignIn'
    pod 'Alamofire', '~> 4.0'
    pod 'AlamofireImage', '~> 3.1'
end

When I run the application and keep finding the following warning in the console:

[Firebase/Core][I-COR000003] The default Firebase app has not yet
  been configured. Add [FIRApp configure] to your application
  initialization. Read more: ".

So in my appdelegate, I had added FIRApp.configure() which results in a crash

' [Firebase/Messaging][I-IID001000] Firebase is not set up
  correctly. Sender ID is nil or empty. 2017-06-14 18:25:37.044
  MYAPP[10520:128089] *** Terminating app due to uncaught exception
  'com.firebase.instanceid', reason: 'Could not configure Firebase
  InstanceID. Google Sender ID must not be nil or empty.''

Is it the GoogleModbileAdsSDK which required the Firebase config?
What am I missing here?

A: Check this out
https://firebase.google.com/docs/ios/setup
You need to add to the pod file the ones you need to use from database

A: If you don't want to install other google packages then use
pod 'GoogleSignIn'

it will only install the package require for googleSignIn

A: try to add this code in AppDelegate.swift
override init() {
        FirebaseApp.configure()
}

instead of configureing in :
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool


text:
Q: JSP Servlet MYSQL query does not execute So I'm fighting with this issue for 2 hours straight and I cannot find a solution.
I have 2 files. Manage.jsp where I'm printing out whole table with data and there I have 2 submit buttons - 1 to delete specific row, other to download a file from within that row.
Submit buttons pass a string regarding to a specific row with a unique name that allows to identify whole row which will be deleted/downloaded within a servlet file.
Similar method works with inserting or other queries but for this one it doesn't seem to work. It is strange especially because same command in MySQL Workbench actually does the job.
@WebServlet("/ManageFiles")
public class ManageFiles extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String alert = "";
        String remove = request.getParameter("remove");
        String download = request.getParameter("download");
        Connection con = null;
        if (remove != null) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String DB_NAME = "wap_dama";
                out.println("test");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?serverTimezone=UTC","root","asd123");
                PreparedStatement ps = con.prepareStatement("delete from wap_dama.files where FileName = ?");
                ps.setString(1, remove);
                int row = ps.executeUpdate();
                if (row > 0)
                {
                    out.println(row);
                    alert = "Your file was successfully deleted!";
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }

As for the jsp code

                  <%
                  try
                   {
                        Class.forName("com.mysql.cj.jdbc.Driver");
                        String DB_NAME = "wap_dama";
                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?serverTimezone=UTC","root","asd123");
                        PreparedStatement ps = con.prepareStatement("SELECT id_files, FileName, FileExtension, FileSize FROM files WHERE users_id_users=?");
                        int id = (int) session.getAttribute("id");
                        ps.setInt(1, id);
                        ResultSet rs =ps.executeQuery();
                        //Statement stmt=con.createStatement();
                        //ResultSet rs=stmt.executeQuery(ps);
                        while(rs.next())
                        {

                    %>

                            <%out.println(rs.getString("FileName")); %>
                            <%out.println(rs.getString("FileExtension")); %>
                            <%out.println(rs.getInt("FileSize")); %>
                            <button type="submit" class="btn btn-warning" name="download" value="<%out.println(rs.getString("FileName")); %>">Download</button>
                            <button type="submit" class="btn btn-danger" name="remove" value="<%out.println(rs.getString("FileName")); %>">Remove</button>

                      <%
                      }
                      %>

Any thoughts?

A: Okay, seems like the problem has been fixed by simply using .strip() function next to variable containing name of the file. For some reason there must have been some additional white spaces added and therefore resulting in error.


text:
Q: How to re.sub() what i don't want in a string? I have this :
var1 = {u'data-sport_id': u'basket_us', u'data-event_id':     u'sacramento_kings__golden_state_warriors', u'data-compet_id': u'nba_-_matchs', u'title': u'Basket US - NBA - Matchs - Sacramento Kings // Golden State Warriors - 1 avril 2018 - 4h10', u'data-name': u'sportif.clic.accueil.zone_centrale.details', u'href': u'/event/523450/sports/basket-us/nba-matchs/golden-state-warriors-chez-les-sacramento-kings', u'data-placement': u'bottom', u'data-toggle': u'tooltip', u'class': [u'trow--event', u'tc-track-element-events']}
var2 = {u'data-sport_id': u'rugby_a_xiii', u'data-event_id': u'st_georgeilla_dragons__newcastle_knights', u'data-compet_id': u'nrl', u'title': u'Rugby \xe0 XIII - NRL - St George/Illa Dragons // Newcastle Knights - 1 avril 2018 - 8h10', u'data-name': u'sportif.clic.accueil.zone_centrale.details', u'href': u'/event/521076/sports/rugby-%C3%A0-xiii/nrl/st-georgeilla-dragons-newcastle-knights', u'data-placement': u'bottom', u'data-toggle': u'tooltip', u'class': [u'trow--event', u'tc-track-element-events']}

And I want to keep :
var1 = basket_us
var2 = rugby_a_xiii

I'm trying things this but it doesn't work :
re.findall(r"data-sport_id':(.)*'(.)*'", var1)
re.findall(r"data-sport_id':(.)*'(.)*'", var2)

But I would like to know, can I do a re.sub() and only keep what I want ?
(.)*data-sport_id(.)*[WHAT I WANT]'(.)*

A: Those are dicts, you can access them like:
Code:
var1.get('data-sport_id', '')

or if you are sure the key will be present like:
var1['data-sport_id']

Test Code:
var1 = {u'data-sport_id': u'basket_us',
        u'data-event_id': u'sacramento_kings__golden_state_warriors',
        u'data-compet_id': u'nba_-_matchs',
        u'title': u'Basket US - NBA - Matchs - Sacramento Kings // Golden State Warriors - 1 avril 2018 - 4h10',
        u'data-name': u'sportif.clic.accueil.zone_centrale.details',
        u'href': u'/event/523450/sports/basket-us/nba-matchs/golden-state-warriors-chez-les-sacramento-kings',
        u'data-placement': u'bottom', u'data-toggle': u'tooltip',
        u'class': [u'trow--event', u'tc-track-element-events']}
var2 = {u'data-sport_id': u'rugby_a_xiii',
        u'data-event_id': u'st_georgeilla_dragons__newcastle_knights',
        u'data-compet_id': u'nrl',
        u'title': u'Rugby \xe0 XIII - NRL - St George/Illa Dragons // Newcastle Knights - 1 avril 2018 - 8h10',
        u'data-name': u'sportif.clic.accueil.zone_centrale.details',
        u'href': u'/event/521076/sports/rugby-%C3%A0-xiii/nrl/st-georgeilla-dragons-newcastle-knights',
        u'data-placement': u'bottom', u'data-toggle': u'tooltip',
        u'class': [u'trow--event', u'tc-track-element-events']}

print(var1.get('data-sport_id', ''))
print(var2.get('data-sport_id', ''))

Results:
basket_us
rugby_a_xiii


text:
Q: SwiftUI + Firebase - Listener not listening for changes? I've set up a listener, but it doesn't seem to be changing according to changes in the data. The flow is the following:

*

*If userCustomHabit is empty, user sees a button

*When clicked, user can enter text in a TextField from a sheet to add to userCustomHabit (an array of strings)

*Now that userCustomHabit is not empty, they should see something else

However, the problem I'm seeing is that userCustomHabits isn't updating in the view itself even though it is updating in the Firestore database.
Anyone know why this is? Included code below:
View
@ObservedObject var viewModel = RoutinesViewModel()

Group {
  if self.viewModel.userCustomHabits.isEmpty {
    Button(action: {
      self.showCreateSheet.toggle()
    }) {
      Text("Create your own habits")
        .font(Font.custom("Roboto-Regular", size: 20))
        .frame(width: geometry.size.width * 88/100, height: 200)
        .foregroundColor(.black)
        .background(Color.init(UIColor.systemGray5))
        .cornerRadius(40)
        .overlay(
          RoundedRectangle(cornerRadius: 40)
            .stroke(style: StrokeStyle(lineWidth: 2, dash: [20]))
            .foregroundColor(Color.init(UIColor.systemGray3))
        )
    }
  }
  else {
    // Something else
  }
}
.onAppear(perform: self.viewModel.newHabitsListener)

Sheet
VStack {
  TextField("Enter text", text: $enteredText)
  Button("Add Habit") {
    self.viewModel.createNewHabits(newHabit: self.enteredText)
  }
}

View Model
@Published var userCustomHabits = [String]()

func newHabitsListener() {
  db.collection("users").document(currUser?.uid ?? "").addSnapshotListener { documentSnapshot, error in
    guard let document = documentSnapshot else {
      print("Error fetching document: \(error!)")
      return
    }
    guard let data = document.data() else {
      print("Document data was empty.")
      return
    }
    DispatchQueue.main.async {
      self.userCustomHabits = data["userCustomHabits"] as! [String]
    }
  }
}

func createNewHabits(newHabit: String) {
  db.collection("users").document(currUser?.uid ?? "").updateData(["userCustomHabits": FieldValue.arrayUnion([newHabit])])
}

A: So I played around with your code a bit (since the code sample is incomplete, I had to make a few assumptions), and it seems like you might never have created the document you're writing to in the first place.
updateData only updates existing documents (see the documentation). To create a new document, use setData (see the documentation)
When changing your code form updateData to setData, the listener kicked in as expected.
However, it might be better to add a sub-collection customHabits to each user document. This way, adding new habits is as simple as adding a new document, which also makes querying a lot easier.


text:
Q: Ввод данных в эксель Предположим, в Excel ввожу данные, например номера телефона.
Какую ввести функцию, которая при вводе уже существующего номера будет сообщать об ошибке, или просто в соседнем столбце сообщать об этом?
A: =СЧЕТЕСЛИ(диапазон;новый_номер)>0

=ЕЧИСЛО(ПОИСКПОЗ(новый_номер;диапазон;))

ИСТИНА - есть такой номер.
Можно к ячейкам, в которые вводятся номера, применить инструмент Проверка_данных (закладка Данные), использовав похожую формулу.
Если на листе, можно добавить проверку:
=ЕСЛИ(СЧЕТЕСЛИ(диапазон;новый_номер);"уже есть";"порядок")

A: Я делал по-другому в Microsoft Office 2007.
Выделял весь столбец, даже незаполненные строки.
Потом на вкладке "Главная" выбирал - "Условное форматирование".
Далее выбирал - "Правила выделения ячеек".
Далее - "Повторяющиеся значения".
Далее выбрал как выделять и нажимаю ОК.
Вот и все, все повторы будут выделены цветом.


text:
Q: How to create compound indices in pymongo I do not know how to create compound indices in pymongo. In documentation (for example, here and here) I see only specific examples like:
>>> my_collection.create_index([("mike", pymongo.DESCENDING),
...                             ("eliot", pymongo.ASCENDING)])

or
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])

I do not get the reason - why to provide such specific examples right with DESCENDING and ASCENDING constants without giving any basic example - such as where we have, for example, two ordinary fields and want to have a compound index without any extra constraints and properties.


text:
Q: Python: How to make program wait till function's or method's completion Often there is a need for the program to wait for a function to complete its work. Sometimes it is opposite: there is no need for a main program to wait.
I've put a simple example. There are four buttons. Clicking each will call the same calculate() function. The only difference is the way the function is called.

*

*"Call Directly" button calls calculate() function directly. Since there is a 'Function End' print out it is evident that the program is waiting for the calculate function to complete its job.

*"Call via Threading" calls the same function this time using threading mechanism. Since the program prints out ': Function End' message immidiately after the button is presses I can conclude the program doesn't wait for calculate() function to complete. How to override this behavior? How to make program wait till calculate() function is finished?

*"Call via Multiprocessing" buttons utilizes multiprocessing to call calculate() function.
Just like with threading multiprocessing doesn't wait for function completion. What statement we have to put in order to make it wait?

*"Call via Subprocess" buttons doesn't do anything since I didn't figure out the way to hook subprocess to run internal script function or method. It would be interesting to see how to do it...
Example:
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication(sys.argv)

def calculate(listArg=None):
    print '\n\t Starting calculation...'
    m=0
    for i in range(50000000):
        m+=i
    print '\t ...calculation completed\n'

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(Dialog_01, self).__init__()

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()

        directCall_button = QtGui.QPushButton("Call Directly")
        directCall_button.clicked.connect(self.callDirectly)
        myBoxLayout.addWidget(directCall_button)

        Button_01 = QtGui.QPushButton("Call via Threading")
        Button_01.clicked.connect(self.callUsingThreads)
        myBoxLayout.addWidget(Button_01)

        Button_02 = QtGui.QPushButton("Call via Multiprocessing")
        Button_02.clicked.connect(self.callUsingMultiprocessing)
        myBoxLayout.addWidget(Button_02)

        Button_03 = QtGui.QPushButton("Call via Subprocess")
        Button_03.clicked.connect(self.callUsingSubprocess)
        myBoxLayout.addWidget(Button_03)

        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.setWindowTitle('Dialog 01')

    def callUsingThreads(self):
        print '------------------------------- callUsingThreads() ----------------------------------'
        import threading
        self.myEvent=threading.Event()
        self.c_thread=threading.Thread(target=calculate)
        self.c_thread.start()

        print "\n\t\t : Function End"

    def callUsingMultiprocessing(self):
        print '------------------------------- callUsingMultiprocessing() ----------------------------------'
        from multiprocessing import Pool

        pool = Pool(processes=3)
        try: pool.map_async( calculate, ['some'])
        except Exception, e: print e

        print "\n\t\t : Function End"

    def callDirectly(self):
        print '------------------------------- callDirectly() ----------------------------------'
        calculate()
        print "\n\t\t : Function End"

    def callUsingSubprocess(self):
        print '------------------------------- callUsingSubprocess() ----------------------------------'
        import subprocess
        print '-missing code solution'
        print "\n\t\t : Function End"

if __name__ == '__main__':
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(480,320)
    sys.exit(app.exec_())

A: Use a queue: each thread when completed puts the result on the queue and then you just need to read the appropriate number of results and ignore the remainder:
#!python3.3
import queue    # For Python 2.x use 'import Queue as queue'
import threading, time, random

def func(id, result_queue):
    print("Thread", id)
    time.sleep(random.random() * 5)
    result_queue.put((id, 'done'))

def main():
    q = queue.Queue()
    threads = [ threading.Thread(target=func, args=(i, q)) for i in range(5) ]
    for th in threads:
        th.daemon = True
        th.start()

    result1 = q.get()
    result2 = q.get()

    print("Second result: {}".format(result2))

if __name__=='__main__':
    main()

Documentation for Queue.get() (with no arguments it is equivalent to Queue.get(True, None):
    Queue.get([block[, timeout]])

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

How to wait until only the first thread is finished in Python
You can to use .join() method too.
what is the use of join() in python threading

A: I find that using the "pool" submodule within "multiprocessing" works amazingly for executing multiple processes at once within a Python Script.
See Section: Using a pool of workers
Look carefully at "# launching multiple evaluations asynchronously may use more processes" in the example.  Once you understand what those lines are doing, the following example I constructed will make a lot of sense.
import numpy as np
from multiprocessing import Pool

def desired_function(option, processes, data, etc...):
    # your code will go here. option allows you to make choices within your script
    # to execute desired sections of code for each pool or subprocess.

    return result_array   # "for example"

result_array = np.zeros("some shape")  # This is normally populated by 1 loop, lets try 4.
processes = 4
pool = Pool(processes=processes)
args = (processes, data, etc...)    # Arguments to be passed into desired function.

multiple_results = []
for i in range(processes):          # Executes each pool w/ option (1-4 in this case).
    multiple_results.append(pool.apply_async(param_process, (i+1,)+args)) # Syncs each.

results = np.array(res.get() for res in multiple_results)  # Retrieves results after
                                                           # every pool is finished!

for i in range(processes):
    result_array = result_array + results[i]  # Combines all datasets!

The code will basically run the desired function for a set number of processes.  You will have to carefully make you're function can distinguish between each process (hence why I added the variable "option".)  Additionally, it doesn't have to be an array that is being populated in the end, but for my example thats how I used it. Hope this simplifies or helps you better understand the power of multiprocessing in Python!


text:
Q: Capitalize first letter of last name in column of a table I would like to capitalize first letter for the last name and erase extra spaces as well as remove comma or period in my table by running a query by sql view.

A: To make changes to a table containing names, run the query shown below (change the table name and field names to match your database).
This will:

*

*Remove leading and trailing spaces

*Change the first character of the name to Uppercase

*This will NOT change the case of any other letters in the string
UPDATE TblEmployee SET TblEmployee.FirstName = UCase(Mid(Trim([FirstName]),1,1)) &
Mid(Trim([FirstName]),2), TblEmployee.LastName = UCase(Mid(Trim([LastName]),1,1)) &
Mid(Trim([LastName]),2);


text:
Q: MS CRM Dynamics - browse to dynamics portal (from my application) without Login dialog? From my C# application, I would like to open my dynamics portal within a browser.
I would like to do this with no need of the user to prompt his credentials in the Login dialog.
is it possible?
In salesforce.com for example it is possible. you can add a session info to your salesforce.com portal URL, in that way you can browse with that URL with no need to authenticate.
is that also possible in Dynamics CRM?
please help...
hagai


text:
Q: replacing some text in square brakets in bash I have this string that I get from running jack_lsp.
a2j:Arturia BeatStep [28] (capture): Arturia BeatStep MIDI 1

in a xml file, I save the connections state from a  previous jack session.
<connection>
    <output>a2j:Arturia BeatStep [20] (capture): Arturia BeatStep MIDI 1</output>
    <input>starmaze:midi_to_slave_1</input>
</connection>

You may have noticed, that between the previous session (saved in the xml file) and the current session, the value in [] (square brakets) has been changed.
asu such I am trying to update the value in the file  whenever I want to load it.
To do that I have the following bash snippet:
ARTURIA_CHAN=$( jack_lsp | grep Arturia | grep capture | sed -e 's/^.*\[\(.*\)\].*$/\1/' )
ARTURIA_XMLCHAN=$( cat "${ofname}" | grep Arturia | grep capture | sed -e 's/^.*\[\(.*\)\].*$/\1/' )
if [ "${ARTURIA_CHAN}" != "${ARTURIA_XMLCHAN}" ]; then
   sed -e "s/\[$ARTURIA_XMLCHAN\]/\[$ARTURIA_CHAN\]/g" -i.bak1-art "${ofname}"
   echo "changing arturia from ${ARTURIA_XMLCHAN} to ${ARTURIA_CHAN}"
fi

ofname is the "output filename" and it is basically the xml file.
The 2 variables seem to get the expected values (what's within the []), but the sed operation either does not work correctly , or does not save the file in the end. I can't figure out that it is though. Is it more apparent to you perhaps?
thank you.

A: Better use an XML parser with a XPath expression to modify the XML file. One example with xmlstarlet :
$ xmlstarlet edit -L -u "/connection/output[contains(., "Arturia")]" -v "remplacement_string" file.xml


text:
Q: need help with UINavigationController I have a class called CataloguesEtTarifsPDFViewController which displays a tableView.
Now, inside this class I wanna create a UINavigationController and set the root of the UINavigationController this class:
Here is what I did:
CataloguesEtTarifsPDFViewController.h

 UINavigationController *navigationController;

in the implementation file
CataloguesEtTarifsPDFViewController.m

- (void)viewDidLoad
{

    CataloguesEtTarifsPDFViewController *catalog =[[CataloguesEtTarifsPDFViewController alloc] init];

    loadingView.hidden=YES;
   navigationController = [[UINavigationController alloc] initWithRootViewController:catalog];

}

When I click on the table cell I do this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WebViewController *webViewController = [[WebViewController alloc] init];

    [self.navigationController pushViewController:webViewController animated:YES];

    [navigationController release];

}

But when I run and click on the tableView nothing happens...not view is showed up!!!Where am I going wrong?
IMPORTANT: I don't have a delegate file.Only CataloguesEtTarifsPDFViewController.h CataloguesEtTarifsPDFViewController.m and CataloguesEtTarifsPDFViewController.xib.
EDIT:
- (IBAction)showViewCataloguesEtTarifsPDF:(id)sender{
    // Remove view to middleView
    [mainMenuViewController removeViewsToMiddleView];
    // create view controller
    cataloguesEtTarifsPDFViewController = [[CataloguesEtTarifsPDFViewController alloc] init];
    cataloguesEtTarifsPDFViewController.mainMenuViewController = mainMenuViewController;

   // hide/show header button
    [mainMenuViewController.headerViewController showMainMenuButton];
    // highlight footer tabbar button
    [mainMenuViewController.footerViewController.footerTabBar setSelectedItem:mainMenuViewController.footerViewController.footerTabBarItemMyAudi];
     UINavigationController*  navigationController = [[UINavigationController alloc] initWithRootViewController:cataloguesEtTarifsPDFViewController];
      [self presentModalViewController:navigationController animated:YES];
}

A: You should probably read this: http://www.iosdevnotes.com/2011/03/uinavigationcontroller-tutorial/
Or this: http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007457-CH1-SW1
Or watch this: http://peepcode.com/products/iphone-view-controllers-part-i
That'll give you the basics and you'll be well equipped to answer your question and fix your code :)
PS: You don't have to explicitly create and set a UINavigationController in your view controller. If the view controller is embedded within a navigation controller, the navigationController property of your view controller instance will automatically find it and return it.

A: What you're doing in viewDidLoad is wrong.
Wherever you are showing the CataloguesEtTarifsPDFViewController, you should wrap it in a UINavigationController there and show the UINavigationController instead.
This will make sure the navigationController property of UIViewController will be set.
In your tableView:didSelectRowAtIndexPath: method you should release the webViewController variable instead of the navigationController property.


text:
Q: Is there a simple way to open ".sty" files by something similar to the "texdoc"? Is there a simple way to open ".sty" files by something similar to the "texdoc"? I'm looking for something like texsty to simply open .sty files.

A: Windows (without cyg)
Native Windows isn't really cut out for this. It's been a while since I did any batch file scripting, but try this:
Save the following as file texsty.bat and place it on your PATH (or in the working directory of your command prompt):
@echo off
for /f "usebackq tokens=*" %%a in (`kpsewhich %*.sty`) do "C:\Program Files\Texmaker\texmaker" "%%a"

Use as eg texsty hyperref. If you want to be able to specify files which do not end in .sty (eg .cls, .pdf, .dtx, .clo) then you can remove the .sty extension from just after the %* in the batch file, but then would have to invoke for sty files as eg texsty hyperref.sty (and it might be better to call it texstart instead of texsty in that case).
This assumes that Texmaker is installed in the default path. For other editors/paths, one can edit the command line accordingly. It should also be possible to use start to use the default program associated with sty files, but this doesn't work for me via this batch file...
I got the syntax from Batch equivalent of Bash backticks.
Bash (or similar shells)
For completeness, if using bash, I would add the following function definition to my ~/.bashrc file:
texsty ()
{
# invoke kpsewhich, but remove any unwanted characters that may show up on Windows
local kpseret="$(kpsewhich "$1.sty" | tr -d '\r')"
if [ -z "$kpseret" ]; then
echo "'$1' not found."
else
xdg-open "$kpseret"
#or for Windows, use start instead of xdg-open:
#start "$kpseret"
fi
}

This just wraps the method offered by egreg in his comment into a more convenient function. Again, invoke as eg texsty hyperref. Personally, I'd probably prefer the more general texstart obtained by removing .sty from the kpsewhich call and renaming the function, then invoke as eg texstart hyperref.sty.

A: Unfortunately windows does not have the flexibility of unix commands. This has to be done on two step process or using a script as per the accepted answer.
You use kpsewhich filename.sty to locate and then you type the path and the editor name in my case notepad. If you doinf this thing often download sublime2 and have it on the path.

EDLIN.EXE not supported anymore! However EDIT still works and you can replace Notepad with EDIT if you like.
This answer is more of a note to myself.


text:
Q: Could a sentence with relative clause be simple sentence? It sounds a bit basic and simple question but I want to learn if a sentence as the following can be classified as simple sentence?

They decided that it was a good idea to invest in the company.

And if there is a special name for this part of sentence when a "independent sentence" , what I mean is that the part it was a good idea to invest in the company, follows that or is it simply called as object.

Edit :
Another sentence could be as the following:

I liked the book that I bought last weekend.

or

It tasted so good that I could not help but have another one.

A:
Could a sentence with relative clause be simple sentence?

No.
There are three types of sentences in English.

*

*Simple: One independent clause with a subject and a verb (predicate).

*Compound: Two independent clauses joined by a coordinator such as for, and, but, etc.

*Complex: One independent clause with one or more dependent clauses. A dependent clause could be
(1) a noun clause. One example is a clause with the complementizer that:

They decided that it was a good idea to invest in the company.

(2) a relative clause with relative pronouns such as which, that, who and whom, etc.

I liked the book that I bought last weekend.

(3) an adverbial clause with conjunctions such as because, if, as, since and when, etc.

I couldn't finish homework because it was too late.

As John Lawler commented, a simple sentence is rare in English and you can Google its examples.


text:
Q: Adding To JQuery's Ajax:Success Function I have made a custom sort of wrapper for the JQuery's Ajax function and everything is working quite nicely but now I want to go a bit further. I want to add a custom bit of code to the Success function that will be automatically called with each Ajax Request but that won't overwrite what is specified in the actual request. It needs to be called in the success since it will be modifying content received from the server.
My custom Ajax Func:
 $.adv_ajax = function(options) {
            if (!(options.url)){
                options.url="index.php";
            }
            if (!(options.data_type)){
                options.dataType='json';
            }

var extra_success=function(){
 add_special_fx();
}
                options.success=options.success+extra_success;

            return $.ajax(options);
        }

A typical Ajax call using it:
    $.adv_ajax({
    url: "user_accounts.php",
                dataType: 'json',

                success: function(response){
$("#mydiv").html(response);

    }
    });

A: You could use the ajaxSuccess() function. It fires after every successful ajax request.
http://jqapi.com/#p=ajaxSuccess

A: I believe you are looking for jQuery Global AJAX Events: http://api.jquery.com/category/ajax/global-ajax-event-handlers/. They allow you to add event handlers to all AJAX requests.
.ajaxSuccess()

Attach a function to be executed whenever an Ajax request completes
  successfully. This is an Ajax Event.

Source: http://api.jquery.com/ajaxSuccess/

A: If you need to call custom function only in your wrapper, wrap calling your handler to the another function where you can call as many functions as you need:
options.success = function(data, textStatus, jqXHR) {
    options.success(data, textStatus, jqXHR);
    extra_success(data, textStatus, jqXHR);
}

The only thing that I not sure that it will work if your reassing options.success with new function, maybe you will need to create separate options object end extedn it with current one.


text:
Q: `pstricks` package preventing compilation Today I updated to the latest version of MiKTeX (2.9.6703, I was previously using an older version of MiKTeX 2.9) and now the pstricks package entirely prevents me from compiling a document when loaded using \usepackage{pstricks}. Thus, the code below produces fatal error messages, but commenting out \usepackage{pstricks} means the document compiles just fine.
\documentclass[a4paper,12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage[UKenglish]{babel}
\usepackage{libertine}
\usepackage{pstricks}
\begin{document}
Hello world!
\end{document}

I get 100 identical error messages saying:

! Text line contains an invalid character.
  l.1 ...@^^@^^@^^@^^@^^@^^@^^@^^@^^@^^@^^@^^@^^@^^@
                                                    ^^@^^@^^@^^@^^@^^@^^@^^@^^...

I get the same errors whether I use XeLaTeX, LuaLaTeX of pdfLaTeX.
Does anyone have any idea what's going on?
(Edit: This question was originally about pst-asr but it seems the problem is actually with pstricks, on which pst-asr is dependent.)


text: Q: Algorithm to find out the local translation vectors in a distorted lattice structure for materials simulation For example, I have a set of atomic position data of an lattice structure with BCC, but some parts of the structure are distorted by the thermal perturbation or rotated due to the material defects (such as dislocations or grain boundaries). I want to find out the lattice translation vectors $\bf a_1, \bf a_2, \bf{a_3}$ for each local environments (i.e. each cell). Is there any convenient algorithm or package to realize this?


text:
Q: Make the mod message excerpt in the top bar more useful
moderator message 4 hours ago
Evil Moderator added a new message
  Hello, I'm writing in reference to your Meta Stack Overflow account:   http://meta.stackoverflow....

Yeah.. that excerpt is not very helpful for mod messages (replies are a different thing).
What about removing the introduction part from the excerpt that's shown in the top bar? Since it's almost always the same it's easy to detect and to remove.
Actually I'd even go one step further and detect message templates that have not been modified and in that case only show the name of the template.

A: Going forward, for the very first moderator message (in a thread) that a moderator initiates, the moderator inbox message will have the following form:
<mod name> sent <template name> [with edits] to <recipient name>

No excerpt will show up, and the "with edits" text will only show up if the template has been edited.
Moderator evilness ranking in the message will be determined by number of flags handled compared to fellow moderators on the site.


text:
Q: How do I know what decompression algorithms are compiled-in into the linux kernel? If /proc/config.gz is unavailable, how do I know what decompression algorithms the running kernel is capable of using on a compressed cpio initramfs?
Is the gzip algorithm always available, even when CONFIG_DECOMPRESS_GZIP is not y when building the kernel?

A: Compression algorithms are declared in lib/decompress.c. Gzip is defined in lib/decompress_inflate.c and doesn't get any special status; it'll only be there if CONFIG_DECOMPRESS_GZIP is y when the kernel is compiled.
The list of available compression algorithms is the compressed_formats structure. Since it's defined as static, it isn't available in other source files. The only function that uses it is thus the decompress_method function in lib/decompress.c itself. So the only way to get a kernel to use the table of supported algorithms is to attempt to decompress something that starts with the appropriate two-byte magic sequence, and see if that function returns the algorithm name.
You can tell which decompression functions are supported by searching the list of kernel symbols (/proc/kallsyms). The functions aren't identified as such, so you'll need to bake in the list of symbol names.
</proc/kallsyms cut -d " " -f 3 |
grep -xF -e gunzip -e bzip2 -e unlzma -e unxz -e unlzo -e unlz4

A: You can get to know your compression type by going into the directory sys/power/tuxonice/compression there u will a file named algorithm go into it it will have the decompression type in it for me it was written lzo.


text:
Q: Spring boot not redirecting after validate I've been reading much about the subject but I can't understand it at all.
I have just started to build a web project from 0 with Spring Boot and Java and I have access to static files (css and js place on their respective folders in /resources/static/) but when from the jsp view I validate a login-form my Controller does not catch the PostMapping action.
I realized that my Controller works fine when I set up from application.properties the
spring.resources.add-mappings : false

but I stop seeing my static resources.
I want of course to fix it, understand it and prepare the environment to go making it bigger.
Edited
Yes, my css and js files are under /resources/static
Right now, I have a Controller with a GetMapping("/home") and a PostMapping("/home") methods. When I launch the project and access through localhost:8080/home the flow gets in the GetMapping method and it simply shows a jsp view. To do that I had to add these two lines into application.properties:
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

Also I have there:
spring.mvc.throw-exception-if-no-handler-found: true
spring.resources.add-mappings: true

Here is just a login page, when submit, the PostMapping does not handle the petition and anything happens
To fix it I can change
spring.resources.add-mappings: false

and it works but then, crazy to understand to me, I have no access to js and css files
I have no MvcConfig implements WebMvcConfigurer not any similar.


text:
Q: I get following error when I import *.vue files without .vue extension? I get following error when I import a vue file without .vue extension .

ERROR in
  ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
  Module not found: Error: Can't resolve './components/Navbar'

My web back configuration is as below
module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {

    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },

A: If you are following eslint and you getting this error, try to add the below lines in your eslint config
...
rules: {
    // other stuff
    "import/extensions": ["error", "always", {
      "js": "never",
      "mjs": "never",
      "jsx": "never",
      "ts": "never",
      "tsx": "never",
      "vue": "never"
    }]
  },
...

A: The problem is in your Webpack configuration. To make Webpack automatically resolve .vue extensions use the resolve.extensions option, and include the defaults.
resolve: {
    extensions: ['*', '.js', '.vue', '.json']
}

A: The problem is in Webpack configuration.
Make Webpack automatically resolve .vue extension by including extension array in Webpack resolve
 resolve: {
    extensions: ['.vue'],
   },


text:
Q: No items iterated in array jsx I'm going insane over this problem. The map iteration does not iterate over the items. It render the {this.props.data.length} correct. I get '1' in this case.
No errors or anything in the console. The console.log prints the object and it contains all the data.
var Component = React.createClass({
    render: function(){
        var data = this.props.data;

        if(data == null) {
            return (
...
)
        }
        if(data.information == null) {
            data.information = {informations: []};
        }
        if(data.technicalData == null){
            data.technicalData=[];
        }

        if(data.suppliers == null)  {
            data.suppliers = [];
        } else {
            console.log(data.suppliers);
        }

        return (

{data.name}

                 <Information info={data.information.informations}/>

                 <TechInfo tech={data.technicalData}/>

                <Supplier data={data.suppliers}/>

         );
    }
});

var Supplier = React.createClass({
    render: function() {
      return (

Supplier

                Number of suppliers: {this.props.data.length}
                {this.props.data.map(function(item, i){

Supplier index: {i}

                })}

        )
    }
});

suppliers: [
  { name: "elfa",
    attributes: [
      { key: "artnr",
        value: "58-578-83"
      },
      { key: "url",
        value: "https://www.elfa.se"
      }
    ]
  }

A: You're not returning anything from inside the map. Add a return statement:
{this.props.data.map(function(item, i){
  return
Supplier index: {i}
;
})}


text:
Q: Creating an Excel Chart with Dynamic Dates that Come from a Drop Down Menu I'm trying create a line graph where I can use a drop down to select the start and end dates (and the data seen will change dynamically to reflect those dates). Currently, my data looks like this:
 Date    (Total Funding Before) (Total Funding During) (Total Funding After)
 8/2017    150                          160                  150
 9/2017    160                          160                  160
 10/2017   170                          170                  150
 11/2017   180                          180                  170
 12/2017   190                          180                  160

Can anyone give me insight on how to create this?

A: Yes it's possible :D.
With some dynamic ranges and a lot of patience you could create something like this result:

Step-by-Step guide:
First we make the whole table into "Excel Table". Go to "Home" -> "Format as Table".

Next part, we need to create a couple of "Named Ranges". Go to: "Formulas" -> "Name Manager" -> "New..."

We make our start date a "Named Range". I name it to "Start_Date". And it refers to cell $B$3. My Sheet name is "Sheet1".
We do exactly the same for the "End_Date. We refer it to the cell below, $B$4.

Then we create a name range for the "Date" column. We name our range to "Dates". Check that the "Refers to:" is in this format "=TableX[Column Name]". In our case =Table1[Date]. Notice that the name manager don't use "B7:B16", rather is a reference to the table column area. The last step is very important!, since we want to make all references dynamic.

Time to create drop-down list for start and end date.
Go to: "Data" -> "Data Validation" -> Choose: "List" -> "Source:" =Dates, which is our range we named in the previous step.

Time to create the dynamic range for the X-Axis. I name it "XAxis"
=OFFSET(Sheet1!$B$7,MATCH(Start_Date,Dates,0)-1,0, MATCH(End_Date,Dates,0)- MATCH(Start_Date,Dates,0)+1,1)

This formula will search where the first row is for the first date (Start_Date). Then it will see where the end date is located (End_Date). Those two together will create the range we need. I have ";" as delimiter, while US have ",".

Now we create all the Y-ranges we need. One for every series we want to plot.
We start with Column "Total Funding Before". I name it: YTotalFundingBefore and apply the following formula.
=OFFSET(XAxis,0,1)

So we use the same range as the XAxis and offset it by one column to the right.

We do the same for the following two Series.
Notice for every new serie we create a Name range, we change the column offset. So the last series I named to "YTotalFundingAfter" and the formula is almost same, except 3.
=OFFSET(XAxis,0,3)

Time to apply these ranges for the graph. I select the whole table and create a Line Graph. Then I select the first chart-serie: "Total Funding Before". In the formula bar (marked yellow in the picture) I need to change my references.

Here I want to give a trick to save some time.
When I rewrite the formulas I start like this... since the named ranges will come up automatically (as you can see in the picture):
=SERIES(Sheet1!$C$6,Xaxis,YTotalFundingBefore,1)

Then I add the Sheet name in front of all the variables. In my case "Sheet1". Complete formula will be:
=SERIES(Sheet1!$C$6,Sheet1!Xaxis,Sheet1!YTotalFundingBefore,1)
=SERIES(HeaderCell , XAxis Range , Y-Axis Range , Serie Number)

And then we press enter.

Same thing for the other series, so the second one will be:
=SERIES(Sheet1!$D$6,Sheet1!Xaxis,Sheet1!YTotalFundingDuring,2)

And the same thing for the last serie. Notice I change the header cell ($E$6) and serienumber (3):
=SERIES(Sheet1!$E$6,Sheet1!Xaxis,Sheet1!YTotalFundingAfter,3)

Finally we have a dynamic graph based on our Start and End Date values.
The good thing with table is when new rows (dates) are added, the ranges will pick them up automatically and also the drop down-lists. In the picture below I added 2 rows for demonstration purpose.

There are one important drawback with this setup. When a user applies the whole first date in the date range (2017-08) AND the last date in the date range 2018-07, the chart-series will remove the name ranges and go to absolute values like this: (=SERIES(Sheet1!$E$6,Sheet1!$B$7:$B$18,Sheet1!$C$7:$C$18,1)). My solution have been to have a one or two extra dates in the beginning of the date range. Dates we will probably never use and therefore never use the complete date range.


text:
Q: Interface designs of std::basic_fstream and std::unique_lock I'm comparing the two classes, because they both associate with something else. std::basic_fstream has to associate with a file, while std::unique_lock has to associate with a mutex. As such, providing an open() method seems reasonable. Still, std::unique_lock provides no such methods. Lazy initialization can be performed anyway via move assignment. It may thus seem redundant to provide an open() method. std::basic_fstream, on the other hand, does provide an open() method. std::basic_fstream exists before C++11, and it is the only way to perform lazy initialization then. Putting aside backward compatibility considerations, would std::basic_fstream::open() just be removed? Or it still needs to be there for the operation may fail actually? Note that, the open (associate) operation always succeeds with std::unique_lock (not to be confused with the lock operation).

A: Your last sentence actually contains a hint: "open (associate) operation always succeeds with std::unique_lock". This makes it convenient to declare the open-ness as class invariant, establish it in the constructor and throw exceptions on rare failures. Compared that to files: Opening them can and does fail, so declaring open-ness as class invariant doesn't work as well there.


text:
Q: Where does the space before wrapfigure comes from and how can it be eliminated? The following MWE's code (taken from here and slightly modified: added minipages around) should demonstrate the details:
\documentclass{article}
\usepackage{lipsum,tikz,wrapfig}

\setlength\intextsep{0pt}%<- doesn't seem to matter

\begin{document}
%
\fbox{%
\begin{minipage}[t]{0.45\textwidth}%
    \begin{wrapfigure}{r}{4cm}%
        \begin{tikzpicture}%
            \fill (0, 0) rectangle (4, 4);%
        \end{tikzpicture}%
    \end{wrapfigure}%

    \lipsum[1]%
\end{minipage}%
}%
%
\fbox{%
\begin{minipage}[t]{0.45\textwidth}%
%   \begin{wrapfigure}{r}{4cm}%
%       \begin{tikzpicture}%
%       \fill (0, 0) rectangle (4, 4);%
%       \end{tikzpicture}%
%   \end{wrapfigure}%

    \lipsum[1]%
\end{minipage}%
}%
\end{document}

Screenshot:

Question: How can the gap (see the red questionmark within the screenshot) be eliminated? (My build-environment: Win7-64, Texstudio, TexLive2017, LuaLatex)
Update 1:
According cfr's comments I've added fboxes around the minipages. This shows that there is no space added - instead the minipage environment seems to be influenced by wrapfig: Please see the following screenshot.

A: I fixed it ;)
\documentclass{article}
\usepackage{lipsum,tikz,wrapfig}

\setlength\intextsep{-1.8pt}%<- doesn't seem to matter

\begin{document}

\begin{minipage}[t]{0.45\textwidth}%
    \begin{wrapfigure}{r}{4cm}%
        \begin{tikzpicture}%
            \fill (0, 0) rectangle (4, 4);%
        \end{tikzpicture}%
    \end{wrapfigure}%
    \vspace*{-6.7pt}

    \lipsum[1]%
\end{minipage}%
\begin{minipage}[t]{0.45\textwidth}%
%   \begin{wrapfigure}{r}{4cm}%
%       \begin{tikzpicture}%
%       \fill (0, 0) rectangle (4, 4);%
%       \end{tikzpicture}%
%   \end{wrapfigure}%

    \lipsum[1]%
\end{minipage}%
\end{document}

Just uploaded for you to see if you can figure out what that numbers needed are...

A: You are top-aligning your minipages. If a minipage (or some other box) starts with normal text then "top-aligning" means that its baseline is at the baseline of the first text line. But if it starts with some \vspace then this determines the baseline.
Inside a minipage wrapfig adds at first a zero \vspace. The easiest way to "avoid" the gap is to add a similar space to the other minipage, to adjust their baseline in a similar way:
\documentclass{article}
\usepackage{lipsum,tikz}
\usepackage{wrapfig}

\setlength\intextsep{0pt}
\begin{document}

\fbox{%
\begin{minipage}[t]{0.32\textwidth}
    \begin{wrapfigure}{r}{2cm}%
        \begin{tikzpicture}%
            \fill (0, 0) rectangle (2, 2);%
        \end{tikzpicture}%
    \end{wrapfigure}%

    \lipsum[1]%
\end{minipage}%
}%
%
\fbox{%
\begin{minipage}[t]{0.32\textwidth}%
\vspace{0pt}
    \lipsum[1]%
\end{minipage}%
}%
\fbox{%
\begin{minipage}[t]{0.32\textwidth}%
    \lipsum[1]%
\end{minipage}%
}%

\end{document}

A: Why use the boxes at all?
Is there an actual function in the environment for them?
If not, omit them: simple is best.
Employ vspace, within the wrapfig environment, with a positive or negative value, to raise or lower the level of the figure to match the level of the text.


text:
Q: Is mobx-react (6.1.4) version is compatable for react 18 Is there any issues other than React 18: observer not working with <React.StrictMode>

A: Compatibility matrix

MobX version
React version

6.*
16.8+

4.+/5._
16.8+

As you can see 6.* should work with React 16.8+


text:
Q: Can I compare 2 structures in C++? I have simply declared a structure like this -
struct data{
    int x,y;
};

Now I have declared 2 variables a & b of data type. I've assigned appropriate values to them. Now, I want to check if they are equal! I am trying to do like this -
data a,b;
a.x=12, a.y=24;
b.x=15, b.y=30;
if(a!=b)cout<<"a~b"<<endl;

But the compiler is giving me the following error on the 4th line ->
error: no match for 'operator!=' (operand types are 'data' and 'data')
Where is the problem actually? Isn't this compare supported in C++?? Or I'm making any mistakes??
What is the exact and easiest way to do this?? Do I need to compare each of the elements in the structure separately?? Or there's any other smarter way??

A: You have to implement all operators explicitely that you intent to use. In your case, you will need to supply bool operator!=(const data&, const data&).
A nice way to implement it for PODs like this is to use std::tuple since it already implements ordering:
#include <tuple>

// ...

bool operator!=(const data& p_lhs, const data& p_rhs)
{
    return std::tie(p_lhs.x, p_lhs.y) != std::tie(p_rhs.x, p_rhs.y);
}

std::tie (documentation) creates a temporary tuple of references. Those two tuples can then be compared, since std::tuple defines all comparison operators, as shown here.
I chose to implement operator!= as a free function. You can, of course, choose to implement it as member of your class:
struct data
{
    bool operator!=(const data& p_rhs) const
    {
        return std::tie(x, y) != std::tie(p_rhs.x, p_rhs.y);
    }

    int x, y;
};

Of course you should define all other operators, too. Remember that you can implement most operators by delegating to others.

A: Automatic C++ comparisons are coming in C++20, so you can just add a special operator to indicate that you need default comparisons when new standard is out.
class Point {
 int x;
 int y;
public:
 auto operator<=>(const Point&) const = default;
 // ... non-comparison functions ...
};

https://en.cppreference.com/w/cpp/language/default_comparisons

A: C++ gives you attribute-by-attribute assignment implicitly, but no comparison for equality or ordering. The reason is "just because", don't look too hard into philosophy.
You must to provide those operators, if needed, by implementing them yourself explicitly, for example:
bool operator<(const Data& other) const {
    if (x < other.x) return true;
    if (x > other.x) return false;
    return y < other.y;
}

bool operator==(const Data& other) const {
    return x == other.x && y == other.y;
}

and so on.
Note also that defining for example == doesn't give you != automatically and defining < doesn't provide >= implicitly.
UPDATE
C++20 introduces (will introduce) a new operator <=> (friendly name "spaceship operator") exactly to remove the verbosity of having to define all possible relational operators. In this case adding:
std::strong_ordering operator<=>(const Data& other) const {
    if (auto cmp = x <=> other.x; cmp != 0) return cmp;
    return y <=> other.y;
}

will allow compilation of all relational tests (<, <=, >, >=, ==, !=) between elements of the class based on checking x first and, if that check doesn't resolve, checking y instead.

A: You have to implement bool operator != (const data&, const data&);.
Possible implementation (in c++11):
#include <tuple>

//...

bool operator == (const data& lhs, const data& rhs) {
    return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y);
}

bool operator != (const data& lhs, const data& rhs) {
    return !(lhs == rhs);
}


text:
Q: How to make concentric circle roads? I can make a circle road. I use the shift key to make it an equal roundness.
My problem is trying to make another road outside or within that circle. It is rarely anywhere near going inside or outside of it. Usually it is trying to make a half overlap circle offset to a side (like the olympic symbol).
I have tried placing my cursor in various places. I can't seem to find the formula.
What is a procedure for making easily making a donut road?

A: First, create a circle road using the circle shape.
After that, SimCity will display guidelines in circles above and below the road. Switch to the curved road tool, and then draw the inner circle by following the inner guidelines.

A: Start with two straight roads that intersect at right angles.
Choose a start point on one road and an endpoint on the other road that is the same distance from the intersection.  Click on the start point, drag toward the intersection, and end on the end point.  That circle will be centered on the intersection.
Repeat at different distances from the intersection.


text:
Q: is there any easy way to get fancybox 2 to animate left to right instead of up and down? I have a project i'm working on and using fancybox 2 (which is pretty great).
That said, one annoyance is that the arrows in a gallery point left and right, but the animation moves up and down. i'd really love to animate the new content in from the left, rather than the top.
Before i pull apart the default rollout of fancybox and start overwriting oncompletes and the such, is there something i'm missing?

A: So, here's how i did it, if anyone else runs into this question later.
example: The Fremont
in the plugins.js file, i've made my own version of the fancybox script. changeIn and changeOut are updated as so:
   if(!isForward){
      // move left (backwards)
      startPos.left = (parseInt(startPos.left, 10) + 1500) + 'px';
      wrap.css(startPos).show().animate({
                opacity: 1,
                left: '-=1500px'
            }, {
                duration: current.nextSpeed,
                complete: F._afterZoomIn
            });
        } else {

    // move right (forwards)
    startPos.left = (parseInt(startPos.left, 10) - 1500) + 'px';
    wrap.css(startPos).show().animate({
                opacity: 1,
                left: '+=1500px'

            }, {
                duration: current.nextSpeed,
                complete: F._afterZoomIn
        });
    }

and changeOut looks like this now:
    changeOut: function () {
        var wrap = F.wrap,
            current = F.current,
            cleanUp = function () {
                $(this).trigger('onReset').remove();
            };

        wrap.removeClass('fancybox-opened');

        var leftAmt;

        if(isForward){
            leftAmt = '+=1500px';
        } else {
            leftAmt = '-=1500px';
        }

        if (current.prevEffect === 'elastic') {
            wrap.animate({
                'opacity': 0,
                left: leftAmt
            }, {
                duration: current.prevSpeed,
                complete: cleanUp
            });

        }

isForward is defined in the next/prev function
     next: function () {
      if (F.current) {
         F.jumpto(F.current.index + 1);
         isForward = true;
           }
      },

      prev: function () {
      if (F.current) {
         F.jumpto(F.current.index - 1);
         isForward = false;
           }
      },

and that's that. enjoy!

A: Good idea. Just, there is a bug in you code. you must put
isForward = false; or isForward = true;

before
F.jumpto(F.current.index - 1); or F.jumpto(F.current.index + 1);

in both next and prev function. Since it break your code when you press next and then you press prev. you can try it.
next: function () {
        if (F.current) {
            isForward = true;
            F.jumpto(F.current.index + 1);
        }
    },

prev: function () {
            if (F.current) {
                isForward = false;
                F.jumpto(F.current.index - 1);
            }
        },

A: The latest source code - https://github.com/fancyapps/fancyBox/zipball/master
Includes different animation directions depending on the way you navigate (using scroll mouse or keyboard navigation keys).
You can get horizontal transitions using the left and right key arrows.
No need to hack or customize your own fancybox version.

A: Check the API, maybe there's an option for it?
If not, find the part of the code that does the animation and replace it with your own.


text:
Q: How can I make the gdb `disassemble` command use /s as a default option, through MI I need to disassemble some C code, but I want to also show the source lines mixed in with the assembly code.  The issue I have is that I'm using gdb through the MI interface, which calls disassemble (or equivalent, perhaps -data-disassemble?), and I have no control over the options sent with the command.  If I did have access to the command, I could probably just use
-data-disassemble ... -- 1.
I've tried making a user-defined command, e.g.:
define dis
    disassemble /s
end

but I don't know how to force using that command through gdb/mi.  I also tried making an alias, but it creates a naming conflict ("Alias disassemble is the name of an existing command") and probably wouldn't work anyway because of the MI connection.
I'd like to just add a line to my .gdbinit file that forces the /s option to be a default for disassemble, but I can't find any documentation that shows how this can be done.
As a side note, I'm trying to accomplish this in MSVC 2019, and I can sort of do it manually using the instructions from Microsoft's MIEngine custom command doc.  But this doesn't go through the usual gdb/mi interface, and just dumps text into the Command Window.  I was able to set disassembly-flavor intel, which works in changing the assembly into Intel format, so it seems like what I want to accomplish is at least plausible.


text:
Q: Keras Tuner throws InvalidArgumentError I'm trying to use Keras Tuner to test different configurations and hyperparameters of my neural net
I have code that works when running outside the tuner (but I have to run it with eager execution disabled), but inside the tuner, I get an exception thrown. I'm new to using more complicated neural networks, so I'm trying to wade through the documentation but I get lost sometimes.Hers' the custom_loss and model plus tuner code
def custom_loss(yardline):
yardline=K.cumsum(yardline)
def loss(y_true, y_pred):
    y_true=K.cumsum(y_true)
    y_pred= y_pred*yardline
    new_total_prob= K.sum(y_pred)
    inverse_prob=K.pow(new_total_prob+K.epsilon(), -1)
    y_pred= y_pred*inverse_prob
    cdf_pred= K.cumsum(y_pred)
    return K.mean(K.square(y_true-cdf_pred))
return loss

Here's the model
def build_model(hp):
input_layer= Input(179,)
yardline=Input(199,)
x=Dense(32)(input_layer)
for i in range(hp.Int('num_layers', 2,4, default=4)):
    x= Dense(units=hp.Int('units_' + str(i),
                                        min_value=32,
                                        max_value=512,
                                        step=32),
                           activation='relu')(x)
    if (i==3 or i==5):
           x=Dropout(hp.Choice('dropout_'+ str(i),[0.15,0.25]))(x)
output_layer = Dense(199, activation='softmax')(x)
model=Model(inputs=[input_layer, yardline], outputs=output_layer)
model.compile(optimizer='adam',loss=custom_loss(yardline), metrics=['accuracy'])
return model

Here's the tuner code
tuner = kt.Hyperband(
    hypermodel=build_model,
    objective='val_accuracy',
    max_epochs=5,
    factor=2,
    hyperband_iterations=3,
    distribution_strategy=tf.distribute.MirroredStrategy(),
    directory='.',
    project_name='project')
tuner.search([X_train,yardline_train],y_train,
         epochs=5, batch_size=43,
         validation_data=([X_val, yardline_val],y_val))

Any help appreciated
The error says in particular Invalid Argument Error: and expects data into input_2...
 Again just seems strange since it ran when I loaded model without the tuner


text:
Q: Define props with 2 optional types in Dart In Typescript, I can define a var with 2 types like this
foo: string | number = 'bar'
How can I do the similar in Dart?

A: You can't do that in dart 2.

Dart 2 is statically typed

https://dart.dev/faq#q-is-dart-a-statically-typed-language


text:
Q: What is causing my @Html.DropDownList generate an error? My registration get and post method was working without error and now it generates the following error after post:

Here is my registration get and post
What am I missing?


text:
Q: 2 класса для ссылок Есть файл style.css, который отвечает за стили сайта, в нем прописаны - a, a:active, a:hover, определяющие стили ссылок.
Захотелось часть ссылок на сайте сделать немного отличающимися от них. Первое что пришло в голову заключить ссылки в тег
, ссылающийся на классы new2 a, new2 a:active, new2 a:hover :

  css

Результата естественно нет, т.к. ссылка будет все равно с классом a, a:active, a:hover. Естественно можно переправить ссылки на new1 a, new1 a:active, new1 a:hover, тогда класс new2 будет работать.
Есть ли другой способ?

A: Задать стили для нужных ссылок, например для всех:
a{color: blue;}

Для некоторых:
a.some{color: green !important;}

Получиться:
Синяя
Зеленая

A: p.new2 a {}
p.new2 a:active {}
p.new2 a:hover {}


text:
Q: How to correctly encode arabic subtitles in c#? Hello there i am creating a video player with subtitles support using MediaElement class and SubtitlesParser library, i faced an issue with 7 arabic subtitle files (.srt) being displayed ???? or like this:

I tried multiple diffrent encoding but with no luck:
SubtitlesList = new SubtitlesParser.Classes.Parsers.SubParser().ParseStream(fileStream);
subLine = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(subLine));

or
 SubtitlesList = new SubtitlesParser.Classes.Parsers.SubParser().ParseStream(fileStream,Encoding.UTF8);

Then i found this and based on the answer i used Encoding.Default "ANSI" to parse subtitles then re-interpret the encoded text:
 SubtitlesList = new SubtitlesParser.Classes.Parsers.SubParser().ParseStream(fileStream, Encoding.Default);
 var arabic = Encoding.GetEncoding(1256);
 var latin = Encoding.GetEncoding(1252);
 foreach (var item in SubtitlesList)
 {
  List<string> lines = new List<string>();
  lines.AddRange(item.Lines.Select(line => arabic.GetString(latin.GetBytes(line))));
  item.Lines = lines;
 }

this worked only on 4 files but the rest still show ?????? and nothing i tried till now worked on them, this what i found so far:
exoplayer weird arabic persian subtitles format (this gave me a hint about the real problem).
C# Converting encoded string IÜÜæØÜÜ?E? to readable arabic (Same answer).
convert string from Windows 1256 to UTF-8 (Same answer).
How can I transform string to UTF-8 in C#? (It works for Spanish language but not arabic).
Also am hoping to find a single solution to correctly display all the files is this possible ?
please forgive my simple language English is not my native language

A: i think i found the answer to my question, as a beginner i only had a basic knowledge of encoding till i found this article
What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
Your text editor, browser, word processor or whatever else that's trying to read the document is assuming the wrong encoding. That's all. The document is not broken , there's no magic you need to perform, you simply need to select the right encoding to display the document.
I hope this helps anyone else who got confused about the correct way to handel this, there is no way to know the files correct encoding, only the user can.


text:
Q: How to get access token to pull Azure Monitor metrics for a specific subscription? We need to generate an AAD access token which can be used for a client to query Azure Monitor metrics (though Fluent API) for a specific subscription. So the requirements are:
1. the token can only be used to query metrics for a specific subscription, but no others
2. only can query metrics from Azure Monitoring (through ARM I believe)
How can we:
1. obtain the access token?
2. For Azure Management Fluent SDK, how to use the token directly?
Thanks!

A:
1. How to obtain access token to list Azure resource metrics

a. create a service principal and assign Reader role for the sp. (I use Azure CLI to do that)
az login
az account set --subscription "<your subscription id>"
az ad sp create-for-rbac -n "readMetric" --role Reader

b. get access token
POST /<your sp tenant>/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=<your sp appid>
&client_secret=<your sp password>
&resource=https://management.azure.com/

c. List metrics for one Azure resource
GET https://management.azure.com/{resource id}/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=""
Authorization : Bearer <access_token>

2. For Azure Management Fluent SDK, how to use the token directly?

Regarding the issue, please refer to the following steps
static async Task Main(string[] args)
        {
       /*
           Please install sdk Microsoft.IdentityModel.Clients.ActiveDirectory and Microsoft.Azure.Management.Fluent

      */

            var tenantId = "<your sp tenant>";
            var clientId = "<your sp appId>";
            var clientSecret = "<your sp password>";
            var subscriptionId = "<your subscription id>";
            var context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId, false);
            var credential = new ClientCredential(clientId: clientId, clientSecret: clientSecret);
            var result = await context.AcquireTokenAsync("https://management.azure.com/", credential);

            var token = result.AccessToken;
            var tokenCredentials = new TokenCredentials(token);
            var azureCredentials = new AzureCredentials(
                tokenCredentials,
                tokenCredentials,
                tenantId,
                AzureEnvironment.AzureGlobalCloud);
            var client = RestClient
                .Configure()
                .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .WithCredentials(azureCredentials)
                .Build();
            var azure = Microsoft.Azure.Management.Fluent.Azure
                          .Authenticate(client, tenantId)
                          .WithSubscription(subscriptionId);
            var resourceId = "/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/jimtest/providers/Microsoft.Compute/virtualMachines/testvm";
            foreach (var metricDefinition in await azure.MetricDefinitions.ListByResourceAsync(resourceId))
            {
                var metricCollection = await metricDefinition.DefineQuery()
                                .StartingFrom(DateTime.UtcNow.AddMinutes(-5))
                                .EndsBefore(DateTime.UtcNow)
                                .ExecuteAsync();
                Console.WriteLine("Metrics for '" + resourceId + "':");
                Console.WriteLine("Namespacse: " + metricCollection.Namespace);
                Console.WriteLine("Query time: " + metricCollection.Timespan);
                Console.WriteLine("Time Grain: " + metricCollection.Interval);
                Console.WriteLine("Cost: " + metricCollection.Cost);
                foreach (var metric in metricCollection.Metrics)
                {
                    Console.WriteLine("\tMetric: " + metric.Name.LocalizedValue);
                    Console.WriteLine("\tType: " + metric.Type);
                    Console.WriteLine("\tUnit: " + metric.Unit);
                    Console.WriteLine("\tTime Series: ");
                    foreach (var timeElement in metric.Timeseries)
                    {
                        Console.WriteLine("\t\tMetadata: ");
                        foreach (var metadata in timeElement.Metadatavalues)
                        {
                            Console.WriteLine("\t\t\t" + metadata.Name.LocalizedValue + ": " + metadata.Value);
                        }
                        Console.WriteLine("\t\tData: ");
                        foreach (var data in timeElement.Data)
                        {
                            Console.WriteLine("\t\t\t" + data.TimeStamp
                                    + " : (Min) " + data.Minimum
                                    + " : (Max) " + data.Maximum
                                    + " : (Avg) " + data.Average
                                    + " : (Total) " + data.Total
                                    + " : (Count) " + data.Count);
                        }
                    }
                }
            }
  }

For more details, please refer to the document

A: Let me clarify a bit more on my problems.
The service has an SP which already has permission to query ARM for a number of subscriptions. Now there are a bunch of metrics clients which are doing metrics query work for each individual subscription. Due to security reason, these clients cannot access the service SP; in order to query metrics, the proposal is that for each individual client, it can first request a token for its subscription from the service, and use the token to query metrics.
Now whenever the service receives the token request from a client, it should ask AAD for an access token, which is scoped to only the corresponding subscription (since the SP has access to multiple subscriptions by default), and distribute back to the client. We don't want the client to use the obtained token to either query metrics of another subscription or to read resource other than metrics.


text:
Q: ZSH thinks unterminated quote if preceded by exclamation mark (!) I have zsh 5.3 (through oh-my-zsh), if I run echo --message="foo!", I get unterminated quote prompt on the next line:
$ echo --message="foo!"
dquote>

This doesn' happen in bash.
When I drop the ! character from the argument, it works fine:
$ echo --message="foo"
--message=foo

What's happening here?

I should also note that if I answer the unterminated quote prompt with " and hit return, I get this output, which totally drops the !:
$ echo --message="foo!"
dquote> "
--message=foo

A: That's the history expansion at work.
This is what the zshexpn(1) manpage says about it:

If the shell encounters the character sequence !" in the  input,  the
         history  mechanism  is temporarily disabled until the current list (see
         zshmisc(1)) is fully parsed.  The !" is removed from the  input,  and
         any subsequent ! characters have no special significance.


text:
Q: Is there any way to intercept and modify build-in Class's static method? With instanceof, we can do this:
new Number(1) instanceof Number           // true

But we can't do this:
1 instanceof Number                       // false

Since ES6 provide [Symbol.hasInstance] for us, we can use it to create a new class in order to make instanceof could check for primitive value. For example:
class MyNumber {
    static [Symbol.hasInstance](x){
        return typeof(x) === 'object'? x instanceof Number:typeof(x) === 'number'
    }
}
const a = 1
const b = new Number(1)
a instanceof MyNumber                 // true
b instanceof MyNumber                 // true

However, can we just intercept and modify build-in Class's static method (Number[Symbol.hasInsatnce] in this case) instead of creating another new class (MyNumber in this case)?

A: Classes are in fact functions. So Object.defineProperty on Number will do it.

Object.defineProperty(Number, Symbol.hasInstance, {
  value: function(x) {
    return typeof(x) === 'object' ? x instanceof Number : typeof(x) === 'number'
  }
});

console.log(1 instanceof Number);


text:
Q: How to get edit text values from a listview I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_servic_homepage);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    url = getResources().getString(R.string.webservice);
    aq = new AQuery(ServicHomepage.this);
    cd = new ConnectionDetector(ServicHomepage.this);
    findviewbyId();
    progressdialog();
    if (cd.isConnectingToInternet()) {
        getintentData();
    } else {
        Toast.makeText(ServicHomepage.this, "CheckIternet connection",     Toast.LENGTH_SHORT).show();
    }
}

private void progressdialog() {
    pd = new ProgressDialog(ServicHomepage.this);
    pd.setMessage("Loading...");
}

public void findviewbyId() {

    recyclerview = (ListView) findViewById(R.id.service_recycler_view);
    update_descrptn = (TextView) findViewById(R.id.update_descrptn);
    uploadimages = (TextView) findViewById(R.id.uploadimages);

}

public void getintentData() {
    SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
    catid = prefs.getString(Constants.CATID, "");
    subcatid = prefs.getString(Constants.SUBCATID, "");
    user_id = prefs.getString(Constants.USERID, "");
    isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");

    clicklistener();
}

public void clicklistener() {
    uploadimages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
            startActivity(i);
        }
    });
    update_descrptn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
            for (int i = 0; i < serv_adapter.getCount(); i++) {

                View view = serv_adapter.getView(i,null,null);
                EditText edittext = (EditText)view.findViewById(R.id.et_amount);
                EditText et_description = (EditText)view.findViewById(R.id.et_description);
                String str = edittext.getText().toString();
                String str1 = et_description.getText().toString();

                Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
            }
            updateList();
        }
    });
}

private void updateList() {
    String substring = null, msgString = "";
    String MAIN_CART = null;
    MAIN_CART = "{\"service\":[%s]}";
    String temstring = "";
    for (int i = 0; i < arrayList.size(); i++) {

        substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
                + "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
        temstring = temstring + substring;

    }
    temstring = temstring.substring(0, temstring.length() - 1);
    msgString = msgString + String.format(MAIN_CART, temstring);
    Log.e("msgString=============", msgString);
}

This is the method where all the items are adding in the list
   public String parseanimcat(String object) {
    try {
        JSONObject json = new JSONObject(object);
        JSONObject jsonobj = json.getJSONObject("data");
        status1 = jsonobj.getString("status");
        message = jsonobj.getString("message");
        arrayList = new ArrayList<>();
        JSONArray jarray = jsonobj.getJSONArray("dataFound");

        for (int i = 0; i <= jarray.length(); i++) {
            JSONObject jobj = jarray.getJSONObject(i);
            String category = jobj.getString("category");
            String subsubcat_id = jobj.getString("subsubcat_id");
            Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
            model = new Data_Model();
            model.setTitle(category);
            model.setSubcatid(subsubcat_id);
            arrayList.add(model);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return object;
}

This is my adapter class-
    private class service_list_adapter extends ArrayAdapter<Data_Model>{
    private ArrayList<Data_Model> array_list;
    Context context;
    String[] etValArr;
    ViewHolder holder;
    String[] totalValue;
    Data_Model model;
    HashMap<String, String> hm = new HashMap<>();
    ArrayList<HashMap<String, String>> list = new ArrayList<>();

    public service_list_adapter(Context context,int   resourceId,ArrayList<Data_Model> arrayList) {
        super(context,resourceId,arrayList);
        this.context = context;
        this.array_list = arrayList;
        etValArr = new String[array_list.size()];
        totalValue = new String[array_list.size()];
    }
    private class ViewHolder {
        public TextView serv_title;
        public EditText serv_descrptn, serv_amount;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
          model = array_list.get(position);
        POSITION = position;

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
            holder = new ViewHolder();
            holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
            holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
            holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
            convertView.setTag(holder);
            holder.serv_title.setTag(position);
            holder.serv_descrptn.setTag(position);
            holder.serv_amount.setTag(position);
        } else
            holder = (ViewHolder) convertView.getTag();

        holder.serv_title.setText(model.getTitle());
        holder.serv_descrptn.setText(model.getServdescription());
        holder.serv_amount.setText(model.getServamount());
        holder.serv_amount.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                model.setServamount(s.toString());
            }
        });

        holder.serv_descrptn.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                model.setServdescription(s.toString());
            }
        });
        return convertView;
    }

}

A: be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it


text:
Q: How is the memory of returned C types handled under GC? According to the documentation for NSString's method -UTF8String:

The returned C string is automatically
  freed just as a returned object would
  be released; you should copy the C
  string if it needs to store it outside
  of the autorelease context in which
  the C string is created.

So under retain/release memory management, the following method:
- (const char*) giveMeACString
{
    NSString* string = @"I'm a string!";
    return [string UTF8String];
}

is fine, so long as the calling method treats the returned const char* as it would an autoreleased object.
However, under garbage collection there isn't an autorelease context, as far as I'm aware. And C types aren't garbage collected, so it doesn't look like the GC will treat the returned pointer as it would a returned object.
What is its lifespan tied to? Is it still freed at a point in the thread's runloop that is reliably `later on', or does it behave differently under GC than under non-GC?

A: I think the memory is allocated from garbage collected memory and the return type is __strong const char*.  This means that it will be collected in the normal way when it is not reachable from the root set of pointers.
That basically means you need to store it in a pointer variable that is marked as __strong or it will be collected at some point.
I'd speculate that an immutable string maintains a reference to the UTF8 version of itself, so it only has to calculate it once and therefore the UTF8 string probably won't go away until the NSString does which is why you don't have to worry about it disappearing normally.

A: Since you did not explicitly allocate those spaces, you do not need to worry about deallocation.


text:
Q: GeoPandas unable to read in PostGIS table I am attempting to read columns from a PostGIS table into a GeoDataFrame and am getting the following issue:
df = geo.GeoDataFrame.from_postgis("select geom __geometry__, id
from hist_line limit 5",con, geom_col='__geometry__')

Traceback (most recent call last):
  File "/Users/stephen/anaconda/lib/python2.7/site-    packages/IPython/core/interactiveshell.py", line 3066, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-137-0f8eeafc0543>", line 1, in <module>
    df9 = geo.GeoDataFrame.from_postgis("select geom as __geometry__, id     from hist_line limit 5",con, geom_col='__geometry__')
  File "/Users/stephen/anaconda/lib/python2.7/site-    packages/geopandas/geodataframe.py", line 201, in from_postgis
coerce_float, params)
  File "/Users/stephen/anaconda/lib/python2.7/site-packages/geopandas/io/sql.py", line 42, in read_postgis
    s = wkb_geoms.apply(lambda x: shapely.wkb.loads(binascii.unhexlify(x.encode())))
  File "/Users/stephen/anaconda/lib/python2.7/site-    packages/pandas/core/series.py", line 2169, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/src/inference.pyx", line 1059, in pandas.lib.map_infer (pandas/lib.c:62578)
  File "/Users/stephen/anaconda/lib/python2.7/site-packages/geopandas/io/sql.py", line 42, in <lambda>
    s = wkb_geoms.apply(lambda x: shapely.wkb.loads(binascii.unhexlify(x.encode())))
AttributeError: 'NoneType' object has no attribute 'encode'

The table has the structure:
CREATE TABLE hist_point (
id BIGINT NOT NULL,
version SMALLINT NOT NULL,
visible BOOLEAN,
user_id INTEGER,
user_name TEXT,
valid_from TIMESTAMP,
valid_to TIMESTAMP,
tags HSTORE,
geom GEOMETRY(POINT,900913),
typ1 CHAR,
typ TEXT,
minor INTEGER,
CONSTRAINT hist_point_pkey PRIMARY KEY (id, version   )

The table is populated with data from OpenStreetMaps.  I have been able to load data from this table into normal Pandas DataFrames - so no issue with the database connection, so am unsure why it's not working for GeoPandas.
I am using Python 2.7 loaded via Anaconda (and GeoPandas loaded using 'pip install geopandas') on OSX 10.11.
And insight would be much appreciated.
Thank you,
Stephen.


text:
Q: Using 6S lithium-ion battery with(out) bms? I built a 6S LTO battery pack and I am wondering - does it need BMS? Battery will be charged with car alternator - voltage wont exceed passive BMS balancing threshold (battery will never reach maximum voltage), thus balancing wont even happen. Is it safe to use battery like that? Or do I need to use active balancing, which, as I understand, balance all the time, at any voltage?

A:
does it need BMS?

You always need a BMS for any Li-ion battery, LTO and any other chemistry. Never operate Li-ion cells without protection: it's at best dangerous for the cells, and and worst dangerous for people and property.

Battery will be charged with car alternator

Never charge a Li-ion battery directly from an alternator that is not current limited (and most alternators aren't). Always use a charger (a current limiting and voltage regulating circuit) between the alternator and the Li-ion battery. If you don't, it damages the battery and overheats the alternator.

thus balancing wont even happen

Well, that's up to you. Just know that the effective battery capacity will go down faster as the cells get our of balance.

Is it safe to use battery like that?

Absolutely not!

Or do I need to use active balancing

You don't. (Most applications don't.)

, which, as I understand, balance all the time, at any voltage?

No, that's not what "active balancing" is. That would be "SoC based" balancing.