text:
Q: Change background loading color in Windows 10? In Windows 10, you can change the colors by going to "Control Panel > Personalization > Colors" and select the color you prefer. This also changes the background color of the windows. When you open a Windows app the entire background will be of that color.
For example, if you have selected the color green then it will look like this at first when loading.
But this does not change the color of the Windows Mail background. The Mail app background is always blue. How to change its color to green?

A: The Windows default background has no effect on applications that use their own
themes, of which Windows Mail is one.
Such applications need to be configured to use your preferred background color.
As described in the post provided by DavidPostill,
How To Change The Mail App Background In Windows 10,
this is done in the account settings:


text:
Q: Implementing binary search with tolerance in JavaScript? I'm trying to find a number between min and max. I only know (through using the more method) whether the number I'm guessing is higher or lower than the number passed. The number that I need to find can be a decimal, which is what is making me nervous, as the average binary search seems to mostly concern itself with the business of integers.
The algorithm I've written is an attempt at a binary search, without the array. The difference, as I see it, between a classical binary search is that the values and the index of the search have been conflated into the same task.

var tolerance = 0;

var tries, min, max, current, needed;

function search () {

  tries = 0;
  min = 0;
  max = 100;
  needed = Math.random() * max;
  current = (max - min) / 2;

  while (!accept() && tries < 100) {

    if (more(current))
      min = current;
    else
      max = current;

    current = min + ((max - min) / 2);

    tries++;

  }

  results();

}

function more (n) {

  return n < needed;

}

function accept () {

  return Math.abs(current-needed) <= tolerance;

}

function results () {

  document.getElementById('results').innerHTML = 'accepted: ' + current + '
needed: ' + needed + '
tries: ' + tries;

}
<button onclick="javascript:search();">search</button>

My question is this; given what I want to do, can this code be improved upon? Or perhaps there is a better way of doing this all together? Obviously, the number of tries is greatly improved by increasing the tolerance - but it's at the expense of the accuracy of the final result. For example, would it make sense for me to increase the tolerance after a certain number of tries?
Also, how best would one go about ensuring that the needed number is in range? I know I could ensure that !more(max) && more(min) before attempting the while loop, but is there a more efficient way than simply bolting on two extra checks at the beginning of the script?

A: It's hard to do better than a binary search for searching a number in a range.
Assuming the range will always be know/similar, validation can be done before the search() function either with the use of your more() function or a clamp function. See this link clamp number
If the range can change dramatically, some kind of exponential function could be used to find 'the good range'.

*

*Range 0-100

*Range 101 to 1000

*Range 1001 to 20000

*etc.

You could also considerate setting your tolerance as a percentage, or as a number of 'good decimals'. See here
Know that you will get the same efficacity while searching for a number with x decimals (ie. 123.45 in a range 0 to 1000) and while searching for 12345 in a range 0 to 100 000.
Since the 'worst case scenario' number of tries is ⌈log2(n+1)⌉. Having a 100 tries allows you to find a number precisely in a range of 0 to n = 1267650600228229401496703205375. Since you have decimals, for every decimal of precision you desire, you need to divide this number by 10.
A 0.xxxxxx precision would leave you with a 0 to 12676506002282294014967032 range in which you would find your number in less than 100 tries.
If my calculations are correct..

A: When binary searching on a real interval, there is no need to check for equality, but instead you keep refining the search interval till it's sufficiently small.
// Generated by CoffeeScript 1.10.0
(function() {
  var eps, hi, lo, mid, more, secret;

  // This is your tolerance value.
  eps = 0.01;

  // The binary search routine will never get to see this.
  secret = 45.63;

  more = function(test) {
    return test > secret;
  };

  lo = 0;

  hi = 100;

  while (hi - lo > eps) {
    mid = lo + ((hi - lo) / 2);
    if (more(mid)) {
      hi = mid;
    } else {
      lo = mid;
    }
  }

  console.log(mid);

}).call(this);

Output: 45.635986328125

On out of range values, the output will be equal to lo or hi, where equal means that their absolute difference will be less than eps.

See also: Binary searching on real numbers: Topcoder.

binary_search(lo, hi, p):
   while we choose not to terminate:
      mid = lo + (hi-lo)/2
      if p(mid) == true:
         hi = mid
      else:
         lo = mid

     return lo // lo is close to the border between no and yes

Since the set of real numbers is dense, it should be clear that we usually won't be able to find the exact target value. However, we can quickly find some x such that f(x) is within some tolerance of the border between no and yes. We have two ways of deciding when to terminate: terminate when the search space gets smaller than some predetermined bound (say 10^-12) or do a fixed number of iterations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting variables in NSUserDefaults I am trying to use NSUserDefaults function to save my game. My question is how to code a variable in NSUserDefaults so that I can press a button and the value can add up to the original value.
I have tried the following code to save and to load the method, but failed the numbers can load correctly.
saving
- (IBAction)water2:(id)sender {

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    NSMutableArray * water = [defaults objectForKey:@"water"];

    for(NSNumber * waternumber in water) {
        NSLog(@"Score: %i", [waternumber intValue]);

        NSMutableArray * water = [NSMutableArray arrayWithObjects:
                                  [NSNumber numberWithInt:[waternumber intValue]+1], nil];

        [defaults setObject:water forKey:@"water"];

    NSLog(@"Score: %i", [waternumber intValue]);

        NSMutableArray * nestedStructure = [[[NSUserDefaults standardUserDefaults] objectForKey: @"nested"] mutableCopy];

        // Make some change to the structure

        // Add it the whole thing back into NSUserDefaults
        [[NSUserDefaults standardUserDefaults] setObject:nestedStructure forKey:@"nested"];
        // Synchronize to ensure it's saved
        [[NSUserDefaults standardUserDefaults] synchronize];
    } }

