text:
Q: Web service Excel conversion I have ASP.NET web service, which is creating file in XML table format.
I need to convert this file into Excel 2003 format.
What can I use instead of Microsoft.Interop library?
UPDATE: I also need to copy format from the original file.

A: you can read the data from xml using linq and then insert it on the run using linq to excel with the dll provided in the post above.
also take a look at this article i hope it helps
http://blogs.msdn.com/b/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx

A: Have you tried OpenXML? Here is an example
With Office 2007
Look here for Cell Formatting

A: I use ExcelLibrary
I think it's a very easy to use tool.
you can transform an XML string to an excel file in one method.
I also heared about NPOI, maybe give it a look also.

A: I've found the answer by myself.
I could not use different libraries, because I had to open file in XML Table format and resave it to Excel 2003 format.
Maybe my experience in this question will help someone. I used Windows Server 2008 with IIS 7.0 and Excel Library Microsoft.Office.Interop.Excel version 12.
Microsoft says, that using Interop DLL may cause unpredictable result, but it's NOT impossible.
The main problem of using Interop classes lies into access to launch DCOM applications by user, that starts web-service.
To make web-service works correct in my way I did next:

*

*I opened "dcomcnfg" and disable authorization for all DCOM
components.
Another way is to find exactly your DCOM objects and give
permissions to local launch to the user, that starts the service.

*Gave permissions to registry branch
HKEY_CLASSES_ROOT\CLSID\ID_OF_MICROSOFT_APPLICATION_CLASS
ID_OF_MICROSOFT_APPLICATION_CLASS = class, which contained in
web-server error while accessing to Interop DLL

*It's very strange, but important: I created folder
for 86x: C:\Windows\System32\config\systemprofile\Desktop
for 64x: C:\Windows\SysWOW64\config\systemprofile\Desktop

*Gave write permission to web-service user to all folders, which my
web-service use, including folder from item (3).

If your web-service works under NETWORK SERVICE try to change it to some local user, maybe it may help you.


text: Q: How to bundle node js and express js for production? I am working on a project which run node express server and using Angular as frontend. I have build Angular project and placed files in public folder for node folder. I want to bundle express and node code for production where node code cannot be modified and easily understand. Can some one help me how can i bundle the node server?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing directly to a Zebra/Swecoin TTP2030 receipt printer in Ubuntu I have a Swecoin/Zebra TTP2030 USB-LPT receipt printer that I am using on Ubuntu.  I'd like to use it like a normal printer, which Zebra says is possible under Windows.  Anyone know anyway to do this under Ubuntu?  I've tried a few printer drivers, and I just get reams and reams of the printer code printed out.  Anyone have any insight on getting this thing running like a normal printer?
I already have it communicating via the ttputil: http://www.rainbow-software.org/linux/

A: Ok, I found it, and the good news is that these printers have been added to CUPS 1.5, so it should "just work" on new systems.  But I'm on Ubuntu/lucid, so I did it like this:

*

*downloaded zebraCupsDrivers_v2.zip from http://www.cups.org/str.php?L3767

*installed via gnome system-config-printer-applet

*used ttp20x0.ppd in ppd/ from zebraCupsDrivers_v2.zip

*built rastertozebrakiosk in filters from zebraCupsDrivers_v2.zip by doing:

*

*apt-get install libcups2-dev libcupsimage2-dev

*gcc -o rastertozebrakiosk rastertozebrakiosk.c -lcups -lcupsimage

*cp rastertozebrakiosk /usr/lib/cups/filter/

A: If you can get the device added, you should be able to print from the command line.
$ lpr file.prn

You'll need to create an output file using the printer's native code.


text:
Q: How can I fix my python word descrambler? QUESTION: Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
MY CODE:
s1 = 'rkqodlw'
s2 = 'world'

def scramble(s1, s2):
    unscrambled_word = []
    n = 0
    x = 0
    s1_list = list(s1)
    s2_list = list(s2)
    s1_letter = s1_list[n]
    s2_letter = s2_list[x]
    for letters in range(len(s2_list)):
        while n > len(s1_list):
            if s1_letter == s2_letter:
                n = n + 1
                x = x + 1
            else:
                n = n + 1
    return 'True' if x == len(s2_list) else 'False'

I am trying to get my code to dissect each of the two strings. If the word of the first string does not match the word of the second string then n will +1 and move onto the second letter. If it matches then both n and x will + 1. My thought on my code is if x == the length of the second string before the giant loop ends then it will return True. Otherwise False. The problem is with the loop. The loop only seems to run through the first two letters of both strings and then stops. I am a fairly new coder any input is greatly appreciated! Thanks!

A: You just need to make sure the letters in str2 are all present in str1 in sufficient quantities
def scramble(str1,str2):
    d1 = {}
    for c in str1:
        if not c in d1:
           d1[c] = 0
        d1[c] += 1
    for c in str2:
        if not c in d1 or d1[c] < 1:
            return False
        d1[c] -= 1
    return True

The ideas is to go through all the characters in str2 and if for example, str2 has three "a" letters, make sure that str1 has at least three "a" letters. This requires counting the number of times each character occurs in str1. This is most naturally done with a dictionary. A dictionary maps things, called keys, to other things, called values. In this case we map keys which are single characters to a values which are numeric counts.
First step is to create an empty dictionary d1={}.
Next is to go character by character in str1 which is the first for loop. For each of these characters, we ask if this character has ever been previously placed into d1. If it has not, then we create a new mapping within d1 for that character to a starting value of zero. Every time a character is encountered in this loop through str1, the count value mapped from that character in d1 is incremented by 1. After the first for loop (that goes through str1) is complete, the dictionary contains counts of every letter in str1.
The next idea is to iterate through every character in str2. If it is a character not present in d1, then that means the character was not present in str1, so str1 is missing a character it would need to scramble into str2. At that point, you can stop processing and just return False.
Otherwise, if you only encounter characters that exist as keys in d1, you subtract one from the d1 mapped count value every time you encounter that character while for looping through str2. If the subtraction would ever cause the d1 count value to go below zero, then that means str2 has a higher number of that particular character than str1 had, so once again str1 cannot scramble into str2. Therefore you can return False at that point and stop processing.
Finally, if we make it through the entire 2nd loop (through str2) without encountering either of the return False cases mentioned above, that means that str1 has at least as many of every character that str2 has and can therefore scramble into str2 using some of its letters. You then return True.

A: from collections import defaultdict
s1 = 'rkqodlw'
s2 = 'world'

def scramble(s, t):
    d=defaultdict(int)
    for c in s:
        d[c]+=1
    for c in t:
        d[c]-=1
    return min(d.values())>=0
scramble(s1,s2)

alternatively use Counter
from collections import Counter
s1 = 'rkqodlw'
s2 = 'world'

def scramble(s, t):
    c=Counter(s)
    c.subtract(Counter(t))
    return min(c.values())>=0
scramble(s1,s2)

A: Alternative:
s1 = 'rkqodlw'
s2 = 'world'

def scramble(s1, s2):
  s1_list = list(s1)
  for char in s2:
    if char in s1_list:
      s1_list.pop(s1_list.index(char))
    else:
      return False
  return True

print(scramble(s1,s2))

Here's how it works: You run through the loop for each letter in s2, and if that letter is also in a list version of s1, you delete it from that list version. That way, if s2 was 'rabbit' for example, and s1 was 'braintrain', you would meet the first 'r', 'a', and the first 'b', delete it from 'braintrain' to get 'intrain', and the next 'b'would then fail the test and a False would be returned. If there were enough 'b's though, the scrambler would return True. The final Trueis returned if the test is never failed (that is, all letters in s2 are also in s1) when the function finishes.

A: Updated version:
s1 = scrambled word that may contain s2
s2 = word to be searched
Step 1. Find the set of s2
Step 2. Iterate through each letter of set of s2. Let's call each letter as s
Step 3. For each letter s, find out how many times it occurs in s1 and s2
Step 4: If letter count in s2 <= letter count in s1, then OK, else exit and return False
Step 5: If all letters in set of s2 meet the condition of Step 4, then s2 is in s1. You can return True
The code for this is:
def scramble_check(s1,s2):
    return True if all(s2.count(s) <= s1.count(s) for s in set(s2)) else False

print (scramble_check('rkqodlw', 'world'))
print (scramble_check('moonshine', 'moon'))
print (scramble_check('strain', 'brain'))
print (scramble_check('aaaappppleeeset', 'apple'))
print (scramble_check('braintrain', 'rabbit'))

Output of the above code is:
True
True
False
True
False

Jace, to make you understand that one line of code, I expanded the function. Here's the more expanded version.
def scramble_check(s1,s2):
    ss = set(s2)  #create a set from word s2

    for s in ss: #iterate through each letter in set ss

        #compare count of occurrences of s in both s1 and s2
        #if s2 count is more than s1, then the word cannot be made with s1
        #so return False and exit the function
        if s2.count(s) > s1.count(s): return False

    #if we iterated through all of ss and each letter met the condition, then s2 can be created using s1. So return True
    return True

All this is a single line:
return True if all(s2.count(s) <= s1.count(s) for s in set(s2)) else


text:
Q: gzip compression on AWS How can we enable gzip compression on AWS using a docker file for react js application?
We want to enable GZIP compression for artifacts flowing from Server to a browser.
In IIS we have used such a setting. But we are not aware of how to set this in Docker file in react js.

A: You need to use some sort of server to enable gzip, like in your earlier case you used IIS, mostly I use Nginx to enable gzip, you can do from Nginx config,
but for that, you have to use Nginx base Image to server Reactjs app.
Here is DockerFile for nginx
FROM node:10.15-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN yarn
COPY ./ .

RUN yarn run build_prod

FROM nginx:1.17.6-alpine

RUN apk add --update --no-cache \
bash \
curl

#config nginx and supervisord
COPY ConfigFiles/nginx.conf /etc/nginx/nginx.conf
COPY ConfigFiles/site.conf /etc/nginx/sites-available/default.conf

RUN mkdir -p mkdir -p /etc/nginx/sites-enabled && \
mkdir -p /run/nginx && \
mkdir -p /var/www/frontend && \
ln -s /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf

WORKDIR /var/www

#COPY dist ./frontend
COPY --from=build-stage /app/dist ./frontend