Loading method:
- (IBAction)continue:(id)sender {
    NSMutableArray * nestedStructure = [[[NSUserDefaults standardUserDefaults] objectForKey: @"nested"] mutableCopy];

    // Make some change to the structure

    // Add it the whole thing back into NSUserDefaults
    [[NSUserDefaults standardUserDefaults] setObject:nestedStructure forKey:@"nested"];
    // Synchronize to ensure it's saved
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    NSMutableArray * water = [defaults objectForKey:@"water"];

    for(NSNumber * waternumber in water) {
        NSLog(@"water: %i", [waternumber intValue]);
    }

A: for saving into NSUserDefaluts
 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
 NSMutableArray * water = [[NSMutableArray alloc] init];
 [defaults  setObject: water forKey:@"water"];

for getting in some where
 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
 NSMutableArray *water1 = [[NSMutableArray alloc]initWithArray:[defaults objectForKey:@"water"]];


text:
Q: Show that G', the commutator subgroup of G, is normal in G. Prove that any subgroup A with G' $\subseteq$ A $\subseteq$ G is normal in G. Show that G', the commutator subgroup of G, is normal in G.
Prove that any subgroup A with G' $\subseteq$ A $\subseteq$ G is normal in G.
So the definition of the commutator subgroup is that;
In the group G, let G' be the subgroup generated  by the set {$xyx^{-1}y^{-1}$ : x,y in G}.
So to show it is normal in G I must show that ($xyx^{-1}y^{-1})^{-1}G'xyx^{-1}y^{-1}$=G' but I just can't manipulate it to work.
Thanks

A: Suppose $g \in A$.  You know that $k= hgh^{-1}g^{-1} \in A$, because $k= hgh^{-1}g^{-1} \in G' \subset A$.  Hence $hgh^{-1} = kg \in A$.
Note that this proof is shorter than the standard proof that $G'$ is normal in $G$.

A: A subgroup $N$ of $G$ is normal if $gng^{-1}$ is in $N$ for all $g\in G$ and $n\in N$. You can use this to check normality of the derived subgroup.


text:
Q: Log all queries executed on SQL Server Management Studio I am using SQL Server 2008 R2, been a technical manager I would like to monitor all the queries executed on the SQL Server Management Studio query window, is there an option to log this or any open source software I can use, kindly suggest

A: Use SQL Profiler and insert the values into a table. Its risky as the table size will increase drastically. Also this will impact the performance of the server as well. You can filter the resultset based on the ApplicationName as Micorsoft SQL Server Management Studio - Query and filter the events only for T-SQL SQL:StmtStarting


text:
Q: How to prompt user to sign in after filling out form while keeping form data with rails I have a Rails 4 App an Order Model where a user fills out a form for necessary data for price calculations etc. What I want is that they are prompted to sign in (with DEVISE gem) at the end of step_3 and are routed to a payment section but they can store their form data from the Order Model that the user has previously filled out, this data being the order form data before they signed in.
Main Issues:

*

*Redirecting them after sign in mid way through process using devise

*Saving the form data and associating it with the current user immediately before routed to the payment section

*the Order.find_by section. What do I find the order by?
Background:
Rails 4
PostgreSQL
Devise Gem
class OrdersController < ApplicationController
 before_action :authenticate_user!, :except => [:step_1,:process_step1,:step_2a,:process_step_2a, :step_2b, :step_2c, :step_3]

def step_1
  @order = Order.find_by id: session[:order_id]
  if @order.nil?
  @order=Order.new
  @order.save!
  end
end

def process_step1
order = Order.find_by id: session[:order_id]
order.update_attributes(order_params)
if (order.building == 'Residential') || (order.building == 'Commercial' )
  redirect_to step_2a_path
elsif (order.building == 'Commercial + Parking') || (order.building == 'Residential + Parking')
  redirect_to step_2b_path
else
  redirect_to step_2c_path
  end
end

  def step_2a
   @order = Order.find_by id: params[:session_id]
 end

  def process_step_2a
  order= Order.find_by status: 'cart'
# , user_id: current_user.id
order.update_attributes(order_params)
if order.save
  redirect_to step_3_path
  end
  end

  def step_2b
  @order= Order.find_by status:'cart'
# , user_id: current_user.id
  end

  def process_step_2b
  order= Order.find_by status: 'cart'
# , user_id: current_user.id
order.update_attributes(order_params)
if order.save
  redirect_to step_3_path
end
 end

  def step_2c
  @order= Order.find_by status:'cart'
  # , user_id: current_user.id
  end

  def process_step_2c
   order= Order.find_by status: 'cart'
   order.update_attributes(order_params)
    if order.save
  redirect_to step_3_path
end
  end

  def step_3
  @order= Order.find_by status:'cart'
# , user_id: current_user.id
  end

 def process_step_3
   order= Order.find_by status: 'cart', user_id: current_user.id
   order.update_attributes(order_params)
   if order.save
  redirect_to payment_path
end
 end

 def payment
  @order= Order.find_by status:'cart', user_id: current_user.id
 end

A: First off you should really refactor you routes. With that structure your application is going to get exponentially more confusing to navigate the larger it grows, and will make it practically impossible for anyone else to work on it/help you with debugging. Take a look at this guide on RESTful routing to learn more.
As for you issue, you can store their form data in one of the rails temporary storage mechanisms (I'd recommend a session variable) while they're logging in then redisplay it after they finish

A: *

*There is a callback after_sign_in_path_for, you can add it in your ApplicationController. Usage is here
2,3. Continue to use session[:order_id]. Can't figure out why do you use find_by status: 'cart' and Order.find_by id: params[:session_id]. Check this url to save old session after log in.
Personally I do not recommend this method and I think it's better to bind order id to some secure random generated value stored in cookie.


text:
Q: Convert the JavaScript Object to similar items I have a JavaScript array of objects which looks like this,
var object = [{"Fruit" : "Banana", "NAPrice" : 45},
     {"Fruit" : "Banana", "EUPrice" : 50},
     {"Fruit" : "Banana", "AUPrice" : 30},
     {"Fruit" : "Apple" , "NAPrice" : 25},
     {"Fruit" : "Apple" , "EUPrice" : 20},
     {"Fruit" : "Apple" , "AUPrice" : 23},
     {"Fruit" : "Berry", "NAPrice" : 18},
     {"Fruit" : "Berry", "EUPrice" : 8},
     {"Fruit" : "Berry", "AUPrice" : 17}];

As you can see in each object there are similar fruits but different traits, can we combine them altogether? To look something like this,
var object = [{"Fruit" : "Banana", "NAPrice" : 45, "EUPrice" : 50, "AUPrice" : 30},
     {"Fruit" : "Apple", "NAPrice" : 25, "EUPrice" : 20, "AUPrice": 23}
     {"Fruit" : "Berry", "NAPrice" : 18, "EUPrice" : 8, "AUPrice": 18}];

PS: Note that there will be common number of prices for fruits, here 3 fruits prices of each kind.

A: You can use Array.reduce and Object.values() to achieve this. I first created an Object with keys as fruit values and kept assigning Objects to it. Later I took out all the values of the Object.

var object = [{"Fruit" : "Banana", "NAPrice" : 45},
     {"Fruit" : "Banana", "EUPrice" : 50},
     {"Fruit" : "Banana", "AUPrice" : 30},
     {"Fruit" : "Apple" , "NAPrice" : 25},
     {"Fruit" : "Apple" , "EUPrice" : 20},
     {"Fruit" : "Apple" , "AUPrice" : 23},
     {"Fruit" : "Berry", "NAPrice" : 18},
     {"Fruit" : "Berry", "EUPrice" : 8},
     {"Fruit" : "Berry", "AUPrice" : 17}];

var newObj = object.reduce((acc, ob) => {
  if (acc[ob.Fruit]) {
    Object.assign(acc[ob.Fruit], {...ob});
  } else {
    acc[ob.Fruit] = {...ob};
  }
  return acc
}, {});

var merges = Object.values(newObj)

console.log(merges)


text:
Q: MATLAB plot- Filtering data before plotting I have a 90x2 matrix a where a(:,1) is the x and a(:,2) is the y.
I want to plot only values where y is greater than BOOM. How can I do that?
Currently I have
plot(a(:,1),a(:,2));

One more thing, how can I display the numbers in full and not num*10^4?

A: The standard approach is to make a mask with find. You would do that first
mask = find(a(:,2) > BOOM);

the mask will be a list of index positions where the second column exceeded the BOOM threshold. You can use it to select only those entries from the row ordering
plot(a(mask,1), a(mask,2))

You could also make a logical mask, it works much the same way and is sometimes more convenient.
As for the display you can try
format short

A: You can do:
plot (a(a(:,2)>BOOM,1),a(a(:,2)>BOOM,2));
set(gca, 'YTickLabel', num2cell(get(gca, 'YTick')))


text:
Q: PyQt5 how to start multiprocess but in not main thread I am writing a program that reads data from an excel file to some system via API.
The function that fetches data from excel and sends it via API is in a separate thread to keep the GUI alive.
Loading via API is a long process. Most of the time is sending and waiting for API data.
I wanted to send each excel line in a separate process. How to do it?
def api_import(k, sheet,number_columns, items_number, ok, total, total_success):
   item = sheet[get_column_letter(3)+str(k)].value
   templ_id = sheet[get_column_letter(number_columns)+str(k)].value
   item_id = get_item_id(item)['item_id']
   query = {"template_id": str(templ_id)}
   resp = templ_attach(item_id, query)
   if resp==200:
      ok += 1
   total += 1
   item_create_param = 0
   item_update_param = 0
   item_error = 0

   for l in range(number_columns):
       if l <4:
           pass
       else:
           param_name = sheet[get_column_letter(l)+str(1).upper().replace(" ", "")].value
           param_description = sheet[get_column_letter(l)+str(2)].value
           param_value = sheet[get_column_letter(l)+str(k)].value
           param_type = sheet[get_column_letter(l)+str(3)].value
           if "[T]" in param_type:
               param_type = 4
               query = {"name": str(param_name), "type": param_type, "description": str(param_description), "text_value": str(param_value)}
           elif "[D]" in param_type:
               param_type = 0
               query = {"name": str(param_name), "type": param_type, "description": str(param_description), "numeric_value": param_value}
           else:
               param_type = 1
               query = {"name": str(param_name), "type": param_type, "description": str(param_description), "logical_value": param_value}

           resp = input_param(item_id, query)
           if resp==201:
               item_create_param += 1
           elif resp==202:
               item_update_param += 1
           else:
            item_error += 1

   if item_error == 0:
       total_success += 1
   return {'total':total, 'total_success':total_success, 'ok':ok}

class MainWindow(QDialog):
   def __init__(self):
       super(MainWindow,self).__init__()
       loadUi("gui.ui",self)
       self.browse.clicked.connect(self.browsefiles)
       self.load.clicked.connect(self.send)

   def browsefiles(self):
       fname=QFileDialog.getOpenFileName(self, 'Open file', 'C:\Program files', 'Excel Spreadsheet files (*.xlsx, *.xls)')
       self.filename.setText(fname[0])

   def send(self):
       self.worker = WorkerThread()
       self.worker.start()
       #self.worker.worker_complete.connect(self.evt_worker_finished)
       self.worker.update_progress.connect(self.evt_update_progress)

   #def evt_worker_finished(self, emp):
       #self.QMessageBox.information(self, "Done!", "Wczytywanie zakonczone!\n\n{} {}".format(emp["fn"], emp["ln"]))

   def evt_update_progress(self, val):
       self.progressBar.setValue(val)

class WorkerThread(QThread):
   update_progress = pyqtSignal(int)
   worker_complete = pyqtSignal(dict)
   def run(self):
       start_time = time.time()

       file_path = "import.xlsx"
       print(file_path)
       wb = load_workbook(file_path)
       sheetnames = wb.sheetnames

       for sheet in wb:
           print(sheet)
           number_rows = sheet.max_row
           print(number_rows)
           number_columns = sheet.max_column
           items_number = number_rows-3
           ok = 0
           total = 0
           progress = 0
           total_success = 0
           for k in range(number_rows+1):
               if k>3:
                   report = api_import(k, sheet,number_columns, items_number, ok, total, total_success)
                   total = report['total']
                   ok = report['ok']
                   total_success = report['total_success']
                   progress = round(total/items_number*100)
                   print("{}%".format(progress))
                   self.update_progress.emit(progress)

       self.worker_complete.emit({"emp_id":1234, "fn":"XXX", "ln":"YYYY"})

       end_time = time.time() - start_time
       item_time = end_time/total


text:
Q: Windows Azure - CDN as a Website? I'm using Windows Azure for hosting my MVC3 project.
This project is an online store for Facebook pages which divided into two parts:

*

*Management panel for sellers which allow to manage products and Orders.

*Online store for consumers which allow to browse products and place order(s).

My question is if it's possible to place the whole front-end on CDN (the online store that placed on Facebook page). What constitutes usability best practice for this situation?

A: Not really possible.  Though, you can place large portions of static content up there.  However, you cannot use the CDN in practice as a full webserver.  Since underlying resources are tied to blob storage and blob storage is case sensitive, you will find that you will get a lot of 404s in practice (e.g. user types default.html and page is actually Default.html in storage).  Also, you would have no dynamic abilities at all (no .aspx, .php, etc.) nor default pages (http://example.com/ actually might map to http://example.com/index.html).
Use it for what it is good for - quickly delivering static content and caching it on the edge, closest to your consumers.  It is not a replacement for a web server.


text:
Q: Difference Between J48 and Markov Chains I am attempting to do some evaluation of the relative rates of different algorithms in the C# and F# realms using WekaSharp and one of the algorithms I was interested in was Markov Chains. I know Weka has an HMM application but I have not been able to implement this into WekaSharp and was wondering if there was a way to modify the J48 Algorithm to suit this purpose. I know there is some similarity between J48 and first order Markov chains but am trying to determine what needs to be modified and if this is a reasonable thing to do. Here is the J48 as implemented in Yin Zhu's WekaSharp:
type J48() =
    static member DefaultPara =  "-C 0.25 -M 2"
    static member MakePara(?binarySplits, ?confidenceFactor, ?minNumObj, ?unpruned, ?useLaplace) =
        let binarySplitsStr =
            let b = match binarySplits with
                    | Some (v) -> v
                    | None -> false
            if not b then "-B" else ""
        let confidenceFactorStr =
            let c = match confidenceFactor with
                    | Some (v) -> v
                    | None -> 0.25 // default confi
            "-C " + c.ToString()
        let minNumObjStr =
            let m = match minNumObj with
                    | Some (v) -> v
                    | None -> 2
            "-M " + m.ToString()
        let unprunedStr =
            let u = match unpruned with
                    | Some (v) -> v
                    | None -> false
            if u then "-U" else ""
        let useLaplaceStr =
            let u = match useLaplace with
                    | Some (v) -> v
                    | None -> false
            if u then "-A" else ""
        binarySplitsStr + " " + confidenceFactorStr + " " + minNumObjStr + " " + unprunedStr + " " + useLaplaceStr

Thank you very much.

A: J48 is just an implementation of the C4.5 algorithm that learns decision trees by considering the entropy of each attribute (dimension) and taking the attribute that has maximum entropy as root of the current subtree. This algorithm does not need reinforcement.
I guess that by Markov Chains you mean Hidden Markov Model that is used in reinforcement learning.
You should take a look to HMMWeka.
A related question is:
What is the equivalent for a Hidden Markov Model in the WEKA toolkit?


text:
Q: Como hospedar site no meu pc Estou criando uma aplicação em php com usando o xampp.
Gostaria de saber como faço para transformar meu PC em um servidor de hospedagem, para poder acessar minha aplicação de qualquer lugar.
Ja tentei acessar o admin do meu roteador (D-link Dir-608) criei um "servidor virtual", todavia, sem sucesso, ocorre erro ao tentar acessar o ip externo.
Alguém tem alguma dica ou tutorial ensinando? Obrigado.

A: Utilize o software No-IP. Realize o cadastro no site, escolha um nome de host externo, exemplo minha-casa.sytes.net, instale o software em seu computador e acesse o software com suas credências.
Uma vez acessado e logado no software, será necessário configurar seu roteador para encaminhar um determinado tráfego a sua máquina. No caso de uma hospedagem, as portas importantes seriam as 80 para acesso via HTTP, e 443 para acesso via HTTPS. Acredito que apenas configurar a 80 seja o suficiente para o seu caso.
Para realizar essa configuração você vai precisar do IP da sua máquina, pois o que será feito é redirecionar todo o tráfego que chegar na porta 80 do seu roteador para sua máquina.
Para pegar seu IP, abra o Prompt de Comando e digite, ipconfig. Seu ip deverá ser algo parecido com 192.168.x.x, 10.x.x.x ou 172.16.x.x.
Acesse o roteador e procure pela configuração de encaminhamento de portas ou no inglês, port forward. Você deverá informar nessa configuração o endereço IP da sua máquina e também a porta de entrada e de saída. Tanto a porta de entrada como de saída será a porta 80 e o endereço IP o da sua máquina.
Com tudo configurado corretamente, você deverá configurar o xampp para responder no endereço do site que registrou no No-ip.
Espero que seja útil e consiga realizar sua configuração.


text:
Q: Rails get number of people who picked a radio button input option? Using devise, and so in my model I'll have a question, answer choices, and a submit button.
QUESTION
ANSWER CHOICE (30)
ANSWER CHOICE (20)
ANSWER CHOICE (n)
ANSWER CHOICE (n)
SUBMIT

On submit, I want it to show what answer choice was picked by how many people.
For example, if there were 100 people, and 30 people picked the first one, 20 the second, and so forth..how would I go about implementing this in rails?
A question would have_many answer choices, and I would have the form somehow show the answer choices in the select_for tag but for radio buttons, but how do I do the part where the rails app would show how many people picked what in the view?

A: You just have to use aggregate queries using COUNT and GROUP BY.
Check this out.
Example from the Rails documentation:
Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }


text:
Q: Getting the value out of a dynamic asp:DropDownList Basically, I have a drop down list with a ID and runat="server" tag and is inside a asp:TableCell. The original DDL has no options, but through javascript, I am populating the dropdown with some options that update my table on the front end. On button click, through my vb.net code, I need to retrieve the text inside the ddl. Any suggestions of how to do this would be nice. Thank you in advance, and if you need any more information from me please let me know.
P.S. I am not able to use ajax with this project.
[HTML] - Just showing the tablecell and ddl
<asp:TableCell ID="ocProduct">
    <asp:DropDownList ID="myDropDown"  CssClass="ocProduct"
      OnChange="indexChanged(this);" runat="server">
    </asp:DropDownList>
</asp:TableCell>

[VB.net]
Protected Sub updateWeight_Click(Sender As Object, e As EventArgs)
  msgbox(myDropDown.text) ' does not work
  msgbox(mytable.rows(1).cells(0).text) ' does not work
  msgbox(myTable.rows(1).cells(0).controls(0).toString) ' does not work
  msgbox(myDrowDown.selectedValue) ' does not work
  ' All of these are returning ""
end sub

[JavaScript] - This is just showing how I load the ddl
var ddl = document.getElementById('myDropDown');
var tempOption = document.createElement('option');
tempOption.text = "Please select an option..."
tempOption.value = 0;
ddl.options.add(tempOption);

for (var i = 1; i <= counter; i++) {
    var option = document.createElement('option');
    var tempArray = parsePerHash(i);

    option.text = tempArray[0];
    option.value = i;

    ddl.options.add(option);
    }
};

A: You have to use the specific properties of that control.
Try using "msgbox(myDropDown.SelectedValue)". You can see the list of properties here: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist_properties(v=vs.110).aspx


text:
Q: How to make images in Bootstrap 4 slider responsive? I am creating website page using bootstrap 4  slider, but images are not responsive and it looks good only in 1980x1080.
How to make images responsive?
My code looks like that:

                Get Started

A: Since you set the images to be as backgrounds for .carousel-item AND you don't have any other content on those items you should set couple more properties in order to see those images. Example:

.carousel-item {
  height: 400px; /* set some height*/
  /* optionals */
  background-repeat: no-repeat;
  background-position: cneter;
  background-size: 100% 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

                Get Started

As a side note: you can't use image as header, so don't place img inside h1.


text:
Q: Must the repository have persist functionality? In Fowler's book "Patterns of Enterprise Application Architecture" there is no mention of persistent features of the Repository pattern. By "persistent features" I mean such features that update, save, add or delete entities. Just pure matching mechanism over a set of domain objects.
On the other side, lets take a look at Mike Hadlow's blog post named Using the IRepository pattern with LINQ to SQL. There are concrete persistent methods like insert and delete.
So how should a repository pattern be implemented? Could you guys please point me towards good "true" repository implementations. I'm getting some frustration on this topic.
Thanks in advance! Hope for your help!

A: A repository should just act like an in-memory collection of data. The nomenclature you choose, whether it be Add or Insert, Delete or Remove, Select or Get, is not important.
You could separate your repository into 2 interfaces, and then have a ReadOnlyRepository for getting / selecting data, and a WriteRepository for adding / updating / deleting data. It doesn't matter. What matters is that your application or business code uses the repository to interact with data as if it was already loaded into memory, so you don't have to craft SQL queries intermingled with business or application code.
Update
Since we're talking about a pattern, there is not a single "true" repository interface or implementation. There can be many different implementations that all follow a similar pattern.


text:
Q: Extra quotes when logging objects with NLog I have a code that outputs interpolated string to the log with NLog.
Here is an example
_logger.LogDebug($"REQUEST {webRequest.RequestUri}", Id)
WebResponse webResponse = await _httpService.SendRequestAsync(webRequest);
var response = ParseResponse(webResponse);
_logger.LogDebug($"RESPONSE {(int)response.StatusCode} {JsonConvert.SerializeObject(response.Body)}", Id);

In this example, in a first case of calling the function _logger.LogDebug, I get the expected result as a result:
2019-04-15 09:27:24.5027 DEBUG   e1701b07-d228-4543-a320-3cb1b7f2e4b0 REQUEST http://url/
But in the second case, the expected result is wrapped in additional quotes.
2019-04-15 09:27:57.2907 DEBUG   "e1701b07-d228-4543-a320-3cb1b7f2e4b0 RESPONSE 200 [{...},{...}]"
Here is the _logger.LogDebug method
using NLog;

private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

public void LogDebug(string message, Guid id)
{
    Logger.Debug($"{id.ToString()} {message}");
}

The result of the JsonConvert.SerializeObject(response.Body) is a string representation of array of json eg: [{"key":"value","key":"value"},{"key":"value","key":"value"}]
Here is a part of my Nlog.config
  <targets>

    <target name="csv" xsi:type="File" fileName="${shortdate}-${level}-services.log">
      <layout xsi:type="CSVLayout" delimiter="Tab" withHeader="false">
        <column name="time" layout="${longdate}" />
        <column name="level" layout="${uppercase:${level}}"/>
        <column name="message" layout="${message}" />
      </layout>
    </target>

  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="csv" />
  </rules>

Why do I get additional quotes in the second case and how can I avoid it?

A: As per the docs,

CSV Options quoting - Default Quoting mode for columns.
Default: Auto
Possible values:
Auto - Quote only whose values contain the quote symbol, the separator or newlines (Slow)
All - Quote all column. Useful for data known to be multiline such as Exception-ToString
(Fast) Nothing - Quote nothing (Very Fast)

The default is Auto - which means it is quoting your string since it contains a quote, a tab (the separator) or a new line.
It is important it does this, so that the file is a valid CSV file (otherwise Excel etc don't know where the column data begins and ends.


text:
Q: Create a discrete distribution from transformed container elements Suppose we have a std::vector<T> v and T is a class with a member function U T::f() const, where U is convertible to double. I want to create a std::discrete_distribution<> d(/* v[0].f(), ..., v[v.size() - 1].f() */). Is this possible without creating a new container containing the values v[0].f(), ..., v[v.size() - 1].f()?

A: Something like boost::transform_iterator can do that. You'll just need to create those from the vector's iterators.

A: If you can add a operator double to T then you can have that return f() and then use the iterator constructor of std::discrete_distribution like
struct Foo
{
    operator double() const { return f(); }
    double f() const { return 1.0; }
};

int main()
{
    std::vector<Foo> foo(10);
    std::discrete_distribution dd{foo.begin(), foo.end()};
}


text:
Q: Diagnosing a dynamic programming vs priority queue situation I am trying to determine if the following can be solved using DP or priority queue:
1) I have a set of objects. My goal is to choose enough of them to give me the highest score, while fulfiling a constraint.
2) Characteristic of each object. Each object has a score and a depth associated with it.
3) Constraint: The sum of depths from the eventual set of objects must be <=100
For example

Index/Score/Depth (numbers below follow accordingly)
1 70 10
2 60 30
3 40 50
4 40 25
5 30 35

The possible output from these can be

Sum of Score/Sum of Depth (numbers below follow accordingly)
170 90  (i.e. Objects 1,2,3)
200 100 (i.e. Objects 1,2,4,5) -- the winner
130 90  (i.e. Objects 2,4,5)
150 85  (i.e. Objects 1,3,4)
140 95  (i.e. Objects 1,3,5)

The above shows that the greedy approach won't work, i.e. always taking the highest score or lowest cost. For example taking objects 4,5 (total score 70, total depth 60) is better than taking just object 3 (score 40 cost 50). As a result of this, a straightforward approach will not work, I need to explore my entire search space. So it seems like priority queue won't work, would it? How about DP? Is there a way to apply dynamic programming here?

A: The stated problem is a reformulation of the classical Knapsack problem, which is well-known to be solvable by dynamic programming. See this Wikipedia article for more details. The approach using a priority queue will most likely result in a greedy algorithm, which can be refined to yield a 2-approximation. More precisely, the items can be sorted by efficiency and be taken greedily until the next item does not fit anymore. Then take the better out of this solution and the most profitable item.


text:
Q: Convert data of 1 column to multiple columns per user I have two tables which are created with a stored procedure.
Visualization first and second table.
The first table is created based on the id the user selects.
The second table is created when the user selects two filter. These filters are then added in the binding table.
The result table should use the first table to get all the data and the second one to match the correct region and function per user.
The result should be like this:
Image result table
Is it possible to get all the regions in one column and all the matching functions in that region in the another column based on the binding table?
I'm using Oracle 11g.