nginx.conf
user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile on;
    #tcp_nopush on;
    keepalive_timeout 65;
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types application/javascript application/rss+xml application/vnd.ms-fontobject application/x-font application/x-font-opentype application/x-font-otf application/x-font-truetype application/x-font-ttf application/x-javascript application/xhtml+xml application/xml font/opentype font/otf font/ttf image/svg+xml image/x-icon text/css text/javascript text/plain text/xml image/gif;
    include /etc/nginx/sites-enabled/*.conf;
    client_max_body_size 10M;
}

site.conf
server {
    listen 80;
    #server_name d;

    root /var/www/frontend;
    index index.html;

    location / {
            try_files $uri /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root /var/www/frontend;
    }

    location ~ /\.ht {
        deny all;
    }
}


text:
Q: Difference between obj-m+=[modules_list] and obj-m=[modules_list] What's a difference between obj-m=md1.o md2.o and obj-m+=md1.o md2.o in a kernel make-file?

A: You can try to infer it with an example:
obj-m= a.o b.o
obj-m1= 1 2 3
obj-m= c.o d.o
obj-m1+= 4 5 6

ALL :
    echo $(obj-m) -- $(obj-m1)

Its output is
c.o d.o -- 1 2 3 4 5 6

So: = assigns (overwriting), and += appends.


text:
Q: пройти по списку ul и сохранить значение li js Существует тег ul с рандомным количеством элементов li, в каждом li лежит input с checkbox-ом и со своим индивидуальным значением, нужно с помощью jQuery реализовать функцию которая проходя по всем li будет сохранять значения тех которые помечены галочкой и сохранить все значения в массив, подскажите пожалуйста.
Вот что нагуглил чтобы ходит по ul, значение выводит, а сохранять не получается...
  function create() {
      $('#checked input:checkbox:checked').each(function() {
          var ert = $(this).val();
          alert(ert);
      });
  }

A: Вам нужно создать массив и добавлять в него значения в виде объекта.
function create() {
  var arrCheck = [];
  $('#checked input:checkbox:checked').each(function(idx, item) {
    var ert = {
      val: $(this, item).val()
    };
    arrCheck.push(ert);
  });
  console.log(arrCheck);
}


text:
Q: Square root of a number to 100 decimal places How can I get the square root for a number to 100 decimal places in R?
I've looked into the gmp and the Rmpfr packages. I can't figure out how I would use them for square roots, (pow.bigz(2,0.5)=1)
but even if I did, I'm not sure how accurate it would be, since I've found that after about 25 decimal places, the digits aren't reliable
eg
mpfr(1/3,400)
# 1 'mpfr' number of precision  400   bits
# [1] 0.333333333333333314829616256247390992939472198486328125

and
as.bigz(1e50/3)
# Big Integer ('bigz') :
# [1] 33333333333333337607355566542238210608487100055552

A: The question is computing one third prior to mpfr so it has already lost precision by the time mpfr sees it.  Do it this way:
mpfr(1, 400)/3


text:
Q: ACF: How to query for a given value count of an array like field? (e.g.: How many rows has a `flexible_content` field?) How can I write a WordPress meta query that gives me an array of users/posts that have a given amount of entries in a custom field that stores multiple values?
Something like SQL COUNT(), but for the number of entries in an ACF array field.
When writing a WP_Meta_Query and comparing with >, >=, etc. this doesn't seem to work for me, perhaps because the data is stored serialized.
So, basically, how can I perform a simple selection of records with a specific count inside their custom field value.

A: This isn't possible using WP_Query, you can't query the insides of structured data stored in a single post meta value.
At best you can use regular expressions, or do math/boolean comparisons, you can even do LIKE comparisons, but these are all string operations.
If you need to query structured data such as objects or arrays, then the data needs breaking apart into multiple separate post meta values.
At the end of the day, post meta values are just strings of text as far as the database is concerned. You can cast them to a different basic data type such as a date or number, but that's it.


text:
Q: push tableview cell frame in cgrect to margin In my swift code below i wan the tableview cell to be pushed to the margins exactly like the cells left side. In the photo below you can see the margins of the tableview cell on the right side are a lot bigger than it its on the side of the left. Please make them equal.
pic of tableview
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
    var numberOfRows = 3

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numberOfRows }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 118
    }
    var btn = UIButton()
    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        setTableVIew()

    }

    func setTableVIew(){

        let VCframe = self.view.frame
        let height = VCframe.height * 0.8
        let widthx = VCframe.width

        tableView.frame = CGRect(x: 0, y: 0, width: widthx, height: height)

        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        tableView.backgroundColor = .blue

        tableView.register(customtv.self, forCellReuseIdentifier: "cell")
    }

}
class customtv: UITableViewCell {

   lazy var backView : UIView = {
    let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
    view.backgroundColor = .green
    print(self.frame.width)
        return view
    }()

    override func layoutSubviews() {
       backView.clipsToBounds = true

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(animated, animated: true)
        addSubview(backView)
    }
}

A: Update backView frame in layoutSubviews
class customtv: UITableViewCell {

   lazy var backView : UIView = {
    let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
    view.backgroundColor = .green
    print(self.frame.width)
        return view
    }()

    override func layoutSubviews() {
       backView.clipsToBounds = true
       backView.frame =  CGRect(x: 0, y: 6, width: bounds.maxX  , height: 110)

    }

they will become equall width cell ... if you want to give margin ... give it to your tableview instead of cell ...
tableView.frame = CGRect(x: 10, y: 0, width: widthx - 20, height: height)


text:
Q: Prompt width and height of image being uploaded I am looking for some method to prompt the width and height of the image being uploaded using an asp file upload control. Following is the code I am using to prompt message for file size. I just want to add the width and height of the image being uploaded using that upload control. Please take a note that I can't use javascript DOM here like img.clientWidth as there is no such html object to call it.
Here's the JS Code
$(document).ready(function () {
    $("#<%= fupNewImage.ClientID %>").bind("change", function () {
        var fSize = ((this.files[0].size) / 1024).toFixed(2);
        if (fSize <= 200) {
            $("#fupSize").html('Good file size: ' + fSize + " kb  Width=? and Height=?" ); // ? denotes the actual value to be put.
        }
        //---------More cases
    });
});

A: Solved!!
Thanks to  @Esailija
After a lot of searching I finally found a workout @ REF https://stackoverflow.com/a/8904008/1584140
var _URL = window.URL || window.webkitURL;
    $("#<%= fupNewImage.ClientID %>").bind("change", function () {
        //================Changed Code===================
        var file, img;
        if ((file = this.files[0])) {
            img = new Image();
            img.onload = function () {
                var fSize = ((file.size) / 1024).toFixed(2);
                var WH = " Widht: " + this.width + "px & Height: " + this.height + "px";

                if (fSize <= 200) {
                    $("#fupSize").html('Good file size: ' + fSize + " kb" + WH);
                }
            };
            img.onerror = function () {
                alert("not a valid file: " + file.type);
            };
            img.src = _URL.createObjectURL(file);
        }
        //====================================
    });
});


text:
Q: Extract uint8_t* subset from a vector I have a vector<uint8_t>, and I'm interfacing with an api that expects a uint8_t* data, size_t size. I need to provide the api with a subset of my vector, in my current solution I create a subset by using the vector constructor, and then I pass the data() of this new vector to the api:
vector<uint8_t> subset(bytes.begin() + offset, bytes.begin() + offset + size);
api(subset.data(), subset.size());

This works fine in the majority of cases, but it is running out of memory on constrained devices. Is there a more efficient way to extract a uint8_t* subset from a vector<uint8_t>?

A: Yes, just combine the two but with data instead of begin.
api(bytes.data() + offset, size);

Using subscript and address-of operators also works
api(&bytes[offset], size);

A: I Think you dont need to make a subset, pass vector's first element and size to want to take out of it. Make sure this size is less than equal to bytes.size()
api(&bytes[0],size);


text:
Q: Am I concentrating these character arrays incorrectly? I've been trying to create a midi file from scratch with c++. I'm separating different chunks(and parts of chunks) into different character arrays.
My code:
#include <iostream>
#include <fstream>
#include <cstring>

int main(int, char* []) {
    std::ofstream MIDIfile ("example.mid")
    char header[] = { /* hex data */ };
    char track_header[] = { /* hex data */ };
    char track_data[] = { /* hex data */ };
    MIDIfile << strcat(header, strcat(track_header, track_data));
    MIDIfile.close();
    return 0;
}

My only problem is that when the file is written, only 8 of the 81 bytes are written. Is there a reason for this? Am I doing something wrong?
Regards, shadowstalker75

A: You'll have to learn what strcat() does. This line is never going to work. Actually, even better, NEVER USE strcat(). It's crap.
MIDIfile << strcat(header, strcat(track_header, track_data));

You have binary buffers of hex data, just use the write() function:
MIDIfile.write(header, sizeof(header));
...

and write one buffer at a time.

A: The formatted operator<< function for char arrays or pointers is for printing null-terminated strings. If your "hex data" contains any zeroes (binary zeroes, 0, not the character '0') then that will act as the terminator.
That's not to mention the buffer overflows you have, since you append into a fixed-sized array which is specifically sized for the data you initialize it with.
The solution is first of all not to use arbitrary binary data as strings (the strcat function also expects the data to be null-terminated strings) but as raw data. Secondly you need to use the write function to write arbitrary data.


text:
Q: JITWatch Launching TriView for null I'm trying to run my own classes in JITWatch, however, I can only seem to get the prepackaged .java files in the sandbox/sources folder to work. Every time I run my own classes in the sandbox, I get the following in the console:
Parsing JIT log: C:\path\to\sandbox.log
Parsing complete
Looking up class: MyClassName
Launching TriView for null

The TriView window then opens up with nothing displayed.
I've tried sorting the issue by updating my JAVA_HOME env variable to Java 11, as JITWatch runs on Gradle 5.5.
The class I'm trying to get this working with is as follows:
public class MyClassName {
    public static void doIt() {
        for (int i = 0; i < 4; i++) {

            Thread th = new Thread(() -> {
                System.out.println("Hello");
                System.out.println("Hello again");
                System.out.println("Hello one last time");
            }, String.valueOf(i));
            th.start();
        }

    }

    public static void main(String[] args) {
        MyClassName.doIt();
    }

}

I feel as though I'm missing something small. Any suggestions, please let me know!

A: I can reproduce your issue, but this does not seem to be the fault of JITWatch, though, the log file simply does not include anything about MyClassName...
I have manually compile and ran the SimpleInliningTest, with that JITWatch shows output.
It seems your class is not touched by the JIT :)


text:
Q: How to set condition for div id I am trying to pass condition for id ? How to achieve the below condition
if ( $vm->check( "pagetype = cart" ) )
{
echo $ showRightcolumn? 'contentarea2' : 'newcontentarea';
}
else
echo $showRightColumn ? 'contentarea2' : 'contentarea';

in this statement
<div id="<?php echo $showRightColumn ? 'contentarea2' : 'contentarea'; ?>">

A: For any complex processing you could always create a function to return the ID that you want to return, and then echo the result of the function, something like:
<?php
  function getId($vm, $showRightColumn) {
    if ($vm->check("pagetype = cart")) {
      return $showRightcolumn ? 'contentarea2' : 'newcontentarea';
    }
    return $showRightColumn ? 'contentarea2' : 'contentarea';
  }
?>
<div id="<?php echo getId($vm, $showRightColumn); ?>">...

However, for simpler conditionals, it may just be better to use a ternary operator which evaluates other ternary statements (as suggested by other answers).

A: Try the following :
<div id="<?php echo $vm->check( "pagetype = cart" )
                    ? ($showRightColumn ? 'contentarea2' : 'newcontentarea')
                    : ($showRightColumn ? 'contentarea2' : 'contentarea') ;
         ?>"
>


text:
Q: seeing lot of CLOSE_WAIT with okhttp 3.81 seeing lot of CLOSE_WAIT connections on ubuntu when I execute the below command where 20919 is the pid of tomcat. Does lot of sockets in CLOSE_WAIT state cause high number of open files ?
sudo lsof -p 20919 | grep CLOSE_WAIT
below is the code to close the client requests
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(30, TimeUnit.SECONDS);
    builder.readTimeout(30, TimeUnit.SECONDS);
    builder.writeTimeout(30, TimeUnit.SECONDS);
    OkHttpClient client = builder.build();

    String webServiceEndPoint = url;
    Response response =null;
    if (!url.matches("^(http|https)://.*$")) {
        webServiceEndPoint = backendConfig.getWebServiceUri().concat(url);
    }

    Request request = new Request.Builder()
            .url(webServiceEndPoint)
            .method(method, getRequestBody(requestContext, method))
            .headers(buildHeaders(headerBuilder))
            .build();

    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            if (isJsonObject(responseBody)) {
                callback.onSuccess(JsonObjectBuilder.fromString(responseBody));
            } else if (isJsonArray(responseBody)) {
                callback.onSuccess(JsonObjectBuilder.arrayfromString(responseBody));
            } else {
               // logger.debug("couldn't determine response type [response : {}]", responseBody);
                callback.onSuccess(responseBody);
            }
        } else {
            callback.onError(responseBody, new SimpleStatusLine(response.code(), ""));
        }
        if(response!=null)response.body().close();
    } catch (Exception e) {
        callback.onFailure(e);
    }finally{
        LOG.debug("finally cleaning rsources");
        if(response!=null)response.body().close();
        client.connectionPool().evictAll();
    }

This does not seem to clean up the CLOSE_WAIT state. I am using tomcat 8 with Okhttp 3.8.1


text:
Q: Python TypeError: 'NoneType' object has no attribute '__getitem__' I'm not quite sure what's going on here. I'm trying to make it play a sound when the darkest part of the feed from my web-cam is in a particular location in the display. When I run it I get this error
File "/home/phur/Documents/052617/052617.py", line 42, in piano
    if par[100, 200] == surface.map_rgb((0, 0, 0)):
TypeError: 'NoneType' object has no attribute 'getitem'
(0, 0)
Here's my code:
import pygame
import pygame.camera
from pygame.locals import *
import time
import random
import Image

pygame.init()
pygame.camera.init()

size = (640, 480)

md = pygame.display.set_mode(size, 0)
pygame.display.set_caption("Piano")

def piano():

    stop_playing = False

    camera = pygame.camera.Camera('/dev/video0', size)
    camera.start()

    while not stop_playing:

        captured = camera.get_image(md)
        md.blit(captured, (0, 0))
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                stop_playing = True

        mp = pygame.mouse.get_pos()
        par = pygame.PixelArray.surface.__init__()

        print mp

        for x in range(0, 213):
            for y in range(0, 240):
                if par[x, y] == pygame.surface.map_rgb((0, 0, 0)):
                    pygame.mixer.music.load("C1.wav")
                    pygame.mixer.music.play()
                    time.sleep(1)
        for x in range(214, 426):
            for y in range(0, 240):
                if par[x, y] == pygame.surface.map_rgb((0, 0, 0)):
                    pygame.mixer.music.load("D1.wav")
                    pygame.mixer.music.play()
                    time.sleep(1)
        for x in range(427, 640):
            for y in range(0, 240):
                if par[x, y] == pygame.surface.map_rgb((0, 0, 0)):
                    pygame.mixer.music.load("E1.wav")
                    pygame.mixer.music.play()
                    time.sleep(1)
        for x in range(0, 320):
            for y in range(241, 480):
                if par[x, y] == pygame.surface.map_rgb((0, 0, 0)):
                    pygame.mixer.music.load("F1.wav")
                    pygame.mixer.music.play()
                    time.sleep(1)
        for x in range(321, 640):
            for y in range(241, 480):
                if par[x, y] == pygame.surface.map_rgb((0, 0, 0)):
                    pygame.mixer.music.load("G1.wav")
                    pygame.mixer.music.play()
                    time.sleep(1)

piano()
quit()

A: It looks like you aren't initializing your pygame.PixelArray correctly.
According to the pygame pixel array doc example. First, you should create a surface or screen for python to display.
size = (640, 480)
md = pygame.display.set_mode(size, 0)
surface = pygame.Surface(size)

Next, in your piano() function:
# create pixel array
par = pygame.PixelArray(surface)

In general, you shouldn't be using the double leading and double trailing underscores functions. In this case, your line par = pygame.PixelArray.surface.__init__() is suspect.
If you're curious here's a good explanation of why some functions have underscores in python


text:
Q: How to make GitKraken show topological order (rather than date order)...? GitKraken shows git trees using date order.
Is there a way to make GitKraken use topological order...?
I've looked at GitKraken's options/settings and I couldn't find anything that specified topo vs date, and I couldn't find anything addressing this online.


text:
Q: How to pass multiple dropdown values as URL parameters? I'm basically trying to create a form , with 2 dropdowns and pass the values from select as URL parameters through a from submit button ,

 <form action="">
 <select id="Select1">
         <option value="1">Tshirt</option>
         <option value="2">Hat</option>
         <option value="3">Sweater</option>
         <option value="4">Hoodie</option>
      </select>
      <select id="Select2">
         <option value="1">Red</option>
         <option value="2">Yellow</option>
         <option value="3">Pink</option>
      </select>
        <input type="submit" value="Submit">

</form>

*

*If none of the dropdowns are selected , the url should be : domain.com

*If the first value is selected , the url should be : domain.com/Tshirt

*Otherwise if both options are selected , the url should be : domain.com/Tshirt/Red

Thanks a lot !

A: Add click event listener on submit button and get text property of selected dropdown option.

const submitBtn = document.querySelector("#submitBtn");
submitBtn.addEventListener("click", () => {
  const select1 = document.querySelector("#Select1");
  const select2 = document.querySelector("#Select2");
  const val1 = select1.options[select1.selectedIndex].text ?? "";
  const val2 = select2.options[select2.selectedIndex].text ?? "";
  const url = `domain.com/${val1}/${val2}`;
  console.log(url);
})
<html>
<head></head>
<body>

 <select id="Select1">
         <option value="1">Tshirt</option>
         <option value="2">Hat</option>
         <option value="3">Sweater</option>
         <option value="4">Hoodie</option>
      </select>
      <select id="Select2">
         <option value="1">Red</option>
         <option value="2">Yellow</option>
         <option value="3">Pink</option>
      </select>
        <input id="submitBtn" type="submit" value="Submit">

</body>
</html>


text:
Q: I have a button and an icon inside a function can be lauched with. How can I drag the button without triggering the icon? If I touch the icon  and drag the button, then the functions triggered by the icon must not be launched. What must I do?
<div>
    <button type="button" class="fixed-button wobble" [style.background]="changeColorService.defaultStyles.firstDesignBackgroundColor" [appMovable]="true">
      <mat-icon [style.color]="changeColorService.defaultStyles.firstDesignFontColor" *ngIf="!(changeKagListIcon)" (click)="openKagListDialog()" matTooltip="KAG-Liste öffnen" [appMovable]="true">dvr</mat-icon>
      <mat-icon [style.color]="changeColorService.defaultStyles.firstDesignFontColor" *ngIf="changeKagListIcon" (click)="dialog.closeAll()" matTooltip="KAG-Liste schließen" [appMovable]="true">close</mat-icon>
    </button>

A: I am not quite sure what you mean, but consider to call event.stopPropagation().
    <button (click)="specialFnc()">
      <mat-icon (click)="$event.stopPropagation()"></mat-icon>
    </button>

If you click the icon the specialFnc won't get called. So if you like this behavior, for the drag event - just stop the event chain at the desired point.
I don't know which directive [appMovable] is, but within the drag handling you have to call stopPropagation.

A: Javascript event.stopPropagation() will help child event bubbling on Parent element Onclick events.
Example,
<button (onclick)="stopChildTrigger($event)">
   <mat-icon><mat-icon>
</button>

stopChildTrigger(e){
   e. stopPropagation();
}


text: Q: Transform the log scale into non-logarithmic scale in R I have created a linear model with logarithmically transformed y and x variables. Now i would like to plot the model but back transform the axis labels for better interpretation. How can i do this in R?


text:
Q: How to set AuthnContext in Azure AD B2C IDP Saml response I am involved in a project to build a new Azure AD B2C IDP and need to support some legacy Saml2 SPs.  These login requests include a RequestedAuthnContext element and require PasswordProtectedTransport, however the Saml response from B2C has an AuthnContextClassRef of unspecified in the assertion and therefore is being rejected by the SP.  So far I have been unable to find any information on how to set this from within a custom policy.  Is anyone able to confirm whether or not this is actually possible and if so what is involved?