A: below sql returned the same result like your [Image result table].
try to run below sql in your Oracle.
is this what you want?
WITH
    COUNTS AS (
        SELECT 120 AS id, 1 AS persionId, 'Region' AS tellingName, 'RegionX' AS tellingValue FROM DUAL
        UNION ALL
        SELECT 120 AS id, 2 AS persionId, 'Region' AS tellingName, 'RegionX' AS tellingValue FROM DUAL
        UNION ALL
        SELECT 120 AS id, 3 AS persionId, 'Region' AS tellingName, 'RegionY' AS tellingValue FROM DUAL
        UNION ALL
        SELECT 120 AS id, 1 AS persionId, 'Function' AS tellingName, 'FunctionX' AS tellingValue FROM DUAL
        UNION ALL
        SELECT 120 AS id, 2 AS persionId, 'Function' AS tellingName, 'FunctionY' AS tellingValue FROM DUAL
        UNION ALL
        SELECT 120 AS id, 3 AS persionId, 'Function' AS tellingName, 'FunctionX' AS tellingValue FROM DUAL
    ),
    BINDING AS (
        SELECT 1 AS seqid, 120 AS id, 'Region' AS "Column", 'Function' AS "Row" FROM DUAL
    ),
    COLUMN_INFO AS (
        SELECT
            T2.seqid,
            T1.tellingValue AS "Column"
        FROM
            COUNTS T1,
            BINDING T2
        WHERE
            T1.id = T2.id AND
            T1.tellingName = T2."Column"
        GROUP BY T2.seqid, T1.tellingValue
    ),
    ROW_INFO AS (
        SELECT
            T2.seqid,
            T1.tellingValue AS "Row"
        FROM
            COUNTS T1,
            BINDING T2
        WHERE
            T1.id = T2.id AND
            T1.tellingName = T2."Row"
        GROUP BY T2.seqid, T1.tellingValue
    )
SELECT
    T1.seqid,
    T1."Column",
    T2."Row"
FROM
    COLUMN_INFO T1,
    ROW_INFO T2
WHERE
    T1.seqid = T2.seqid


text: Q: How can I record my screen on ubuntu" I used several apps such as kazam, simplescreenrecorder, obs etc to record screen but after finishing the recording I find only playing a black screen with audio only. How can I fix this and record different activities?


text:
Q: Swift: UIBezierPath fill intersection of 2 paths I'm working with 2 UIBezierPath to create a rectangle and a semicircle shape. It works fine but I am not able to fill the intersection with color.

That's my drawCircle and my addPaths functions:
private func drawCircle(selectedPosition: SelectionRangePosition, currentMonth: Bool) {
    circleView.layer.sublayers = nil

    let radius = contentView.bounds.height/2
    let arcCenter = CGPoint(x: ceil(contentView.bounds.width/2), y: ceil(contentView.bounds.height/2))
    let circlePath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: .pi/2, endAngle: .pi * 3/2, clockwise: selectedPosition == .left)

    let semiCircleLayerPath = UIBezierPath()
    let semiCircleLayer   = CAShapeLayer()
    semiCircleLayer.fillColor = UIColor.tealish.cgColor

    circleView.layer.addSublayer(semiCircleLayer)

    switch (selectedPosition, currentMonth) {
    case (.left, true):
        let rectanglePath = UIBezierPath(rect: CGRect(x: contentView.bounds.width / 2, y: 0, width: ceil(contentView.bounds.width / 2), height: contentView.bounds.height))
        addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)

    case (.middle, true):
        backgroundColor = .tealish

    case (.right, true):

    // Note: The + 10 is just to overlap the shapes and test if the filling works

        let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: ceil(contentView.bounds.width / 2) + 10, height: contentView.bounds.height))
        addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)

    default:
        backgroundColor = .clear

    }
}

private func addPaths(_ semiCircleLayerPath: UIBezierPath, _ rectanglePath: UIBezierPath, _ circlePath: UIBezierPath, _ semiCircleLayer: CAShapeLayer) {
    semiCircleLayerPath.append(circlePath)
    semiCircleLayerPath.append(rectanglePath)

    semiCircleLayer.path = semiCircleLayerPath.cgPath
}

A: The problem is that the semicircle path and the rectangle path are being added in opposite directions.  This is a function of the way the Cocoa API adds them, unfortunately; in your case, it means that the intersection has a "wrap count" of 0.
Fortunately, there is an easy fix: create separate paths for the semicircle and the rectangle.  When fill them both individually, you should get your desired result.
Unfortunately, this will mean that you can't use layer drawing only: you will want to use the drawRect method to draw the background.

A: If your dates are separate UILabels, you can skip this rendering & path filling problem entirely by dropping a UIView as a child of the calendar, under the labels holding the dates; give it a background color & rounded corners (using layer.cornerRadius as usual). That'll take care of your rounded rect for you.


text:
Q: Disabling gesture in react-navigation 5 I'm creating a project and Initially, it has two stack screens. SettingScreen and ChangePasswordScreen and the one drawer.
 export const SettingStackScreen = ({ navigation }) => (

    <SettingStack.Navigator>
        <SettingStack.Screen
            name="Settings"
            component={SettingScreen}
        />
        <SettingStack.Screen
            name="ChangePassword"
            component={ChangePasswordScreen}
        />
    </SettingStack.Navigator>

);
app.js
             <Drawer.Navigator
                        drawerContent={(props) => <DrawerContent {...props} />}
                    >

                        <Drawer.Screen name="Settings" component={SettingStackScreen} />
                    </Drawer.Navigator>