A: •   Yes, you can configure the 'AuthContext.xml' or the 'LoginHandler.xml' file for the SAML response on the IdP side (Azure AD B2C if it is) with the authentication methods to be responded to the service provider (SP) with SAML 2.0 protocol. The authentication method set in the assertion for 'RequestedAuthnContext' should be as the following example SAML request: -
' <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_7171b0b2-19f2-4ba2-
      8f94-24b5e56b7f1e" IssueInstant="2014-01-30T16:18:35Z" Version="2.0"
        AssertionConsumerServiceIndex="0" >
     <saml:Issuer>urn:federation:MicrosoftOnline</saml:Issuer>
    <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:2.0:nameid-
      format:persistent"/>
    <samlp:RequestedAuthnContext Comparison="exact">
    <saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
</saml:AuthnContext>
 </samlp:RequestedAuthnContext>
  </samlp:AuthnRequest> '

•   Also, the 'AuthnContextClassref' of 'unspecified' as received by you in the SAML response implies that any authentication method that the service provider chooses can be used for authentication. Thus, the IdP responds with 'PasswordProtectedtransport' as the preferred choice of token issuing method and indirectly states that the preferred method authentication is not specified in the SAML request.
Please find the below link for reference on the 'RequestedAuthnContext' parameter: -
https://learn.microsoft.com/en-us/azure/active-directory/develop/single-sign-on-saml-protocol#requestauthncontext


text:
Q: Multiple t-tests vs. one-way ANOVA I'm working on a classification problem and I have a very high F1 baseline of 85%. I have trained three classification models and I want to know which one is the best. How can I do so?
I tried two ways:

*

*To compare each model against the baseline using paired t-test. So I have tests like:

*

*baseline vs. model 1

*baseline vs. model 2

*baseline vs. model 3

That tells me that only model 1 is significantly higher than the baseline and so I concluded that model 1 is the best. Is this a valid methodology given that usually classification models are compared against baselines?

*To compare all models in one fell swoop with one-way ANOVA. So I entered the information of models 1-3 and the baseline which gave me a p-value of 0.02 indicating that there is a difference in means. Yet, with pairwise post-hoc tests, there is no significance between any of the pairs.
Which method is the correct one?

A: There are two problems with your first approach: Multiple testing and the interpretation of the difference between significant and non-significant.
First, when you perform several tests, you increase the overall error rate. If you set $\alpha = .05$, you will still reject the null hypothesis 5% of the time when it is actually true (i.e. when there is no difference whatsoever). However, the probability that you reject the null hypothesis at least once when performing several tests is higher because you are taking this 5% risk each time you run a test. The problem is not very acute with only three tests but it still does not make much sense to run a test if you don't care about controlling the error level.
A quick fix for this problem is to adjust the error level with the Bonferroni correction. Since it is based on a very general probability inequality, it doesn't matter what the tests are and you can always use it but you will loose power. For example, it's possible that, after applying the correction, none of your tests would be significant and you would be back to the results of your second approach. This would resolve the apparent inconsistency but would not be terribly useful. Generally speaking, the main problem with this technique is that yo are not using all the information you have and the correction is usually too conservative. That's one reason to choose an ANOVA approach when you have several groups.
The second problem is that the difference between significant and non-significant is not necessarily itself significant. If you rejected the null hypothesis that model 1 is equal to baseline but not the separate hypothesis that model 2 is different from baseline, you still haven't established that model 1 is different from model 2. Those are three different questions. Let's see how this could happen:

Now, let's imagine that the difference between baseline and model 1 is "barely" significant, say p = .04. The p-value from a test of the difference between baseline and model 2 would then be a little over the threshold, say p = .06, so not significant. Yet, at the same time, model 1 and model 2 appear very similar and the difference between the two is also obviously not significantly different from 0.
The thing is that the logic of statistical testing requires us to specify an error level but there is nothing exceptional about this threshold. We simply have a little less evidence than the score for model 2 is higher than baseline and maybe this evidence is not sufficient to rule out the null hypothesis at the specified error level. This is however not enough to conclude that it is different from model 1.
Ignoring the multiple testing issue, you could then conclude that you don't know if model 2 is in fact better or worse than baseline and you certainly don't know if it is better or worse than model 1. Intuitively, if your data indeed look like the data on the graph, I don't find this very satisfying because it means treating model 1 and model 2 differently based on evidence that is much thinner than the evidence that model 2 is in fact better than baseline. However, this type of thinking is quite different from the logic underlying statistical tests. Instead of blindly make binary decisions based on the tests, I would therefore rather look at some graphs and make a judgment call about the results.
Either way, the results you presented suggest that your models do in fact represent an improvement over the baseline but there is no way you can conclude that model 1 is better than model 2. This is also pretty much what you can conclude from the ANOVA. If you want to know more, you need to look carefully at the size of the difference and probably collect more data/test the models on a larger data set.
PS: All this ignores two potential additional problems that were not raised in the question, namely the nature of your response variable (is it a proportion?) and independence (are all the models tested on the same exemplars?) Depending on the answers to these questions, ANOVA/T-test might not be the best choice anyway (see also this previous question). Also, if you specifically want to compare each group to baseline, you can also achieve that in an ANOVA framework by using contrasts. You would have a theoretically sound approach with more power than post-hoc pairwise tests but still would not address the "which one is best" question.

A: If your goal is to see which methods are better than the baseline, then method 1 is correct. If your goal is to see which methods are better than each other, then method 2 is correct. Method 2 with Dunnett's test could also be used, this makes corrections for the multiple comparisons involved. However, the question of whether you need to make these corrections is subject to debate and differing opinion. The tag "Multiple comparisons" here on Cross Validated will find lots of posts on that subject.


text:
Q: WCF only one way calls are working For some reason when I call service method that IsOneWay=true everything works fine, callback is returned as expected every time. But when I use method that IsOneWay=false, no errors are shown on client side but that method on server side is not called. What could be cause of this? Only thing that I did was small refactoring in logic that handles service instance in client side.
Client side logic
public interface ISomeServiceClient
{
    IService Instance { get; }
}

public class SomeServiceClient : ISomeServiceClient
{
    private ServiceClient client;
    private IServiceCallback callback;
    private System.ServiceModel.InstanceContext instanceContext;

    public SomeServiceClient()
    {
        this.callback = new ServiceCallback();
        this.instanceContext = new System.ServiceModel.InstanceContext(callback);
        this.client = new ServiceClient(instanceContext);
    }

    public IService Instance
    {
        get { return this.client; }
    }
}

public class SomeViewModel
{
    private readonly IService serviceClient;
    public SomeViewModel()
    {
        this.serviceClient = SharedService.Instance.ServiceClient
    }
    public void RetrieveData()
    {
      // Then I just call server side like this
        this.serviceClient.GetSomeData();
    }
}

Note: SharedService is sigleton that returns IService new instance of SomeServiceClient if not yet initialized.
Server side data contracts
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public partial class Service : IService
{
}

[ServiceContract(CallbackContract = typeof(IServiceCallback))]
public interface IService : ISomeDataService
{
}

[ServiceContract(CallbackContract = typeof(ISomeDataServiceCallback))]
public interface ISomeDataService
{
     [OperationContract(IsOneWay = false)]
     List<Data> GetSomeData();
}

I don't know if it's necessary to show also service configuration but here it goes..
<system.serviceModel>
    <services>
      <service name="MyService.Library.Models.Service">
        <host>
          <baseAddresses>
          <!-- ip changed for demo purposes -->
            <add baseAddress="net.tcp://111.111.11.111:2222/MyService" />
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://111.111.11.111:2222/MyService"
                  binding="netTcpBinding"
                  bindingConfiguration="TcpConfig"
                  contract="MyService.Library.Interfaces.IService" />
      </service>
    </services>
    <bindings>
      <netTcpBinding>
        <binding name="TcpConfig">
          <security mode="None">
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
</system.serviceModel>

I have also tried to use other methods that are not one way call, and they are also not calling service.
As I mentioned, no code was changed in configuration file.

A: Since you are using Callback methods in your service, you are using Duplex contract as the messaging pattern between client and server.
A duplex contract consists of two one-way contracts between the client and the server and does not require that the method calls be correlated. We generally, use this kind of contract when your service must query the client for more information or explicitly raise events on the client


text:
Q: Magento update order product on observer I'm trying to update additional_data field on sales_flat_order_item table in Magento.
For this I create a custom module
This is my Observer.php under app/code/local/Distelsa/Wedding/Models :
class Distelsa_Wedding_Model_Observer{

    public function AddWeddingIdToProduct(Varien_Event_Observer $observer)
    {
        $event = $observer->getEvent();

        $item = $event->getQuoteItem();
        $quote = $item->getQuote();
        $product = $observer->getEvent()->getProduct();

        $controllerAction = $event->getControllerAction();
        $params = $controllerAction->getRequest()->getParams();
        $boda = Mage::app()->getRequest()->getParam('boda');

        $write = Mage::getSingleton('core/resource')->getConnection('core_write');
        $query = "UPDATE `sales_flat_quote_item` SET additional_data = '".$params['boda']."' where item_id = ".$item->getId();
        $write->query($query);

    }
}

This is my config.xml:
<global>
    <events>
        <sales_order_save_after>
            <observers>
                <sales_order_save_after_wedding>
                    <type>model</type>
                    <class>wedding/observer</class>
                    <method>AddWeddingIdToProduct</method>
                </sales_order_save_after_wedding>
            </observers>
        </sales_order_save_after>
    </events>
</global>

Any clue on how can I make this works?

A: The <class> is wrong in the config.xml file.
The correct class in the config.xml goes like this :
<global>
    <events>
        <sales_order_save_after>
            <observers>
                <sales_order_save_after_wedding>
                    <type>model</type>
                    <class>distelsa_wedding/observer</class>
                    <method>AddWeddingIdToProduct</method>
                </sales_order_save_after_wedding>
            </observers>
        </sales_order_save_after>
    </events>
</global>

Clear the chache when you are done. Hope this helps.


text:
Q: Traceability matrix in TFS? Is there any best practise to realize a Traceability Matrix in TFS?
We are currently struggeling how we shall configure the Areas, Iterations and how we can build up the "matrix".
We are planning to use the Areas as "functional components" and the Iterations for the software releases.
At the end we want to be able to create a report like this:
                   | Release_1 | Release_2 | Release_3
-------------------------------------------------------
Requirement 1      |    X           X
Requirement 2      |                            X
Requirement 3      |    X                       X

The important point for us is to generate the complete requirement list for a specific release.
The problem we face is that the releases are developed incremental. Meaning over time new requirements are added. We are know looking for a simple way to also link the old/existing requirement to a specific release without the need for duplicating each requirement.
Can someone suggest a way to achive the above matrix?
EDIT:
Requirement means the functionality to be implemented. Release is a specific software version. The requirements are incrementally added to the releases. This means the number of implemented requirements may grow from release to release. What we can do now is to link the implementation of a requirement to a specific release (Iteration). But all the following releases (Iterations) automatically include this requirement, because we work incrementally. But it might also be possible that a requirement gets changed or even obsolete in a following release. How can we handle this to be able to get get the complete/full requirement list for a specific release?


text:
Q: How to store credit card in Paypal Vault without using the server as a proxy We are using Paypal vault to store credit cards. (https://developer.paypal.com/webapps/developer/docs/integration/direct/store-a-credit-card/) this goes like this:
1) Ajax call from browser to server
2) Server sends request with accessToken to Paypal
3) Paypal responds with a token
So: User browser -> our server -> Paypal -> our server
Because of new internal policy I need to remove the 2nd step. So, I should go from the users browser to Paypal, receive the token, store the token
User browser -> Paypal -> User browser -> our server
Any thoughts on that?
UPDATE:
Would it be safe to send the access token through the browser? (I can create it on the server)
https://developer.paypal.com/docs/integration/direct/make-your-first-call/


text:
Q: Element spinner must be declared I'm trying to add Spinner to ActionBar and getting this error right in xml file:
Element spinner must be declared

I'm confused. The problem solution must be simple but I can't really realize how to solve it..

A: It looks like you are trying to put a Spinner in your menu XML. Views such as Spinners are not valid elements in menus.
If you intent to inflate this layout and use it in an Activity or Fragment, you should move this file to /layouts. If you are actually trying to get a Spinner in your ActionBar, I recommend reading the Adding Drop-down Navigation documentation.
In your Activity's onCreate() you will need to call setNavigationMode(NAVIGATION_MODE_LIST), then actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback), passing in a SpinnerAdapter and an ActionBar.OnNavigationListener.


text:
Q: Business date/holiday handling I've posted this question for C# but I may be working in Ruby instead.  So I'm asking the same question about Ruby:
I'm looking for a Ruby class/library/module that works similarly to the Perl module Date::Manip as far as business/holiday dates.  Using that module in Perl, I can pass it a date and find out whether it's a business day (ie, Mon-Fri) or a holiday.  Holidays are very simple to define in a config file (see Date::Manip::Holidays).  You can enter a 'fixed' date that applies to every year like:
12/25                           = Christmas

or 'dynamic' dates for every year like:
last Monday in May              = Memorial Day

or 'fixed' dates for a given year like:
5/22/2010                       = Bob's Wedding

You can also pass in a date and get back the next/previous business day (which is any day that's not a weekend and not a holiday).
Does anyone know of anything like that in the Ruby world?

A: You may use the holidays-gem.
http://rubygems.org/gems/holidays
Some national (and regional) holidays are already predefined, you may define your own holiday definitions.

A: The business_time gem should do what you need.
The example at bottom of the README doc is a good starting example:
require 'rubygems'
require 'active_support'
require 'business_time'

# We can adjust the start and end time of our business hours
BusinessTime::Config.beginning_of_workday = "8:30 am"
BusinessTime::Config.end_of_workday = "5:30 pm"

# and we can add holidays that don't count as business days
# July 5 in 2010 is a monday that the U.S. takes off because
# our independence day falls on that Sunday.
three_day_weekend = Date.parse("July 5th, 2010")
BusinessTime::Config.holidays << three_day_weekend
friday_afternoon = Time.parse("July 2nd, 2010, 4:50 pm")
tuesday_morning = 1.business_hour.after(friday_afternoon)

You probably going to need the chronic gem to help you build the holiday dates from your config file.  However YMMV because your example last monday in may doesn't work in chronic.  Hackaround is do something like this:
# last monday in May (2010)
Chronic.parse('last monday', :now => Time.parse('2010-06-01'))

And look at the tickle gem which works on top of chronic for a way to add recurring events.
/I3az/

A: You could take a look at my Workpattern gem.  It allows you to specify working and resting times.  It was aimed at producing a "Calendar" like is used in planning tools such as Microsoft Project and Primavera P6, so you can specify right down to the minute.
Here is a simple example:
Create a new Workpattern mywp=Workpattern.new('My Workpattern',2011,10)  This is for 10 years from 2011 but you can make it longer or shorter.
Tell it you want the Weekends to be resting and that you also want to rest during the week so you work between 9 and 12 in the morning and 1 and 6 in the afternoon.
mywp.resting(:days => :weekend)
mywp.resting(:days =>:weekday, :from_time=>Workpattern.clock(0,0),:to_time=>Workpattern.clock(8,59))
mywp.resting(:days =>:weekday, :from_time=>Workpattern.clock(12,0),:to_time=>Workpattern.clock(12,59))
mywp.resting(:days =>:weekday, :from_time=>Workpattern.clock(18,0),:to_time=>Workpattern.clock(23,59))

Now just calculate using minutes
mydate=DateTime.civil(2011,9,1,9,0)
result_date = mywp.calc(mydate,1920) # => 6/9/11@18:00

1920 is 4 days * 8 hours a day * 60 minutes and hour.
I wrote the gem to learn Ruby - only scratched the surface.

A: Check out the biz gem.
Here's an example configuration:
require 'biz'

Biz.configure do |config|
  config.hours = {
    mon: {'09:00' => '17:00'},
    tue: {'00:00' => '24:00'},
    wed: {'09:00' => '17:00'},
    thu: {'09:00' => '12:00', '13:00' => '17:00'},
    sat: {'10:00' => '14:00'}
  }

  config.holidays = [Date.new(2014, 1, 1), Date.new(2014, 12, 25)]

  config.time_zone = 'America/Los_Angeles'
end

When you use the optional core extensions, it's as easy as the following to find out if a date is a business day:
require 'biz/core_ext'

Date.new(2014, 12, 25).business_day? # => false


text:
Q: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION) I am getting syntax error in the following code:
function getFridays($year='', $format='', $timezone = 'UTC') {

$fridays = array();
$startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));

$year++;
$endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));

$int = new DateInterval('P7D');

foreach (new DatePeriod($startDate, $int, $endDate) as $d) {
    $fridays[] = $d->format($format);

}

return $fridays;
}

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');

Error: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)

A: Problem is with this line
$fridays = getFridays($year, 'Y-m-d', 'America/New_York');

You cannot put this outside of the function and called another function. If you want to call this you have to put it in another function. Just try to var_dump the $friday after the return outside of the for loop.
var_dump($friday);
exit;

you can see your array.

A: The provided code works fine is copied directly into a sandbox because all of the class stuff is missing. Without it, it will work fine. So, you're declaring the variable inside a method, but trying to set it outside of the method, which is a no-go.


text:
Q: Is band theory applicable only for valence electrons Is band theory applicable only for the valence energy levels of a metal?
When metal atoms come together the valence electrons occupy a band of energy levels. But does the energy of the inner electrons get affected? Do they continue to have discrete energies?


text:
Q: Weierstrass theorem and necessary condition This is $(7.36)$ exercise of Hewitt & Stromberg - Real and Abstract analysis and i can't figure out the construction.
Let $X$ be any noncompact subset of $\mathbb{R}$. Find a separating family $\mathcal{C}$ in the set of all continuous function on $X$, such that polynomials in the family $\mathcal{C} \cup \{1\}$ are not dense in the set of all continuous function on $X$.
Is this a way to describe the necessary condition about compactness for the set X in the Stone-Weierstrass theorem?

A: Suppose at first that $X$ is not closed and let $x_0\in \overline{X} \setminus X.$ Define function $\varphi : X\to\mathbb{R} ,$ $\varphi (t) =(t-x_0 )^{-1} $ then $\varphi\in C(X)$ but for any polynomial $W:\mathbb{R}\to\mathbb{R} $ we have $$\left|\left| W-\varphi \right|\right|_{\infty} =\infty.$$
If $X$ is closed then $X$ must be unbounded. So in this case let us define $\psi :X\to\mathbb{R} ,$ $\psi (t) = e^{|t|}  $ then $\psi\in C(X)$ but for any polynomial $V:\mathbb{R}\to\mathbb{R} $ we have $$\left|\left| V-\psi \right|\right|_{\infty} =\infty.$$


text:
Q: I want to setup Apache Metron, I have installed CentOS 7 on my Windows 7 and VMWare I installed Apache Maven 3.3.9, Python 2.7, Java 1.8, Ansible 2.0.0.2, Vagrant 1.9.6 and VirtualBox 5.1 on CentOS 7
When I run 'vagrant up', there is an error of Maven dependencies and also Ansible failed to setup successfully and this also happens when I do 'vagrant provision'.
Where do I need to run the command mvn clean install packages?

A: try running the command within the metron folder.

*

*Open Terminal, run:
cd metron
mvn clean install


text:
Q: Unable to insert values in Table from variables I am trying to insert the values into the table and i am unable to do this..
I am getting values from Enrty Widgets into a variable and putting them in DataBase but unfortunately i got error
I have tried this but getting error
G_Name = Namee
G_Day = Value.day
G_Month = Value.month
G_Year = Value.year

sql = "insert into Birthdays (Name, Day, Month, Year) VALUES (%s, %d, %d,
%d) %"
val = (G_Name, G_Day, G_Month, G_Year)
mycursor.execute(sql, val)

It should insert values but i am getting following error:
"Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-
parameters; Python 'stringvar' cannot be converted to a MySQL type

A: I have not worked on python 3.X but this is how it works on python 2.7
G_Name = Namee
G_Day = Value.day
G_Month = Value.month
G_Year = Value.year
mycursor = connection.cursor(prepared=True)
sql = """ insert into Birthdays (Name, Day, Month, Year) VALUES (%s, %d, %d, %d)"""
val = (G_Name, G_Day, G_Month, G_Year)
mycursor.execute(sql, val)
connection.commit()

I don't know but that last % in your query is supposed to be there?.

A: G_Name = str(En_Name.get())

i have corrected the error by using above statement
sql query cannot take StringVar() so i converted it to str then used it and it works


text:
Q: Search and replace characters in a file with Python I am trying to do transliteration where I need to replace every source character in English from a file with its equivalent from a dictionary I am using in the source code corresponding to another language in Unicode format. I am now able to read character by character from a file in English how do I search for its equivalent map in the dictionary I have defined in the source code and make sure that is printed in a new transliterated output file. Thank you:).