using this code Drawer is accessible on both screen but I want to access drawer only first screen of SettingStackScreen not on others screen.
I tried gestureEnabled but it disabling the drawer swipe gesture in the both screen.

A: give this a go:
<Drawer.Navigator
  drawerContent={(props) => <DrawerContent {...props} />
  edgeWidth={-1} // don't allow slide-to-open
>
  <Drawer.Screen name="Settings" component={SettingStackScreen} />
</Drawer.Navigator>

from the docs:

edgeWidth
Allows for defining how far from the edge of the content view the
swipe gesture should activate.
This is not supported on Web.

If you go with this solution you're gonna need a burger menu or something that opens the drawer menu, something like:
<BurgerMenuButton onPress={() => navigation.toggleDrawer()} />


text:
Q: Printing an answer on a single page I wanted to print an answer for reference purposes. Is there any way to get just an answer on a page, without the question or other answers?

A: Seems there's no direct link to just the answer, but as Bart mentions in comments, Chrome print dialog, when "more settings" is revealed, lets you print just a selection, so that's a good workaround.

Chrome/Chromium : select your text > File > Print… > More settings > Selection only

It looks like it preserves the content well enough.


text:
Q: Secure Web API With Azure AD Can anyone provide me with instructions on how to setup and secure a Web API project using Azure AD?  I can create the project but when I navigate to /api/values/, I get a 401 response.  The application has been added to the list of applications in my Azure AD directory.
I found a blog post here that appears to address this topic but the steps do not match my environment.  Perhaps this is because it is a bit outdated?
What am I missing?

A: Take a look at the Web API examples at https://github.com/AzureADSamples, specifically WebApp-WebAPI-OAuth2-AppIdentity-DotNet and AzureADSamples/WebApp-WebAPI-OAuth2-UserIdentity-DotNet.


text:
Q: Checking for an instance of a sub class in a list and returning the object I have two objects A and B. Where B is an extension of A.
and I have a list that can contain As and Bs
and I have a method that goes something like:
B findB()
{
    for (int i = 0; i < ABlist.size(); i++)
    {
        if(ABlist.get(i) instanceof B)
        {
                return ABlist.get(i);
        }
        else{return null;}
    }
    return null;
}

which is supposed to look through all the objects in the list and return the object if it is an instance of B. But im getting an incompatible types error because an A cannot be converted to a B.
How would be the best way to solve this issue?

A: Instead of doing instanceof, you could add a method to class and its subclasses which returns this for specific subclass and null for other subclasses. Like this:
class A {
  public A get() {
    return null;
  }
}
class B extends A {
  @Override
  public A get() {
    return this;
  }
}
...
B findB() {
    for (A a : ABlist) {
        if (a.get() != null) {
            return (B) a;
        }
    }
    return null;
}

The idea is to avoid instanceof usage when possible. This operator is the part of the language, but wide usage of reflection and instanceof can make your application slow and unmaintainable.


text:
Q: Terraform For each loop on object and pass to child module I have a AWS s3 lifecycle rule of complex type (object) in my variables.tf file and have assigned it to a variable. Afterwards, I am using for_each loop to iterate over the object and passing this variable from a parent module to a child module where s3 resource is being created where I am stuck and I am not sure if my approach is correct or not. I know that for_each loop only accepts maps and sets but I could not find any resource to convert object to map and I am confused if I should convert object into map in my case.
I am new to Terraform and using Terraform v1.0.5 and the errors below are not of any help which I also tried to search but of no luck. I am trying to implement it for the last two days .I would appreciate if someone could please guide me what I am doing wrong.

A: Your parent module xyz-parent-module should pass the variable  rule_xyz like this: -
module "xyz-parent-module" {
  source = "./aws-module/s3-bucket-module"

  for_each = var.lifecycle_rule_60_days
  rule_xyz = {
    lifecycle_id    = each.value["life_id"]
    prefix_value    = each.value["prefix_val"]
    enabled_value   = each.value["bucket_enabled"]
    expiration_days = {
      days_value = each.value["expiration_list"].expiration_days
    }
  }
}


text:
Q: Potential mod_rewrite Conflict with Placement of POST Request Protection Code in .htaccess (WordPress) For added security, I am trying to block non-standard POST requests on my membership-based WordPress site using the following .htaccess code:
# Block non-standard POST requests
RewriteCond %{REQUEST_METHOD} POST [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-admin/ [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-cron.php [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-login.php [NC]
RewriteCond %{REQUEST_URI} !^.*/sign-in/ [NC]
RewriteRule ^(.*)$ - [F]

The /sign-in/ page is "whitelisted" via the last condition because it is the designated URL that all POST requests are made to by site members when they log in:

I have discovered that the code only works (i.e., successfully blocks all POST requests that are not whitelisted via the rewrite conditions) when placed within the default WordPress .htaccess code:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# Block non-standard POST requests
RewriteCond %{REQUEST_METHOD} POST [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-admin/ [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-cron.php [NC]
RewriteCond %{REQUEST_URI} !^.*/wp-login.php [NC]
RewriteCond %{REQUEST_URI} !^.*/sign-in/ [NC]
RewriteRule ^(.*)$ - [F]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

However, if the POST-blocking code is placed above or below the WordPress .htaccess code, the /sign-in/ condition does not work. If the code is placed above the WordPress default code, POST requests to the /sign-in/ page are blocked via 403 (though interestingly, POST requests to /wp-login.php are not blocked). If the code is placed below the WordPress default code, nothing is blocked at all. I have been told (by Restrict Content Pro, the plugin developers) that the login process checks $_POST values, so it wouldn't work if a POST request wasn't actually being made (my initial thought was that somehow the /sign-in/ URL wasn't getting recognized as a POST request).
I've also been told that this is not expected behavior and that the POST-blocking code should work correctly regardless of where it is placed in the .htaccess file. It has been suggested that there could be some unique server configuration that is causing this behavior. However, I've tested the issue on several different Apache servers/hosting accounts (including stripped-down WordPress installations) and am getting the same results.
I would like to understand the reason for this behavior. I imagine it could have something to do with mod_rewrite and how RewriteRules and/or their flags are being processed, but I haven't been able to come up with any specific ideas that I can test. I've also checked error logs and even tried enabling mod_rewrite logging but haven't found anything of value as far as I can tell.


text:
Q: command not found: vcpkg after downloading it in macOS I am trying to open an OpenCV project using Vscode in macOS. To run it, I need to download the OpenCV packages.
[enter image description here][1]
[1]: https://i.stack.imgur.com/bMl1N.png
Then I was led to the vcpkg web page and tried to install it following the instructions.
Step 1: Clone the vcpkg repo

git clone https://github.com/Microsoft/vcpkg.git

Step 2: Run the bootstrap script to build vcpkg

./vcpkg/bootstrap-vcpkg.sh

After Step 2, the following texts were showed in the terminal:
/vcpkg/bootstrap-vcpkg.sh
Downloading vcpkg-macos...
Telemetry
---------
vcpkg collects usage data in order to help us improve your experience.
The data collected by Microsoft is anonymous.
You can opt-out of telemetry by re-running the bootstrap-vcpkg script with -disableMetrics,
passing --disable-metrics to vcpkg on the command line,
or by setting the VCPKG_DISABLE_METRICS environment variable.

Read more about vcpkg telemetry at docs/about/privacy.md

I don't know if this means a successful installation. When I try to search or install a package, it says

vcpkg search [opencv2]
command not found: vcpkg

How could I fix it?


text:
Q: my code taking multiple strings and counting whitespaces So I'm writing a program that takes in three scanner inputs at a time and counts all the whitespaces in the strings before returning the amount totaled. (scanner inputs are predetermined with testcases in JUnit in another class).
This is my code currently, and I'm not sure where I'm going wrong.
public static int findMostWhitespace (Scanner scn)
{
    String[] array = new String[3];
    for (int i = 0; i < array.length; i++) {
        array[i] = scn.nextLine();
    }
    String input = array[0];
    int spaces = 0;
    for (int i = 0; i < input.length(); i++) {
        if (Character.isWhitespace(input.charAt(i)))
            spaces++;
        }
        String input2 = array[1];
        for (int i = 0; i < input2.length(); i++) {
            if (Character.isWhitespace(input2.charAt(i)))
                spaces++;
        }
        String input3 = array[2];
        for (int i = 0; i < input3.length(); i++) {
            if (Character.isWhitespace(input3.charAt(i)))
                spaces++;
        }
        return spaces;
    }
}

Is there a more efficient way to go about this?

A: Just use replace to replace the whitespaces and count the difference in length
//Scanner scn = new Scanner (System.in);
public static int findMostWhitespace (Scanner scn)
  int numOfSpaces = 0;

  for (int i = 0; i < 3; i++) {
    String str = scn.nextLine();
    int strlen = str.length();
    numOfSpaces += strlen - str.replaceAll(" ", "").length();
  }

  return numOfSpaces;
}

A: First, Remove duplicated code.
public static int findMostWhitespace (Scanner scn)
    {
        int spaces = 0;
        String input;
        for (int j = 0; j < 3; j++) {
            input = scn.nextLine();
            for (int i = 0; i < input.length(); i++) {
                if (Character.isWhitespace(input.charAt(i)))
                    spaces++;
            }
        }
        return spaces;
    }

A: here's the logic
public class MyClass {
    public static void main(String args[]) {

    String s1="hello    world hi";
    System.out.println(s1.length());
    String s2=s1.replaceAll("\\s+","");
    System.out.println(s2.length());
    int count =s1.length()-s2.length();
    System.out.println("White Space "+count);

    }
}

it can also count duplicate space by replacing all using \\s+
and the output is
17
12
White Space 5

explanation
first print statement prints the total length
second print statement print the length after removing space
third difference between them ie total white space


text:
Q: TDirectory::GetFiles listing ignoring case on iOS (FMX, C++) The code below lists files that have extension .cfg and it works fine on Win32.  But, on iOS if i have a file that a user named with caps for the extension (e.g. test.CFG) then i miss it. I found this post using Delphi that might work using TDirectory::TFilterPredicate but i don't know how to implement in C++Builder.
TStringDynArray list;
TSearchOption searchOption;
UnicodeString DocsPath;
int lenDocsFolder;

DocsPath = System::Ioutils::TPath::GetDocumentsPath();
lenDocsFolder = DocsPath.Length();
searchOption = TSearchOption::soTopDirectoryOnly;
try
{
  list = TDirectory::GetFiles(DocsPath, "*.cfg", searchOption);
}
catch (...)
{
    ShowMessage("Incorrect path or search mask");
    return;
}

I suppose i can just run a *.cfg block of code followed by a *.CFG but i'm hoping there is a cleaner approach.

A: Sorry, but I'm not used to C++. But this applies to both C++ and Delphi.
You are calling:
TDirectory.GetFiles(
   const Path, SearchPattern: string;
   const SearchOption: TSearchOption): TStringDynArray;

If you instead call this overloaded version:
TDirectory.GetFiles(
   const Path, SearchPattern: string;
   const SearchOption: TSearchOption;
   const Predicate: TFilterPredicate): TStringDynArray;

you should be able to get what you need.
The TFilterPredicate type is defined as:
TFilterPredicate = reference to function(
   const Path: string;
   const SearchRec: TSearchRec): Boolean;

and should be the correct way to override the way files are matched.

A: I tried the Using a Lambda Expression from the link Remy posted in comment.  I got an E2188 Expression syntaxerror until i disabled the classic Borland compiler.  The code works great for simple predicate (on both Win32 and iOS).
  String ext(".cfg");
  files = TDirectory::GetFiles(CalcPath,
                      [ext](const String Path, const System::Sysutils::TSearchRec &SearchRec) -> bool
                      {
                        return ExtractFileExt(SearchRec.Name) == ext;
                      });

Now, how do i modify the extension string to return results for both .cfg and .CFG at same time?
  String ext(".cfg");  // works fine
  String ext(".cfg;.CFG");  // finds nothing


text:
Q: How do I jump to the next/prev diff in GIT difftool? I am using git difftool to compare 2 large files in VIM. I want to navigate only to the lines that differ.
How do I navigate quickly between lines that differ using GIT difftool ?
I am looking for something like winmerge shortcut keys :
Alt+down  - Next Change
Alt+Up    - Prev Change

A: vim Has an extensive and pretty good helpfile. You would do yourself a favour trying to familiarize yourself with it.
from :h diff
3. Jumping to diffs                 *jumpto-diffs*

Two commands can be used to jump to diffs:
                                *[c*
    [c      Jump backwards to the previous start of a change.
            When a count is used, do it that many times.
                                *]c*
    ]c      Jump forwards to the next start of a change.
            When a count is used, do it that many times.


text:
Q: SQL bit is false I'm having an issue which I've been trying to solve for the past hour, and I can't seem to work it out. I've tried Googling for an answer, but haven't found one that works in my case, or at least I haven't been able to get it working.
Here's my code:
@foreach (var row in db.Query("SELECT * FROM PersonnelFiles WHERE (Badge LIKE '#1003' OR Badge LIKE '#1004' OR Badge LIKE '#1005' AND Archived is not true) ORDER BY Badge ASC"))
{

@row.Rank - @row.Name, @row.Badge

}

So according to my knowledge which is limited, it should now return all entries where badge is like "#1003", "#1004" or "#1005", provided that these are not Archived.
But when trying to do this, it gives me an error: "Incorrect syntax near false".
I hope you can help me, thank you in advance.
EDIT:
Archived is a bit datatype.

A: SELECT *
FROM PersonnelFiles
WHERE (
         Badge LIKE '#1003' OR
         Badge LIKE '#1004' OR
         Badge LIKE '#1005' AND
         Archived AND Archived <> 1
       ) ORDER BY Badge ASC

is the same as
 SELECT *
    FROM PersonnelFiles
    WHERE (
             (Badge LIKE '#1003') OR
             (Badge LIKE '#1004') OR
             (Badge LIKE '#1005' AND Archived <> 1)
           ) ORDER BY Badge ASC

What i supose you mean is
 SELECT *
        FROM PersonnelFiles
        WHERE
                 (
                    Badge LIKE '#1003' OR
                    Badge LIKE '#1004' OR
                    Badge LIKE '#1005'
                 ) AND Archived <> 1
                ORDER BY Badge ASC

se SQL Logic Operator Precedence: And and Or

A: try this:
there is nothing like false in SQL SERVER Bit has 1 or 0 values
@foreach (var row in db.Query("SELECT * FROM PersonnelFiles WHERE
    (Badge LIKE '#1003' OR Badge LIKE '#1004' OR
    Badge LIKE '#1005' AND Archived <>1) ORDER BY Badge ASC"))
{

@row.Rank - @row.Name, @row.Badge

}

SQL SERVER DataTypes


text: Q: Add page via API I run a little lektor blog and want to add a number of pages that I created using a python script. However, after copying the created content folders with their resp. content.lr files into my blog folder, those new pages do not show. Is there an API way of adding pages? Or do I have to use the admin UI to add a page? Didn't found anything in the docs so far.


text:
Q: How to add Entity Framework Geolocation property in Design Database model How can I make an Database Model edmx file that would let me add GeoLocation column to it from design database that would let me generate / reverse engeneering from database.
This one implies that I would modify it by hand.
Do I need to install a plugin for visual studio ? Do I need to find an open source entity generation tool that would help me?
p.s. i am using thisADO.net Poco Generator
I use SQL server 2008 and .net framework 4.0

p.s. 2 What about this reference

p.s. 3 Here on MSDN are some facts about not supporting this feature http://social.msdn.microsoft.com/Forums/en-AU/sqlspatial/thread/34866400-91e5-4af5-9fee-f7f369aa6a61

A: As far as I now the geolocation support in the Entity Framework will be released with .NET 4.5, so until then you will have to do it manually.
The second reference you provide should help you out. What the author describes is a way to store the data in the database, make sure it stays up to date with some triggers and then in the partial class in your code define a property that will convert the data field from your database to actual LatLong data.


text:
Q: How to avoid ltablex from splitting a table? I'm using the ltablex package because I have some large tables which have to splitted on multiple pages. But I have much more small tables (with tabularx), which don't need to be splitted. But they where splitted :/
How can I avoid that for explicit tables?
I inserted these tables with:
\begin{tabularx}{\textwidth}{lcX}

So I added no floating position tag, like !h or t or something else. I tried it with these, but no change. Only with the float-package and the option H they where not splitted, but then they are on the explicit position in text, what I don't want.

A: The fact that ltablex affects all tabularx is not the best feature of the package, you could instead use ltxtable package but anyway with ltablex as with normal tabularx if you want the tabke to float it must be inside a table environment, and once inside such an environment it will not split as table makes a box. You can not add float options such as [h] to tabular or tabularx.


text:
Q: Get all elements inside a specific node I'm new to XML parsing and I'm lost. First, here's my XML:
<?xml version="1.0" encoding="UTF-8"?>
<menu>
    <data>
        <food type="none">
            <price>100</price>
        </food>
        <food type="none">
            <price>50</price>
        </food>
    </data>

    <trash>
        <food type="none" id="1"/>
        <food type="none" id="2"/>
    </trash>
</menu>

I'm trying to parse this XML. I want to get all food items inside data.
When I do:
NodeList nUsines = doc.getElementsByTagName("food");

I also get the food items in trash, but I don't want this.
And sorry if my questions sounds off, I don't know the proper terms for XML
My code so far (inside a method):
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file.getPath());
    doc.getDocumentElement().normalize();

    NodeList nUsines = doc.getElementsByTagName("food");

Thank you

A: Your code has done exactly what you asked it to.
You want a more specific query, such as food elements within the data element.
You could try to select the data element, then query for food elements specifically within that.
Alternatively, look up XPath, and you'll quickly find another way to do this.

A: Using XPath (just one of the options):
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//data/food");

System.out.println(((NodeList)expr.evaluate(doc, XPathConstants.NODESET)).getLength());


text:
Q: Number of different vectors. Let's say that I have a vector with 6 elements. I put two wedges in the vector, i.e., at position 2 and position 6, for instance. And when I say put a wedge, it means... for every time you traverse (Forwards or backwards, only two positions) that position all the positions will be updated with that value. At the risk of sounding insane, let me explain this with an example:

x 2 x x x x 6

How many different ways would there be to so that the vector gets a different value? In this case, there would be 4:
** 2 2 2 2 2 6
** 2 2 2 2 6 6
** 2 2 2 6 6 6
** 2 2 6 6 6 6
How do I generalize this for a vector with say 1000 elements, and more than half the number of wedges?

A: Assuming each pair of consecutive wedges take different values, there must be exactly one change in value somewhere between any two wedges. You can make the change where you want, by walking to the later wedge, then walking back as far as you want before continuing to the next.


text:
Q: Is multi-threading or asyncio suitable for receiving real time tick with API requests and at the same time perform other tasks I have python function which receives and store live tick data from a server(By API requestes). And another function which fetch the data to candle bars of 1minute and appends it to pandas Data frame. Then i want to call another function which apply some mathematical computations and manages order execution in live market.
But i am confused in which method to use between Multi-threading, Multi-processing or AsyncIO. What i want is uninterrupted flow of tick data which receives data in fractions of milliseconds to my system so that i donot miss any realtime data, And at the same time able to manage orders and perform mathematical computations.
Please advise me which option will be better to choose from the above?

A: I think you should use multi-threading and/or asyncIO since getting processes to work together can be a pain in the neck. Since you need to do computations, you should store the data/use a queue and use a second process to make the calculations,and you can add more math processes if one couldn't catch up with data inflow.
On second thought. You'll still have to carefully pack data fast enough so you don't spend most of your time transferring the data(pickle or process Queues don't work 'cause they're too slow)you'll need some custom way, say structs to quickly pack and unpack the data.
But at that point, you might as well use C/C++ as your second(math processing) process :)
TL;DR: Use ansycio and/or threading to receive data, custom structs to quickly pack/unpack data, and a few other Python/C/C++ etc. processes to retrieve and process the data.


text:
Q: Conditional Binding in SPARQL/CONSTRUCT I have a SPARQL CONSTRUCT that works like this:
CONSTRUCT {
  ?uri rdfs:label ?label;
       foo:has-value ?v.
}
WHERE {
  ?uri
     rdfs:label ?label;
     foo:has-flag ?f.

  BIND ( IF ( ?f = 0, "Value for Zero", IF ( ?f = 1, "Value for One", '' ) ) AS ?v )
}

The problem is that when ?f is neither 0 nor 1 (but still has some value) I don't want the has-value statement at all. With the syntax above, I get ?uri has-value ''. It would work, if I could assign some sort of "null" to ?v, or avoid the binding, but I cannot find anything like that in the specs.
Any solution?
EDIT: The solution by Scott works for common graph-based queries. The case I came from involves the use of VALUES, is more complicated and I couldn't find a solution so far.
EDIT/2: the error-triggering solution, suggested by Andy in the Jena mailing list, works fine! Another approach, which I find more readable, is binding an unbound variable when we want to skip the original value.

A: Given feedback in the comments, here is a solution based on OPTIONAL that should meet all of the criteria:
CONSTRUCT {
  ?uri rdfs:label ?label;
       foo:has-value ?v.
}
WHERE {
  ?uri rdfs:label ?label .
  ?uri foo:has-flag ?f.
  OPTIONAL { FILTER (?f = 0)
      BIND("Value for Zero" AS ?v)
  }
  OPTIONAL { FILTER (?f = 1)
      BIND("Value for One" AS ?v)
  }
}

As pointed out, this previous solution will not cover the case where there is  label, but ?f is not 0 or 1:
CONSTRUCT {
  ?uri rdfs:label ?label;
       foo:has-value ?v.
}
WHERE {
  ?uri
     rdfs:label ?label;
     foo:has-flag ?f.
  FILTER (?f = 0 || ?f = 1)
  BIND ( IF ( ?f = 0, "Value for Zero", IF ( ?f = 1, "Value for One", '' ) ) AS ?v )
}

A: A bit hacky but should work with creating a blank node and then filter out those:
CONSTRUCT {
  ?uri rdfs:label ?label;
       foo:has-value ?v.
}
WHERE {
  ?uri rdfs:label ?label .
  OPTIONAL {
    ?uri foo:has-flag ?f.

    BIND ( IF ( ?f = 0, "Value for Zero",
             IF ( ?f = 1, "Value for One", BNODE() )
         ) AS ?v )
    FILTER(!ISBLANK(?v))
  }
}


text:
Q: Problem with NIntegrate over a user-defined region I define a region as follows:
In[259]:= \[ScriptCapitalR] =
  Polygon[{{0, 0}, {Re[gam2], Im[gam2]}, {gam1 + Re[gam2],
     Im[gam2]}, {gam1, 0}}] ;
Graphics[\[ScriptCapitalR]]

According to http://reference.wolfram.com/language/ref/NIntegrate.html, I should be able to integrate over this region simply as follows:
NIntegrate[x^2 *y^2, {x, y} \[Element] \[ScriptCapitalR]]

But I keep getting this error:
NIntegrate::vars: Integration range specification {x,y}\[Element]\[ScriptCapitalR] is not of the form {x, xmin, ..., xmax}. >>

Why is that?

A: Works for me:
gam1 = 2; gam2 = 1 - 2 I;
ℛ = Polygon[{{0, 0}, {Re[gam2], Im[gam2]}, {gam1 + Re[gam2],
    Im[gam2]}, {gam1, 0}}];

NIntegrate[x^2*y^2, {x, y} ∈ ℛ]
(*
  18.3111
*)


text:
Q: Why do some early modern English writers use an apostrophe in art (ar't)? For example, in Verses upon the duke of Buckinghams returne from the Ile of Rees (https://www.english.cam.ac.uk/ceres/ehoc/lessons/lesson1/index.html) the poet spells "art" as "ar't" in the phrase "And ar't return'd again with all thy faults..."
What is that apostrophe eliding?
Addition: I see that the OED shows "art" as the second person singular (archaic) of the verb "to be", with a citation "1535   Bible (Coverdale) Psalms cxxvii. 2   O well is the, happie art thou." So there is a use with the following "thou", so "ar't" can't be a contraction of "are thou".
My thoughts are converging on the apostrophe being a mistake (much like so many people now use apostrophes in plurals - "Pad's available") caused by the writer thinking that "art" is a contraction of "art thou". Shakespeare uses "Art cold?",
"art mad?" in King Lear without the apostrophe (ref First Folio), but later writers quoting King Lear insert the apostrophe for some reason (cf Wells, Poetic Imagery, 1924).

A: If the apostrophe in "ar't" is simply an error by the author, it is not the only one on this page. For example, I note three occurrences of the word "did[']st"—two without an apostrophe (didst) and one with an apostrophe (did'st). The presence or absence of the apostrophe in the case of didst is arguably acceptable either way—since didst could be read as a contracted form of "didest [thou]"—presumably the ancestral form from which didst sprang. Nevertheless, the lack of consistency in the writer's handling of didst on this page raises the possibility that he viewed apostrophes as something closer to optional ornaments than to necessary elements.
Less immediately explicable than the inconsistent treatment of didst and did'st is the word hope't in line 12 of the poem:

Or didst thou hasten headlong to prevent
A fruitlesse hope't for needfull parliament?

In modern U.S. English, an editor would probably render that second line as follows:

A fruitless, hoped-for, needful Parliament?

—so it isn't as though the apostrophe in hope't signals the loss of, say, an s from hopest. If anything, hopet is a letter too long to begin with: after all, writers  generally see no reason to add an e (or an apostrophe) before the t in burnt or learnt or spoilt or spilt. (Admittedly, none of those root verbs ends with an e.) The case would be different if the word in the line had been hop'd—since that spelling clearly involves the loss of an e.
However, in a comment beneath this answer, Peter Shor points out that the spelling "hope't" helps the writer avoid a misreading of hopt or hop't as short forms of hopped, as well as to signal to readers that the word is not to be read as having two syllables (as they might if he had simply rendered the word as "hopet." As for the writer's wish to avoid "hop'd" (aside from the fact that it, too, might, be misread as a short form of "hopped"), he seems scrupulous in distinguishing between past-tense verbs and verblike adjectives ending in a "d" sound ("return'd," "distempered," "gorg'd," "wrong'd" "bespotted," "tortur'd," compos'd," "oppressed") from those ending in a "t" sound ("hope't," "vex't").
(Speaking of orthographic anomalies, in line 17, the writer renders "there's" as "their's":

But their's a reason worse, then this, they say

—an unusual spelling to choose for a common word, although far more forgivable in 1630 than it would be today. Interchangeable use of then for than, on the other hand, seems to have been quite common in the seventeenth and eighteenth centuries.)
Returning to the line that the poster is primarily interested in:

And ar't return'd againe wth all thy faults

one might argue that "ar't" is doing duty for two words—"art thou." However, "art" alone could have accomplished the same thing, since "art" implies "art thou," just as "dost" (as used in this poem) implies "dost thou." It seems extremely unlikely that the writer chose the spelling "ar't" because he wanted to create a contraction of the form "ar[t]'t[hou]."  I can't think of any similar use of an apostrophe to create a contraction that begins at the front of one word and ends at the front of a second word.
I consider it far more likely that the writer simply stuck the apostrophe in "ar't" on an unconsidered or ill-considered whim, without any sense that it was marking the loss of one or more letters from one or two contracted words. If you had access to more than this single page of the manuscript, you could check to see whether the writer consistently uses "ar't" for "art thou," or whether this is simply a variant form that slipped in (like "did'st" in line 9).
My guess is that the writer usually rendered the word as "art" with no apostrophe, but that on this occasion his pen or his wandering thoughts led him to a different orthographic choice. I strongly doubt, in any case, that his use of the form "ar't" was intended to adhere to some established rule of punctuation that prevailed in 1630—because I don't think that any such convention with regard to "ar[']t" existed.
Neevertheless, it is quite possible that the writer views the apostrophe as having a far wider range of uses than the modern big three of elision/contraction, possession, and pluralization. The example of "hope't" in this page indicates that the writer may use the apostrophe to indicate a pronunciation shortened from two syllables to one—and perhaps he also considers it useful for other obscure or idiosyncratic purposes, such as to distinguish "art" used in one basic sense of the word from another.


text:
Q: How to remove special character  character in a file in unix? Below is the data in my file:
one_1.10=to - Standard (£1.10)
ITV_1.10=to - Standard (£1.10)

I want to remove  in my file in unix?
i tried below methods. Opened the file in vi mode  and gave below commands
:set nobomb
:wq

sed -i '1 s/^\xef\xbb\xbf//' <fileName>

But the BOM character is not getting removed. Could someone please help?

A: Try:
cat <filename> | sed 's/\xc2//g'

You had the right idea, but the wrong character (based on your example).


text:
Q: Jquery PrettyPhoto Submit button I am using a Jquery lightbox solution called Pretty Photo. I am opening up a form in the light box and having the user click the submit button that sends an email. When the button is clicked, I receive the email fine, but there is no information in it. Can someone please help?My code is below for the ASPX and ASPX.CS
LandingPage.ASPX.CS
     public partial class LandingPage : WebBasePage
{

      protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        //Create the msg object to be sent
        MailMessage msg = new MailMessage();
        //Add your email address to the recipients
        msg.To.Add("vdecapite@associatedestates.com");
        //Configure the address we are sending the mail from
        MailAddress address = new MailAddress("vdecapite@associatedestates.com");
        msg.From = address;
        //Append their name in the beginning of the subject
        msg.Subject = txtName.Text + " :  " + ddlSubject.Text;
        msg.Body = txtMessage.Text + " : " + txtName.Text;

        //Configure an SmtpClient to send the mail.
        SmtpClient client = new SmtpClient("smtp.aecrealty.com");
        client.EnableSsl = false; //only enable this if your provider requires it
        //Setup credentials to login to our sender email address ("UserName", "Password")
        NetworkCredential credentials = new NetworkCredential("vdecapite@associatedestates.com", "Vpdc05141989");
        client.Credentials = credentials;

        //Send the msg
        client.Send(msg);

        //Display some feedback to the user to let them know it was sent
        lblResult.Text = "Your message was sent!";

        //Clear the form
        txtName.Text = "";
        txtMessage.Text = "";
    }
    catch
    {
        //If the message failed at some point, let the user know
        lblResult.Text = "Your message failed to send, please try again.";
    }
}
    }

            }

LandingPage.ASPX
 TEST

                Name:

                <asp:TextBox ID="txtName"
                                runat="server"
                                Columns="50"></asp:TextBox>

                Subject:

                <asp:DropDownList ID="ddlSubject" runat="server">
                    <asp:ListItem>Ask a question</asp:ListItem>
                    <asp:ListItem>Report a bug</asp:ListItem>
                    <asp:ListItem>Customer support ticket</asp:ListItem>
                    <asp:ListItem>Other</asp:ListItem>
                </asp:DropDownList>

                Message:

                <asp:TextBox ID="txtMessage"
                                runat="server"
                                Columns="40"
                                Rows="6"
                                TextMode="MultiLine"></asp:TextBox>

                <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                    onclick="btnSubmit_Click" UseSubmitBehavior="false"/>

                <asp:Label ID="lblResult" runat="server"></asp:Label>

A: Does jquery lightbox add a form tag around the content? If it does, you will have nested forms i.e. form inside of a form. Nested forms are not html complaint and will behave funny. So make sure that you don't have nested form tag.
Hope this helps


text:
Q: "YSOD" Stack Trace Shown in Synchronous Event Receivers, instead of SharePoint Custom Error Page Original Title:

<nativehr>0x81020089</nativehr> in ItemUpdating (i.e. Synchronous)
  Event Receiver

Edited Question:
In the past when you created an item-based, synchronous event receiver that canceled the event and showed the user a message, you received custom SharePoint error page displaying your message. This is no longer the case and to achieve this behavior, which was the default in the past, you need to modify the Web.config as described below. Other than modifying the Web.config is there any method to display the custom error message to users as was done in the past?

Original Question and Additional Details:
I am receiving the above error in a "yellow screen of death" ASP.NET error page in an ItemUpdating event receiver where I have done the typical:
properties.Status = SPEventReceiverStatus.CancelWithError;
//It does not matter if I use Cancel or CancelWithError
properties.ErrorMessage = "You must be a member of the " + MarketNeedGroups.EngineeringManagers + " group to modify the " + field + " field";
properties.Cancel = true;

Some people seemed to think that it was due to the CustomErrors being set to "off" but that was clearly not the issue I was having as that was set to RemoteOnly on my dev box.
Another person suggested changing
<SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">

to CallStack="false" which I did and it corrected the issue. The amount of crazy answers I saw from people who clearly had no idea what was going on, however, lead me to question this as the best choice. Are there any other possibilities to correct this?
Edit:
I went back and checked some old code that has been in production for the better part of a year now. In said code I perform the same cancel but in an ItemDeleting Event Receiver. If you see this article on MSDN you will notice that it should present the user with a much less scary custom SharePoint error message. In the past my ItemDeleting event receiver displayed the same style of custom error message. It no longer does this. It now presents the user with a the YSOD. I verified the settings of the Web.config from a backup dated from over a year ago and CallStack="true" was exactly the same.
I don't want to modify this setting if I don't have to, but since the chances of me figuring out what has changed are zero, I will just keep this setting in the Web.config set to false. I certainly do not want my users to see the YSOD page as this will generate helpdesk tickets because users will not actually read the message, they will just assume that there was some sort of error in code. There is even discussion of this issue in the MSDN article above in the comments section.
In the Asynch events the error page still seems to be displayed properly. Meaning this exact code does not generate a YSOD but displays the custom SharePoint error.

A: I am afraid, modifying the web.config is the only way here.
Also, apart from changing the CallStack = "false", you should also set the <customErrors mode="On" />. Here is the relevant part of your web.config showing the changes:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <configuration>
        ...
        <SharePoint>
            <SafeMode MaxControls="200"
                CallStack="false"
                DirectFileDependencies="10"
                TotalFileDependencies="50"
                AllowPageLevelTrace="false">
                ...
            </SafeMode>
        ...
        </SharePoint>
        <system.web>
            ...
            <customErrors mode="On" />
            ...
        </system.web>
        ...
    </configuration>

A: The SPEventReceiverStatus enumeration now has a CancelWithRedirectUrl. If I understand correctly you want to show an errormessage to the user that informs why the action was cancelled. For an example see: http://msdn.microsoft.com/en-us/sp2010devtrainingcourse_listsandschemalab_topic4.aspx.
I hope this helps.


text:
Q: Undesired Ctrl+V behaviour in TeXstudio I encounter this fairly frequently:
I copy some text, then select the location at which I want to paste it, and hit crtl +v. Instead of copying the text, Texstudio loads the manual of a (seemingly) random package, then searches for the selected text in this manual (it loads the manual in the onboard pdf viewer).
This is very frustrating as some package manuals are large and it takes Texstudio some time to load them.
Does anybody have any idea why this is happening? I initially thought it was because I had made the pdf viewer the active window, but that can't be the case as I have just selected and copied some text, then selected the paste location.


text:
Q: Load GLTF model from text I'm currently loading a GLTF file from a file served by a static file server.
  import * as THREE from 'three'
  import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

  var loader = new GLTFLoader();

  loader.load(
    'http://localhost:1234/Assembly_PROD.gltf',
    function (gltf) {
      // Do stuff with loaded model
    },
    function (xhr) {
      // process progress
    },
    function (err) {
      // process error..
    }
  );

I'm now moving to an API server that provides GLTF files directly as text.
How can I load a GLTF file directly from its contents (and not through a file url) ?

A: The three.js editor allows to drag&drop glTF files. It uses the File API to read the file contents and then directly calls GLTFLoader.parse() with the respective data.
reader.addEventListener( 'load', function ( event ) {

    var contents = event.target.result;

    var loader = new GLTFLoader();
    loader.parse( contents, '', function ( result ) {

            var scene = result.scene;

            // more code

    } );

}, false );
reader.readAsArrayBuffer( file );

When studying the code, you can see that an instance of ArrayBuffer is passed into GLTFLoader.parse(). However, this method also accepts string data.
three.js R113


text:
Q: No ClassTag available compilation error The compiler keeps producing the following errors:
No ClassTag available for a
  val keys = Array.fill(maxSize+1){ default[a] }
                                  ^
not enough arguments for method fill: (implicit evidence$9: scala.reflect.ClassTag[a])Array[a].
Unspecified value parameter evidence$9.
  val keys = Array.fill(maxSize+1){ default[a] }
                                  ^

for this piece of code
object Utils {
  def default[a] = {
    class DefaultVal {
      var x: a = _
    }
    (new DefaultVal).x
  }
}

class IndexedHeap[a](maxSize: Int)(implicit ev: Ordering[a]) {
  import ev._
  import Utils._

  val keys = Array.fill(maxSize+1){ default[a] }

}

Any ideas on how to fix this?

A: I think adding ClassTag would fix it, like this:
[a:ClassTag]

edit based on your comment on the conflict with implicit params and context bounds:
Change the implicit parameters to include the ClassTag too
implicit ev: Ordering[a], ct: ClassTag[a]