A: The translate method of Unicode objects is the simplest and fastest way to perform the transliteration you require.  (I assume you're using Unicode, not plain byte strings which would make it impossible to have characters such as 'पत्र'!).
All you have to do is layout your transliteration dictionary in a precise way, as specified in the docs to which I pointed you:

*

*each key must be an integer, the codepoint of a Unicode character; for example, 0x0904 is the codepoint for ऄ, AKA "DEVANAGARI LETTER SHORT A", so for transliterating it you would use as the key in the dict the integer 0x0904 (equivalently, decimal 2308).  (For a table with the codepoints for many South-Asian scripts, see this pdf).

*the corresponding value can be a Unicode ordinal, a Unicode string (which is presumably what you'll use for your transliteration task, e.g. u'a' if you want to transliterate the Devanagari letter short A into the English letter 'a'), or None (if during the "transliteration" you want to simply remove instances of that Unicode character).
Characters that aren't found as keys in the dict are passed on untouched from the input to the output.
Once your dict is laid out like that, output_text = input_text.translate(thedict) does all the transliteration for you -- and pretty darn fast, too.  You can apply this to blocks of Unicode text of any size that will fit comfortably in memory -- basically doing one text file as a time will be just fine on most machines (e.g., the wonderful -- and huge -- Mahabharata takes at most a few tens of megabytes in any of the freely downloadable forms -- Sanskrit [[cross-linked with both Devanagari and roman-transliterated forms]], English translation -- available from this site).

A: Note: Updated after clarifications from questioner. Please read the comments from the OP attached to this answer.
Something like this:
for syllable in input_text.split_into_syllables():
    output_file.write(d[syllable])

Here output_file is a file object, open for writing. d is a dictionary where the indexes are your source characters and the values are the output characters. You can also try to read your file line-by-line instead of reading it all in at once.


text:
Q: perfect scrollbar set maxScrollbarLength I used this plugin https://github.com/noraesae/perfect-scrollbar and there is minScrollbarLength but I wana set maxScrollbarLength but I low in programing and i dont know where i can change this option so I ask for help.
my code in index

A: Perfect scrollbar does not support max-size as I know. You have to change plugin code or contact author and report this as a feature. Also you can try jQuery Scrollbar which supports it and has the same styles as perfect scrollbar.


text:
Q: JSON data not displaying in Ionic HTML file I have got my data from my API and it is logged in the console. However, I am unable to access it through my HTML file. I'm not sure why it isn't working? (Looked at other questions and still no joy).
ts file
 patients: [];
 constructor(private viewService: ViewPatientService ) { }
  ngOnInit() {
    this.viewService.viewPatient().subscribe(data => {
    console.log(data);
  });

html file
<ion-item *ngFor="let patient of patients">
Name: {{patient.patients.data[0].FirstName}}
</ion-item>

A: Please note data should hold the patients array, if not add the property as needed.
patients: [];

constructor(private viewService: ViewPatientService) { }

ngOnInit() {
    this.viewService.viewPatient().subscribe(data => {
        console.log(data);
        this.patients = data
    });
}

A:
You haven't assigned the value to patients array

patients: [];

constructor(private viewService: ViewPatientService ) { }

  ngOnInit() {
  this.viewService.viewPatient().subscribe(data => {
      **this.patients = data;**
      console.log(data);
    });

A: patients: any;

constructor(private viewService: ViewPatientService ) { }

  ngOnInit() {
  this.viewService.viewPatient().subscribe(data => {
      this.patients = [data];
      console.log(data);
    });


text:
Q: Why is the MIME Type for HTML text but the MIME Type for XHTML application? What makes XHTML (and other XML languages) applications while other SGML-based languages are text? Aren't XML files text files?

A: XHTML is a subset of XML; XML's media type/mime is text/xml while XHTML's media type/mime is application/xhtml+xml.
Generally HTML is essentially treated like plain text that is interpreted very loosely. Because HTML's junk status reputation XHTML was created to force web designers and web developers to code clean HTML. Gecko (Firefox) and Presto (Opera) browsers correctly break the page and display a malformed XML parse error whereas WebKit (Chrome/Safari) and Trident (Internet Explorer 9.0+ only) fail at failing and merely stop rendering the page.
An XHTML application served as text/html is NOT XHTML, it's HTML with an XHTML doctype.
For XHTML code to be served as an XHTML application it must be served as application/xhtml+xml.
XHTML is also intended to be backwards compatible with HTML.
The following PHP code will look at the headers sent by the client's browser and serve the page as an XHTML application if the browser supports it (all Chrome, Safari 3.0+ (maybe 1.0)), Mozilla Suite 0.8+/all Firefox and Opera 7.0+ (possibly 6.0) support XHTML. Only Internet Explorer 8.0 and older have any market share that does not support XHTML. KHTML browsers (Konqueror) DO support XHTML however I think 4.4 does/did not serve the correct header to the server.
<?php
$http_accept_xhtml = stristr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml');

if ($http_accept_xhtml) {$mime = 'application/xhtml+xml';}
else {$mime = 'text/html';}

header('Content-Type: '.$mime);
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
?>

XHTML is way better than HTML if you're intelligent enough to fix errors when you come across them. It's stricter but that's the point, much less subjectivity. The X in XHTML stands for extensible so it supported SVG and other languages before HTML did if you do a bit of reading.

A: There are several acceptable MIME types for many kinds of data.  For instance, XML could be either text/xml or application/xml (http://tools.ietf.org/html/rfc3023).
HTTP is full of multiple correct ways to do stuff; it's a byproduct of being designed and used by so many people.  It's also constantly evolving.  Generally, even if there was only one way to design something, there can be many ways in which it was used, and these become de facto standards after enough people pick up on them.
If you don't find any problems with saying that your XHTML and SGML are both "applications" and everything still works and it makes you happier, go for it.


text:
Q: Contractive family of functions Problem
Let $\{K_{\alpha}:C\to C\}_{\alpha \in \mathbb{R}^{n}}$ be a family of functions where $C\subset X$ is a closed subset of a Banach space X. Suppose that for some $\theta \in (0,1)$ we have that $\| K_{\alpha}(x) - K_{\alpha}(y)\| \leq \theta \| x-y\|$ and $K_{\alpha}(x)$ is continuous for some fixed x. Lets call $\overline{x} \in C $ the unique fixed point of $K_{\alpha}$ (the contraction).
Show that the function $\alpha \to \overline{x}$ is continous.
Im totally lost in this one, so any help would be really appreciated.
Thanks so much in advance guys <3

A: Let us denote the unique  fixed point of $K_{\alpha}$ by $f(\alpha).$
Counterexample: $C=X= \mathbb R, n=1$ and
$K_{\alpha}(x)= \frac{\alpha}{2}x$, if $| \alpha |<1$ and $K_{\alpha}(x)= \frac{1}{2 \alpha}(1-x)$, if $| \alpha | \ge 1$. In this case we have $ \theta=1/2$ and
$f(\alpha)=0$, if $| \alpha |<1$ and $f(\alpha)=\frac{1}{2 \alpha +1}$, if $| \alpha | \ge 1$.
$f$ is not continuous !


text:
Q: unsigned int mysql in C# In mysql I declared fields of type unsigned int. They defaulted to INT(10) UNSIGNED. In my c# code when I try to read in these values to an uint type it gives me an error saying
"cannot convert long into an uint".
Is there anything I am missing here. I thought BIGINT was supposed to be long and int(10) unsigned was supposed to be uint?
I am using entity framework to read in the values...
Thanks
CODE
from employee in model.employees
select new EmployeeEntity {
  EmpID = employee.EmpID,
  FirstName=employee.FirstName
};

EmpID is declared as UNSIGNED INT 10 in mysql
EmployeeEntity declares EmpID as uint (I tried uint32 as well). However the line
The assignment "EmpID = employee.EmpID" gives me the error...

A: The sounds like an issue with the EF Provider. It might be that the value is simply retrieved as a long. But since you know its a uint you can simply cast it from long to uint.
But try to check if there is a newer version of the EF Provider that maps the types correctly.

A: It is provider trouble. It converts types between DBMS and application with errors. I recommend you to ask their support or change provider.
As for me - I'm using Devart dotConnect for MySQL. Its mapping table is provided here - http://www.devart.com/dotconnect/mysql/docs/DataTypeMapping.html


text:
Q: Formatting text in Adb Shell I was doing some adb shell stuff on windows and stuck at a point. Here's what I was doing..
I was printing all installed apps on my phone and getting their exact path.
zeroltetmo:/ # pm list packages -f
package:/system/app/FilterProvider/FilterProvider.apk=com.samsung.android.provider.filterprovider
package:/system/priv-app/CtsShimPrivPrebuilt/CtsShimPrivPrebuilt.apk=com.android.cts.priv.ctsshim
package:/system/app/YouTube/Youtube.apk=com.google.android.youtube
package:/system/app/vsimservice/vsimservice.apk=com.sec.vsimservice
package:/system/priv-app/WallpaperCropper/WallpaperCropper.apk=com.android.wallpapercropper
package:/system/framework/framework-res.apk=android
package:/system/framework/samsung-framework-res/samsung-framework-res.apk=com.samsung.android.framework.res
package:/data/app/com.whatsapp-1/base.apk=com.whatsapp
package:/data/app/ru.meefik.busybox-2/base.apk=ru.meefik.busybox
package:/data/app/com.google.android.play.games-1/base.apk=com.google.android.play.games

But,
I want this to print only system/app directory but only upto folder name instead of the full path. What i'm doing is piping this to grep and using this pattern to get the result.
zeroltetmo:/ # pm list packages -f | grep -o "system/app.*\/"
system/app/FilterProvider/
system/app/RootPA/
system/app/YouTube/
system/app/ClipboardSaveService/
system/app/TetheringAutomation/
system/app/GoogleExtShared/
system/app/WfdBroker/
system/app/vsimservice/
system/app/USBSettings/
system/app/EasyOneHand3/

But the problem is this / at the end of folder name that I'm stuck with.

A: You can filter the trailing slashes out with sed like that:
pm list packages -f | grep -o "system/app.*/" | sed 's,/$,,'

Explanation of the sed command:
s stands for substitution
, delimits command name from its arguments - it's easier to use something different / when we want to replace /
/$ - string to be replaced. In this case it means slash at the end of the line
The string to replace /$ with is empty because we want to remove it.


text:
Q: Uncaught TypeError: Property '$' of object [object global] is not a function? I am getting the following error

Uncaught TypeError: Property '$' of object [object global] is not a function
  in line 2:

Using the following code:
$(document).ready(function() {
    $('#tabs > ul').tabs({ fx: { opacity: 'toggle' } });
    $('#featuredvid > ul').tabs();
});

The problem appears local at 127.0.0.1 only, while same code OK online!  I'm dazzled, any ideas?

A: I had pretty much same problem. The error message says
TypeError: $ is not a function
$(document).ready(function() {

The line in my code that was throwing error is this :
$(document).ready(function(){

In my case the problem is that $ is not recognized as jquery. I had to replace $ with the keyword jQuery. So finally i changed my code like this:
jQuery(document).ready(function(){

And it worked.

A: I ran into this error when I was trying to use the slide effect that I thought was part of jQuery but was actually a jQuery UI effect. This was the output from my console:
Uncaught TypeError: Property '#<Object>' of object #<Object> is not a function

So, to me it seems like you just need to include the jquery UI library. Add this line after you include jQuery.
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

A: I had the same error with tabs and after some digging in jQuery documentation I found this:
http://docs.jquery.com/Using_jQuery_with_Other_Libraries#Overriding_the_.24-function
Once I overrode the jQuery it was working. So it seems like I had some namespace problems.

A: I got the same error and solve it by adding
var $ = jQuery;

as a global var on my script

A: Is jquery available locally ?  (the error you mention usually means that the jQuery is not available - loaded)
Perhaps you are loading it from a relative path and the structure is different to the online version ..

A: Check to see if any other script you are using is calling jQuery.noConflict(). Doing so releases the $ binding, thus causing the $ symbol to be undefined.
One way to fix this is to add $ as the first parameter of your callback function:
$(document).ready(function($) {
    ...
}

This works because the global jQuery object is passed as the first parameter to a .ready() handler. See also http://api.jquery.com/ready/

A: Use this instead:
jQuery(document).ready(function($){
    $('#tabs > ul').tabs({ fx: { opacity: 'toggle' } });
    $('#featuredvid > ul').tabs();
});

A: Might be a browser security setting, blocking JS to run locally, are you using IE by any chance?
Try with Firefox or play with your security settings in IE

A: Simply, use the following :
jQuery(function() {
    //Your code when document will be ready
});

A: It might be the version of jQuery or something along those lines. I had this exact problem - I was using a local copy of jQuery (version 1.3.2) and then switched to http://code.jquery.com/jquery-latest.pack.js and suddenly it worked (latest at the time was 1.4.1).
I also had some of the issues you mentioned about "Resource interpreted as script but transferred with MIME type text/plain". I think that's safe to ignore for this particular problem as it still shows up for me even though my javascript is working now.

A: Disabling the pop up blocker worked for me


text:
Q: adding a function to .zshrc changes the command I added the following function to my .zshrc
function jptt(){
  # Forwards port $1 into port $2 and listens to it
  ssh -N -f -L localhost:$2:localhost:$1 remoteuser@remotehost
}

then I am running jptt 1 2
and get the following error:

Bad local forwarding specification localhost:2ocalhost:1

It is strange that I lose :l after the 2
the function is working when as I tried to replace the command with a simple line and it worked. I also run the ssh command separately and it works well.

A: The expression $x:l applies the lower-casing modifier to your x variable. The following example illustrates this:
pax> x=ABC
pax> echo $x:lnnn
abcnnn

pax> echo ${x}:lnnn
ABC:lnnn

The first section gives you the lower-case variant, and therefore the modifier is not considered part of your output string. The second section shows how you can prevent this variable expansion by using braces to ensure the :l is not treated as a modifier. In your specific case, that would be done with the line:
ssh -N -f -L localhost:${2}:localhost:${1} remoteuser@remotehost

It's actually a good idea to get into the habit of bracing parameter names as much as possible since there are other cases where this might adversely affect you.

A: Use ${1} and ${2} . Zsh supports : csh string modificators and :l has special meaning (to lowercase variable in front of it) and that's why it is consumed from $1:localhost.


text:
Q: authorizationController delegate didCompleteWithAuthorization what type is the param authorization: ASAuthorization? I work under Delphi, and I try to understand what exactly is the authorization: ASAuthorization param in the didCompleteWithAuthorization delegate of ASAuthorizationControllerDelegate
// ASAuthorizationControllerDelegate function for successful authorization
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
        // Create an account in your system.
        let userIdentifier = appleIDCredential.user
        let userFirstName = appleIDCredential.fullName?.givenName
        let userLastName = appleIDCredential.fullName?.familyName
        let userEmail = appleIDCredential.email

        //Navigate to other view controller
    } else if let passwordCredential = authorization.credential as? ASPasswordCredential {
        // Sign in using an existing iCloud Keychain credential.
        let username = passwordCredential.user
        let password = passwordCredential.password

        //Navigate to other view controller
    }
}

what I don't fully understand here, it's what exactly mean
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {

and
} else if let passwordCredential = authorization.credential as? ASPasswordCredential {

does it's mean that authorization.credential in inherited from both types: ASAuthorizationAppleIDCredential & ASPasswordCredential or that authorization.credential is just a pointer that can be any kind of object and we just need to cast this pointer? How to know with type of object the authorization.credential? In with scenarios authorization.credential return an ASAuthorizationAppleIDCredential ?

A: As stated in apple docs,
credential is the information provided about a user after successful authentication.

Every credential is inherited from / conforms to ASAuthorizationCredential.
There are 3 conforming types : ASAuthorizationAppleIDCredential, ASAuthorizationSingleSignOnCredential and ASPasswordCredential.
ASAuthorizationAppleIDCredential : A credential that results from a successful Apple ID authentication.
ASAuthorizationSingleSignOnCredential : A credential that results from a successful single sign-on (SSO) authentication.
ASPasswordCredential : We can use this to create a credential  with a given user name and password.

You can typecast it according to different ways the credential has been created. If the resulting credential is from Apple ID authentication, then the cred can be typecasted to ASAuthorizationAppleIDCredential.


text:
Q: NX package-based repo: projectRoot vs workspaceRoot? If I have a package-based monorepo with NX, which directory is projectRoot, and which one is workspaceRoot?
From the docs (https://nx.dev/reference/project-configuration):

{projectRoot} and {workspaceRoot}
{projectRoot} is a key word that is replaced by the path to the current project's root directory. {workspaceRoot} is a key word that is replaced by the path to the workspace root directory.

This is hilariously obvious and unhelpful explanation. I want to know which one is which, given I have this directory structure:
(git repo root dir)
|
+- nx.json
+- package.json - it says `"workspaces": [ "packages/*" ]`
|
+- packages/
   |
   +- package1/
   +- package2/

Because package.json mentions my packages/* as "workspaces", my guess is that each package is a workspace, thus workspaceRoot must refer to each package individually, while projectRoot must refer to a top-level dir with my nx.json config. But I have absolutely no idea how to confirm this. I'm experimenting with cache (setting various inputs as seeing is it hits or misses), and absolutely nothing works.
To clarify what I'm confused about: Is "workspace root" a directory containing all the workspaces (i.e. packages), or does it mean "root directory of an individual workspace (i.e. package)." (Here I'm assuming that "workspace" == "package", which may not be true.)

A: Based on reading https://nx.dev/concepts/mental-model, here are my definitions:

*

*"project" = each package, e.g. a library or an app, which refers to each individual subdirectory inside packages/

*"projectRoot" = root of each individual package. In the example from the question, it will be packages/package1 and packages/package2

*"workspace" = collection of all the packages/projects. Note that "package.json" uses the word "workspaces" (plural) to refer to a directory with all the packages, which is what confuses me.

*"workspaceRoot" = the root directory where nx.json is located

In short:

*

*project = package

*workspace = collection of projects


text:
Q: Need to pass data to hidden text field in Selenium I got the below solution here,
jse.executeScript("document.getElementsByName('body')[0].setAttribute('type', 'text');");

and then passing data using SendKeys.
But it is creating duplicate text field with text attribute and hidden text field still exist..

A: You have two input tags. I am assuming you want to execute the script against the second one not the first.
Also, I am using querySelector and that allows you to pass cssSelector to identify the element you want.
Note: Make sure the format of dateToPass is correct
String dateToPass = "01/01/2015";
String scriptText = "document.querySelector('.propertyYear.require').setAttribute('value','" + dateToPass + "')";
((JavascriptExecutor)driver).executeScript(scriptText);


text: Q: Number is saved in database as Number - 1 I have a function that receives a value amount, that is a float number. This number is multiplied by 100 to be converted to a whole number, before it is saved into the database. Dumping the variable after the multiplication shows that its value is 6699. When saving the number to the db (in an int column) it is saved as 6688 though! What can be wrong


text:
Q: why requestAnimationFrame isn't restarting? I want to be able to pause animation and restart it when I need. To achieve this I added 'click' event listener. So far I can pause it but when I try to resume it I am getting this:

Uncaught ReferenceError: animate is not defined

my code:
var canv = document.getElementById('canv'),
ctx = canv.getContext('2d');
var x = 10,
y = 10;
var dx = 1,
dy = 3;
var running = false;
var anim;

var fps = 60;
var delay = 1000 / 60;

function draw() {
    ctx.clearRect(0, 0, canv.width, canv.height);
    ctx.save();
    ctx.translate(x, y);
    ctx.beginPath();
    ctx.arc(0, 0, 5, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
}

function move() {
    x += dx;
    y += dy;

if (x >= canv.width || x <= 0) {
    dx = -dx;
}
if (y <= 0 || y >= canv.height) {
    dy = -dy;
}
}
var start = 0;

(function animate() {
    running = true;
    var current = new Date().getTime(),
    delta = current - start;

if (delta >= delay) {
    move();
    draw();
    start = new Date().getTime();
}

anim = requestAnimationFrame(animate);
})();

window.addEventListener('click', function() {
    if (running == true) {
    cancelAnimationFrame(anim);
    running = false;
} else {
    anim = requestAnimationFrame(animate);
    running = true;
}
});

what is wrong? Why can't I call animate function? As far as I know it's declared in global scope, so why does it say that it is not defined? I don't get it.
fiddle: http://jsfiddle.net/X9qt7/2/

A: You are actually not defining animate() in global scope but as an expression which will never be available from parent. rAF works in the loop inside because it's in animate()'s child scope inside the expression and can reference it.
To fix:
function animate() {
    running = true;
    var current = new Date().getTime(),
        delta = current - start;

    if (delta >= delay) {
        move();
        draw();
        start = new Date().getTime();
    }

    anim = requestAnimationFrame(animate);
}
animate();

Now animate() will defined in global scope.

A: Just go with:
function animate() {
    ...
    window.animation = requestAnimationFrame(animate);
};
animate();


text:
Q: Magento2: Show custom currency symbol in specific store view How to show custom currency symbol in specific store view based on local location ar_SA or ar_EG ?
I tried XML files inside vendor\magento\zendframework1\library\Zend\Locale\Data\ but not working.
Magento 2.1.6


text:
Q: Prime Implicant In a K-map, I know block consists entirely of don't cares and is not part of a bigger block is considered as Prime implicant.
For ex-The one in red in the given figure-

But I am not able to figure out the reason behind it.
As that Prime implicant is of no use then why to consider it even as prime implicant?

A: Prime implicants are the minimal parts of a boolean equation that can represent your function. Since you can represent part of your function with the don't cares, they do count as prime implicants even if every part of the implicant is a don't care.


text:
Q: Show specific value in dropdown I have a table where in each row for each id we have 'Client' column. When a user clicks on the row he is able to change client. I am using jquery.dialog for this operation. When a dialog appears the user sees a dropdownlist with Clients. How I can make that after dialog appears, the user sees the current client as the selected item in the dropdown? I've tried as below:
onDblClickRow: function (row, $element) {
    $.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
        if (clients.length == 0) {
            $('#clientNameEdit').empty();
            $('#clientNameEdit').append('<option value="0">Tasks</option>');
        }
        $.each(clients, function (index, clientt) {
            $('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
        });
    })
   var currentClient = row.clientName; // Client name from Row
   $('#clientNameEdit select').val(currentClient); // Tried to set like that
}

but doesn't work

A: The value passed in to .val needs to be the clientt.Value and not the text name.
if you dont have the clientt.Value, then try something like:-
$("#clientNameEdit option[text=" + currentClient + "]").attr("selected", true);

And bring the setting of the select inside of the success function.

A: The following alteration to your code snippet should do the trick:
onDblClickRow: function (row, $element) {
            $.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
                if (clients.length == 0) {
                    $('#clientNameEdit').empty();
                    $('#clientNameEdit').append('<option value="0">Tasks</option>');
                }
                $.each(clients, function (index, clientt) {
                    $('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
                });
                var currentClient = row.clientName; // Client name from Row
                $('#clientNameEdit').val(currentClient); // Tried to set like that but doesn't work
            });

As indicated above, if you do the currentClient = row.clientName outside the success of the ajax call, it will probably fire before the dropdown is populated and therefore not have any effect.
Secondly the jQuery selector '#clientNameEdit select' should only be '#clientNameEdit' as it refer to the dropdown itself and not it's parent.


text:
Q: How to check if a temporary table is existing in Database I am actually dropping a temporary table in Database. I have to delete only if it exists in the Database. Please let me know how to check if a table exists in Data base.

A: if object_id('tempdb..#myTempTable') is not null
    drop table #myTempTable


text:
Q: Can I change the notation in a built-in Isabelle type-class I have made a type of mine an instance of monoid_add:
instantiation "marking_ext" :: (monoid_add) monoid_add
begin
  definition
    marking_add_def:
    "M + N =
    ...
end

I can now use the familiar + notation between values of type ('a :: monoid_add) marking_ext, e.g., write M + N.  But I would rather use \<oplus>, writing M \<oplus> N.
Can I change the notation of the typeclass instance, yet stay within the built-in hierarchy of type-classes?

A: You can add additional notation for + on your type, e.g. by introducing an abbreviation:
abbreviation marking_add' :: "marking_ext ⇒ marking_ext ⇒ marking_ext" (infixl "⊕" 65)
  where "(⊕) ≡ (+)"

You can tweak the operator precedence as needed (65 is the one that the normal + has).
Note, however, that introducing additional notation can be problematic if it clashes with notation in other theories. If someone wants to use your development in the future together with some other libraries that also define a notation ⊕, there will be syntax clashes and those can make life a bit harder for that person. There's usually a way to get around it (especially for simple notation like this one), but still: I would usually suggest not to use unnecessary extra notation unless there is a real benefit. In this particular case, I don't really see what the benefit would be. But that's just my advice, feel free to ignore it, of course! :)

A: The above answer gives me what I practically need, however, the /literal/ answer to the question turns out to be that you can change notation for a type class globally using notation:
notation plus (infixl "⊕" 65)

You probably won't want to do that for plus, because if you do, arithmetic takes on your new look:
term "(2 :: nat) + 3"

--> "2 ⊕ 3"
  :: "nat"


text:
Q: ESXI Cannot start up from Virtual IDE Hard Drive After an power outage my ESXi at home cannot boot one of my virtual machines.
When i start the VM I get the following error message:

I already tried to connect via ssh to ESXi and ran vmkfstools -x check HOS-HA-1.vmdk which resulted in Disk is error free.

I have a .vmdk and a -flat.vmdk file.
The system that should be running in the VM is Hass.io (Homeassistant .ova)
Do you have any ideas what I could try to get the VM running again?


text:
Q: Timelike completelness Manifolds Let M be an timelike geodesically complete Lorentizian manifold and $v$ unit timelike vector field. I think that that the flow $F_t$ of this vector field is defined for all $t \in \mathbb{R}$.
Is it true? Someone can help me?

A: I know that a Lorentz manifolds is timelike geodesically complete when all timelike geodesic of $M$ is defined for all values of the parameter t. But i don't know if the flow of every vector field timelike is defined for $t\in \mathbb{R}$.


text:
Q: How to add publisher in Installshield 2018 After I built an installer by Installshield. When I double click to install that software, its publisher shown "Unknown". Does anyone know how to make this field to a signed certs? I do have a signed certs from VeriSign.

A:
Maybe check this first:

*

*Installshield Custom Dialogue Installer

*What is causing to show Publisher to unknown on UAC despite signing exe using signtool.

*Windows Installer Unknown Publisher

It seems you can submit files for malware analysis by Microsoft now. Try it out - it seems this yields "trust" - though I am unsure of any costs involved.

UPDATE: Also check this answer: How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" - a description of a strategy for getting your application and setup trusted.

Microsoft: SmartScreen FAQ (cross-link for safe-keeping).

*

*Trust: SmartScreen is "trust-based" - you gain reputation (or lose it).

*Grapevine: Usage analysis is based on submitted real-world user data from many sources: IE, Edge, Windows, Anti-Virus, download volume, download logs, download URL past history, web-site reputation, etc...

*EV-Certificate: Signing with an EV-certificate buys trust outright. Interesting concept.

*Say What?: Full details and exact mechanism of trust calculation is unknown.

The overall idea is that what is downloaded all the time by many users without major incidents is probably not harmful.

Digital Signing
I am outdated on certificates, but how well signing will work largely depends on the nature of your certificate - whether it points to a valid root certificate already present by default on your users' target computers (a self-signed certificate will not be present by default for example - obviously I guess) and what type of certificate it is (see below regarding EV certificate).
In your case the Installshield help file probably provides the information you need to use the certificate you mention. Here is the online version of that help: Installshield 2018: Digital Signing & Security. I believe your VeriSign certificate should work, if it is up to date (I presume SHA256 - Installshield 2015 upwards) and that it is a valid code signing certificate (as opposed to some other type of certificate).
Root Certificates: Microsoft Trusted Root Certificate Program - Portal (2018)

SmartScreen
Beyond signing, we are now (Windows 8 onwards) dealing with "smart screening" (see sample blocking dialog from Windows Defender). A reputation-based system (see the accepted answer in the linked question as well) with setup / application telemetry data determining if your setup is considered safe - in other words a simple, old-school certificate just isn't enough anymore to gain trust. So they tell me :-).
You can apparently use an EV code-signing certificate to "buy trust" (interesting concept - one would have to say) - it is essentially a more expensive certificate with USB hardware token security and a more rigorous vetting process for the buyer (and there are further details): "Programs signed by an EV Code Signing certificate can immediately establish reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher."
To point out the obvious, the below links are not meant as endorsements:

*

*Microsoft SmartScreen & Extended Validation (EV) Code Signing Certificates

*https://www.digicert.com/code-signing/

*https://www.globalsign.com/en/code-signing-certificate/

*Symantec Extended Validation (EV) Code Signing certificate - Getting Started.

Disclaimer: I am on shaky ground with these issues due to lack of experience, but the provided answer is "best effort" to help get you going. Please do report any important discoveries with comments to the answer or just edit the answer in-situ for the rest of the community (or add your own answer obviously).

Linking Monster: And now, the link-fest. Apologies :-).
Some Further SmartScreen Links For Safekeeping:

*

*How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

*InnoSetup - fails to use global sign EV code signing

*How to pass the smart screen on Win8 when install a signed application?

*How to pass the Windows Defender SmartScreen Protection?

Some Further Certificate Links For Safekeeping:

*

*How to Add a Digital Certificate to a SingleImage Install Shield Installation Program

*Changing the Timestamp Server for Digital Signatures.

*UAC prompt from unidentified publisher appears when uninstalling MSIs on Windows Vista and Windows Server 2008

*Best practice to sign InstallShield setup and include intermediate certificates

*Odd 'Program name' when installing signed msi installer

*Is it possible to define a Windows Installer-uninstaller filename?

*How should I create Trusted Publisher name for my Windows applications (comments)


text:
Q: What happened when javascript engine interpret object literal? Recently I tried to create an object using object literal. And I need a property that use another property in the object. Like this
var object = {
    property1:'property1',
    property2:'property2 is from ' + this.property1
};
console.log(object.property2);// property2 is from undefined

The this.property1 is undefined in the property2.
I do know many ways to deal with this problem. My question is what happens behind the scenes? In other words, how javascript engine interpret object literal? I know "hoisting" happens in the function. Does "hoisting" happens in object literal?
Thanks.

A: That's what happens:
this refers to the scope where your code is running.
The same way in this code:
var a = 42;

var o = {
    key: a
};

a is resolved from the current scope, the this reference in your code is resolved to whatever this refers to "outside" of an object literal. (quotes with "outside" are used since there is no any "inside" or "outside" of literal - all the code runs in the current scope).
So technically your code could be transformed to something like
var a = this;

var object = {
    property1:'property1',
    property2:'property2 is from ' + a.property1
};

or even
var p = this.property1;

var object = {
    property1:'property1',
    property2:'property2 is from ' + p
};

so that some special properties of this did not confuse you.