text:
Q: Connect Epic medical system from mobile app Recently I read Open Epic API.We have a mobile App that just keep users and their family's health records.
Now some of our clients need to share this data to their Epic EHR .I think it is possible to use Epic web services to insert a user records to epic from a 3rd party app.But I did'nt find any more documentation regarding this.
My Questions are here
1)Is it possible to update a a users basic health records from our app to Epic using Open epic web service ?
2)From where i get the Web service documentations ?details like API endpoint , parameters , return types etc
3)What all details i need to connect to an epic account through web service?
Help is highly appreciable,
Thanks,


text:
Q: Given a list of pairs, how to sort them by frequency of the second value? I am trying to sort a pair list such as [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)] by the frequency of the second term in each of the tuples. The resulting sorted list should be something like [(3,3),(5,3),(1,1),(2,1),(2,5)]. In this case, the frequency table would look like 1: 2, 3: 2, 5:1.

A: Using Counter to construct a key to pass to sort or sorted is a natural approach:
from collections import Counter
my_list = [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)]
counts = Counter(y for _,y in my_list)
sorted(my_list,key = lambda p:counts[p[1]],reverse = True)

Which evaluates to:
[(1, 1), (2, 1), (3, 3), (5, 3), (2, 5)]

A: Similar to @John's answer, we can build a frequency map using a collection.defaultdict, then sort by the second value of each tuple using the frequencies from the dictionary, making sure we sort in reverse:
from collections import defaultdict

lst = [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)]

frequency_map = defaultdict(int)
for _, snd in lst:
    frequency_map[snd] += 1

print(sorted(lst, key=lambda x: frequency_map[x[1]], reverse=True))

Output:
[(1, 1), (2, 1), (3, 3), (5, 3), (2, 5)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I make Entangling Shot viable? I love the visual effect and crowd control capabilities of Entangling Shot, but the 75% 90% weapon damage property seems to make it very weak compared to other Demon Hunter primaries such as Hungering Arrow, which does 115%.
Is there a playstyle or rune that makes Entangling Shots more viable?
Update: With the 1.04 patch, the damage of Entangling Shot has been increased from 75% to 90% weapon damage. This certainly helps to make it more viable, but it still seems underused compared to Hungering Arrow, so I believe that the question is still valid.

A: Entangling Shot is made as defensive skill so using it as primary DPS attack isn't really efficient.
You should use it with Chain Gang or Heavy Burden rune as a fight opener to keep enemies at bay and make DPS with your secondary skill.

Shock Collar is offensive rune and it adds more lighting damage but overall it is still out-damaged by other skills.

Bounty Hunter Rune is a good reason for you to use this skill as much as possible since it adds life steal,but i doubt you will need
   so much healing with full group of players.

A: What I didn't realize at first - mainly because the skill description does not really explain it - is that Entangling Shot actually damages 2 enemies per shot (or 4 with the Chain Gang rune). So that's 75% * 2, which suddenly does not seem that bad, especially with the slowing effect. That makes it viable at low levels as a "mini-AoE" weapon, similar to Hungering Arrow. In later levels the slow effect becomes the more important thing, and can really make a difference.
I personally think every Demon Hunter needs some way to slow down enemies. If you're not fond of other slowing skills, this might just be the one for you, though I agree that in the long run this causes less single-target damage than any other DH skill, and less AoE damage than other DH AoE skills.
Frankly, I don't rely on my hatred generator for damage, only for - well - hatred generation :) having it slow multiple enemies at once is a definite plus.

A: Using Entanging Shot as a primary doesn't do as much up-front damage, but it works very well with the Cull The Weak and Steady Aim passives, and also lets Ball Lightning get more ticks off. At level 40/Nightmare, this is by far my preferred build for dealing with anything other than bossfights.

A: In solo scenarios, Entangling Shot is my primary of choice (with Chain Gang rune).  At low levels at least, this coupled with Rapid Fire (while using Steady Aim and Withering Fire) makes quick work of pretty much anything, whether it's single or multi-target.  A couple Entangling Shots gets everything snared, then a full volley of Rapid Fire should kill almost anything.  Once hatred runs out or the enemy (enemies) needs to be re-snared, you use ES (after laying a trap and vaulting away!) to gain hatred while still doing multi-target damage while slowing them down.  I'm only in mid 30's, but this playstyle has worked very effectively for solo-play to this point (I've only died twice, both of which were my first attempts on The Butcher and Belial).

A: I still don't really get why people don't like Entangling Shot. The very first rune makes it a hugely viable killer, and one that stacks well with other passives and gear combos. Whilst it's not perfect as a single target spell, it is great for groups. And most of the time, you'll be facing groups.
4x75% damage is 300% damage. Those hits crit normally, they count as hits for life-on-hit, they can slow/freeze with cold damage (redundant) or take any normal elemental effects (specially on crits). Plus it's free. Actually, it gives you Rage.
What's not to like? You're doing a nice spread of damage that will always slow (those chains go for about half a screen if you keep firing), and can get all your passive effects on four targets by just hitting one. With the slow, you'll find that you have a leapfrogging effect, where the slow wears off one, they jump to the front, get chained, then the pack behind them runs forward and gets slowed in turn. Don't think of it as a 4 man slow, it's really a whole mob, on demand slow with decent damage. I'd have to test it, but I swear I've seen damage numbers from other skills on chained enemies as well sometimes.
You have your Cull the weak passive that makes it do 86.25% damage. Times that by four and it blows away hungering arrow for basic damage as well as being reasonable crowd control.
Try using a hand crossbow with some cold (or lightning) damage and a quiver. Take Entangling Shot w/ Chain Gang, Caltrops w/Bait the Trap, Vault w/ Rattling Roll, and Passives of Archery, Sharpshooter and Cull the Weak. It's a level 54 build, but you'll find that Entangling Shot holds its own pretty well. Drop caltrops, open fire (spread your fire a little), vault away, repeat. It works quite well in Inferno, as long as you have decent fire speed to maintain the slow and don't get too surrounded. Always Vault, hope, Vault again if you do (or use SS if you have it as well). You can also drop Cull the Weak if you want a different passive.
28% or more crit (without any gear at all), plenty of slots open for single damage, escapes (SS) or AoEs, enough slow to consider yourself a bit of a crowd controller. What's not to like?
Entangling shot doesn't do everything, it isn't the best at anything, but it does do everything well enough with just one slot that you could ever want when kiting or AoE'ing to have a place on the taskbar at all times.

A: What I find good about entangling shot is that it has a AoE that with its last rune you can gain life and still slows the enemies down. But if you pair it up with other slow monster skills - like rapid fire with web shot, companion, vault rune with trail of cinders, spike trap scatter, and rain of vengeance flying strike.
Right now I am using brooding, cull the weak and archery. I am able to run through the act with just my demon hunter. And it seems to be doing the trick with high crit chance and damage gear with slow and knockback chances.


text:
Q: How to retrieve the list of dynamic nested keys of BigQuery nested records My ELT tools imports my data in bigquery and generates/extends automatically the schema for dynamic nested keys (in the schema below, under properties)
It looks like this

How can I get the list of nested keys of a repeated record ? so for example I can group by properties when those items have said property non-null ?
I have tried
    select column_name
    from my_schema.INFORMATION_SCHEMA.COLUMNS
    where
        table_name = 'my_table

But it will only list first level keys
From the picture above, I want, as a first step, a SQL query that returns
message
user_id
seeker
liker_id
rateable_id
rateable_type
from_organization
likeable_type
company
existing_attempt
...

My real goal through, is to group/count my data based on a non-null value of a 2nd level nested properties properties.filters.[filter_type]
The schema may evolve when our application adds more filters, so this need to be dynamically generated, I can't just hard-code the list of nested keys.
Note: this is very similar to this question How to extract all the keys in a JSON object with BigQuery but in my case my data is already in a shcema and it's not a JSON object
EDIT:
Suppose I have a list of such records with nested properties, how do I write a SQL query that adds a field "enabled_filters" which aggregates, for each item, the list of properties for wihch said property is not null ?
Example input (properties.x are dynamic and not known by the programmer)

search_id
properties.filters.school
properties.filters.type

1
MIT
master

2
Princetown
null

3
null
master

Example output

search_id
enabled_filters

1
["school", "type"]

2
["school"]

3
["type"]

A: The field properties is not nested by array only by structures. Then a UDF in JavaScript to parse thise field should work fast enough.
CREATE TEMP FUNCTION jsonObjectKeys(input STRING, shownull BOOL,fullname Bool)
RETURNS Array<String>
LANGUAGE js AS """
function test(input,old){
  var out=[]
  for(let x in input){
    let te=input[x];
    out=out.concat(te==null ? (shownull?[x+'==null']:[]) : typeof te=='object' ? test(te,old+x+'.') : [fullname ? old+x : x]  );
  }
  return  out;
  Object.keys(JSON.parse(input));

}
return test(JSON.parse(input),"");
""";
with tbl as (select struct(1 as alpha,struct(2 as x, 3 as y,[1,2,3] as z ) as B) A from unnest(generate_array(1,10*1))
 union all select struct(null,struct(null,1,[999])) )
select *,
TO_JSON_STRING (A ) as string_output,
jsonObjectKeys(TO_JSON_STRING (A),true,false) as output1,
jsonObjectKeys(TO_JSON_STRING (A),false,true) as output2,
concat('["', array_to_string(jsonObjectKeys(TO_JSON_STRING (A),false,true),'","' ) ,'"]') as output_sring,
jsonObjectKeys(TO_JSON_STRING (A.B),false,true) as outpu

 from tbl

A: Have you looked at COLUMN_FIELD_PATHS? It should give you the paths for all columns.
select field_path from my_schema.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS where table_name = '<table>'

[https://cloud.google.com/bigquery/docs/information-schema-column-field-paths]


text:
Q: Finite number of T-invariant subspaces iff the restriction has a finite number of T-invariant subspaces Let $V$ a finite vector space over a field $F$ and let $T\in \mathcal L({V})$ an operator.
$p_m=p_1^{r_1}\cdots p_n^{r_n}$ the minimal polynomial of $T$ and $W_i=\ker(p_i^{r_i}(T))$
$V=\displaystyle \bigoplus_{i=1}^nW_i $ $\hspace{0.4cm}$ by the primary decomposition theorem.
Show that $T$ has a finite number of $T$-invariant subspaces iff $T|_{W_j}$
has a finite number of T-invariant subspaces for every $1 \leq j \leq n$
I was trying to prove it without using cyclic vector.

A: *

*Check that the $W_i$ are $T$-invariant subspaces.

*Check that if $S$ is a $T$-invariant subspace, then so is $S \cap W_i$.

Suppose there are finitely many $T$-invariant subspaces $S_1, \ldots, S_m$ of $V$. Then $S_1 \cap W_i, \ldots, S_m \cap W_i$ are the $T|_{W_j}$-invariant subspaces of $W_j$ (possibly with repeats).

If $S$ is a $T$-invariant subspace of $V$, then check that
$$S = \bigoplus_{i=1}^n (S \cap W_i).$$
If each $W_i$ has finitely many $T|_{W_j}$-invariant subspaces, what does that say about the number of $T$-invariant subspaces of $V$?


text:
Q: Непонятная работа for с else with open('film_list.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    list_films = [line.rstrip('\n') for line in lines]

def movie_search():
    search = input('Введите название фильма/режисёра/год или x для выхода: ')
    for i in range(len(list_films)):
        if search.lower() in list_films[i].lower():
            film = list_films[i].split(", ")
            print(f'Фильм: {film[0]}')
            print(f'Режисcёр: {film[1]}')
            print(f'Страна: {film[2]}')
            print(f'Год: {film[3]}')
        elif search.lower() == 'x':
            print('Спасибо за работу')
            return
    else:
        print('Не нашел данных по этом вводу!')

    return movie_search()

movie_search()

Если цикл for не нашел в списке нужного фильма, он должен отработать else с print('Не нашел данных по этом вводу!'), но почему этот else срабатывает всегда когда находит фильм, вроде бы решение лёгкое, но никак не могу понять что не так :(

A: Кодовый блок в else выполняется после завершения цикла for, то есть после того, как все элементы итерируемого элемента были исчерпаны.
Вот если у вас в цикле сработает break, тогда код в else не будет выполнен

A: for i in range(2):
    print('x')
else:
    print('z')

вывод x, x, z
касательно else:

Когда элементы исчерпаны (например, исчерпана последовательность, либо
итератор возбудил исключение StopIteration) выполняется часть
инструкции, идущая после else (если эта часть присутствует) и цикл
завершается.

в вашем случае вы просто неправильно используете else
сделай проверку if, а не else

A: Верный ответ
with open('film_list.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    list_films = [line.rstrip('\n') for line in lines]

def movie_search():
    search = input('Введите название фильма | режиссера | страну | год или x для выхода: ')
    flag = False
    for i in range(len(list_films)):
        if search.lower() in list_films[i].lower():
            film = list_films[i].split(", ")
            print(f'Фильм: {film[0]}')
            print(f'Режиссер: {film[1]}')
            print(f'Страна: {film[2]}')
            print(f'Год: {film[3]}')
            flag = True
        elif search.lower() == 'x':
            print('Спасибо за работу')
            return
    if flag:
        return movie_search()
    else:
        print('Не нашел данных по этом вводу!')
        return movie_search()

movie_search()

A: else цикла срабатывает всегда, когда цикл дошёл до конца(не встретив break или return)
Соответственно, когда вы нашли фильм, нужно завершить цикл с помощью break или return


text:
Q: Skype corrupted on Windows, not showing Login menu option I had installed Skype on Windows 7 and it was working fine for a while. Recently, I downloaded some other utility for Windows, and it required the MS VC runtime redistributable, which I also installed and ran. It looks like that has caused Skype to stop working. Now when I run Skype, it does not even show me the Login option under the Skype menu.

Earlier when it was working, when I clicked the "Skype" menu shown in the image above, it used to drop down the "Login" or "Connect" menu option, and which, when clicked, would pop up a dialog in which I could login to Skype. Now that Skype menu only shows the "Close" menu option when I click it. Hence no way at all to login.
I uninstalled and reinstalled Skype a couple of times via Control Panel, but there is no change.
Thanks for any advice.

A: Try to uninstall using a third-party tool, such as Revo Uninstaller and Geek Uninstaller. Remove all registry and files that may left behind by the original uninstaller (these two programs help to do that for your).


text:
Q: Can I deploy same Laravel project in main domain and subdomain? I have developed a news website project using laravel 8x for one domain(main domain) Can I use the same project in subdomain? Main domain project frontend will Bangla language and the subdomain project frontend will English. Is it possible? or do I have to install new Laravel apps for the subdomain project?
Also, database will be different.

A: Hi There of course you cant use different databases for same Laravel Project unless you make separate installation for each domain and its subdomain.
Indeed You can use localization in Laravel so you will not have to install 2 copies for the same app
More details about localization here : https://laravel.com/docs/8.x/localization


text:
Q: Difficulty returning some values in C# So I'm going to simplify an assignment I'm working on. I'm sorry if it's crazy bad I'm very new to C#. I should add that the finalMethod call is within Main() and is the only thing in Main().
finalMethod(ifPossible(functionOne()), functionTwo()))

static int functionOne()
    {
        int number;
        Console.WriteLine("Enter a number: ");
        number = int.Parse(Console.ReadLine());
        return number;
    }

static int functionTwo()
    {
        int number;
        Console.WriteLine("Enter a number: ");
        number = int.Parse(Console.ReadLine());
        return number;
    }

static bool ifPossible(int x, int y)
    {
        if (x < y)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

static int finalMethod(bool x)
    {
        if (x == true)
        {
            Console.Write("Success");
        }
        else
        {
            Console.Write("Fail");
        }
    }

My problem is that I need to return the int values from the first two functions into the finalMethod function. This is probably going to require a lot of restructuring but any help would be greatly appreciated.

A: You have a close ) on a wrong place. Try this:
finalMethod(ifPossible(functionOne(), functionTwo()));

Try to do some refactoring like this:
static int getInputValue()
{
    Console.WriteLine("Enter a number: ");
    var input = Console.ReadLine();
    return int.Parse(input);
}

static bool ifPossible(int x, int y)
{
    return x < y;
}

static void finalMethod(bool x)
{
    if (x)
    {
        Console.Write("Success");
    }
    else
    {
        Console.Write("Fail");
    }
}

var number1 = getInputValue();
var number2 = getInputValue();

finalMethod(ifPossible(number1, number2))

A: Couple of things in above code:
1.remove int return  value from finalmethod
2. ifpossible is taking 1 argument it should take two.
    class Program
    {
        static void Main(string[] args)
        {
            SomeClass.finalMethod(SomeClass.ifPossible(SomeClass.functionOne(), SomeClass.functionTwo()));
            Console.ReadLine();
        }
}
    class SomeClass
{
    internal static int functionOne()
    {
        int number;
        Console.WriteLine("Enter a number: ");
        number = int.Parse(Console.ReadLine());
        return number;
    }

    internal static int functionTwo()
    {
        int number;
        Console.WriteLine("Enter a number: ");
        number = int.Parse(Console.ReadLine());
        return number;
    }

    internal static bool ifPossible(int x, int y)
    {
        if (x < y)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    internal static void finalMethod(bool x)
    {
        if (x)
        {
            Console.Write("Success");
        }
        else
        {
            Console.Write("Fail");
        }
    }
}


text:
Q: Best practice for an AJAX call to running C code? I have an underlying C application driving some pretty intensive hardware. I'm currently designing a web interface for the device, the majority of it's function is to present status information to the user. So every second or so, update fields on the web page with pertinent information (temperature, framerate, yada yada...) The device runs linux and has apache. Current setup:

*

*Javascript from the web status page makes an AJAX call (from setInterval)

*PHP file runs, writes to FIFO

*C application reads FIFO, does some work based on input (likely blank, meaning just give me the stats), writes back to FIFO

*PHP file reads from FIFO, parses, json_encode, echo

*Javascript parses JSON and updates page

Here's where you come in... the goal is to take out the PHP middleman. What are the conventions (assuming they exist) for AJAX calls to C programs? Best practice?
Options (as far as I know):

*

*Sockets. Have the C program listen on a particular port. Something similar here.

*Node.js. I'm not familiar with this, I've never used it. But my brief exposure makes me think this may be a great use for it? As I understand it... it's "javascript on the server side", but it's actually C code? Just need some insight here.

*CGI. Can cgi work with a C program that constantly runs? Or does it load up a C program from scratch when called?

*HTML5 WebSockets?

Any insight appreciated. Of course, the best answer is quite possibly not even listed above. That's just the extent of my knowledge in this area. Thanks!

A: We have used the C library libwebsockets (http://libwebsockets.org/) to communicate between JavaScript and a C++ application. In our case we send JSON to and from the C++ backend via websockets.
In your case you could take the same data that you currently send via Ajax and send it to the C program over the websocket. The C program can then generate the same JSON that the PHP program generates and send that back to the JavaScript, again via the websocket.


text:
Q: Does not get Response in HWIOAuthBundle I have successfully installed HWIOAuthBundle. I login to Facebook with this bundle. After a successful login, I get no response. I see a blank screen.
My config file is:
hwi_oauth:
    firewall_name: secured_area
    resource_owners:
        facebook:
            type:          facebook
            client_id:     xxxxxxx
            client_secret: xxxxxxx
            scope:         "email"
            infos_url:     "https://graph.facebook.com/me?fields=id,name,email,picture.type(square)"
            paths:
                email:          email
                profilepicture: picture.data.url

My Security File is:
security:
    providers:
        hwi:
            id: hwi_oauth.user.provider

    firewalls:
        secured_area:
            anonymous: ~
            oauth:
                resource_owners:
                    facebook:      "/login/check-facebook"
                login_path:        /login
                use_forward:       false
                failure_path:      /login

                oauth_user_provider:
                    service: hwi_oauth.user.provider

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }

My Routing file is:
hwi_oauth_redirect:
    resource: "@HWIOAuthBundle/Resources/config/routing/redirect.xml"
    prefix:   /connect

hwi_oauth_login:
    resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
    prefix:   /login

facebook_login:
    path: /login/check-facebook

google_login:
    path: /login/check-google

custom_login:
    path: /login/check-custom

A: Try this in your config:
security:
    providers:
        hwi:
            id: hwi_oauth.user.provider

    firewalls:
        secured_area:
            anonymous: ~
            oauth:
                resource_owners:
                    facebook:      "/login/check-facebook"
                login_path:        /login
                use_forward:       false
                failure_path:      /login
                #new line here
                default_target_path: / #or something else /profile etc.

                oauth_user_provider:
                    service: hwi_oauth.user.provider

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }


text:
Q: Using SOAP/XML-RPC request as a Monitor in JMeter I am using jmeter to submit a few SOAP messages to the application engine. I need a monitor that can collect some of the application engine's performance statistics. But the only option to query the application statistics is to send a different SOAP message to the application.
How can I use a SOAP/XML-RPC request sampler as a monitor? I can't use HTTP request as a monitor since there's no corresponding HTTP service to retrieve monitor results.

A: Actually as per Creating WebService Test Plan it is recommended to use HTTP Request sampler to perform SOAP calls. HTTP Request Sampler has "Use as Monitor" checkbox

Don't forget to add HTTP Header Manager in order to send correct Content-Type and SOAPAction headers.


text:
Q: rsyslog: Discarding Unwanted Messages I have a problem with rsyslog, "stop" doesn't discard messages.
cat /etc/rsyslog.d/10-ignore-user.conf

if $msg contains "" then stop

If I replace "stop" by "/tmp/rsyslog.log" the filtering is ok, I see all message of "username"
For information:

*

*CentOS Linux release 7.4.1708 (Core)

*rsyslog-8.24.0-12.el7.x86_64

*I don't change /etc/rsyslog.conf

*I have another conf file by default    /etc/rsyslog.d/99-listen.conf

$SystemLogSocketName /run/systemd/journal/syslog

I have the same problem with redhat solution
https://access.redhat.com/solutions/1564823
Thanks for your help.


text:
Q: How to Fix Python Selenium Error: 'No Chrome Binary at ...' I'm trying to run the below code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
driver = webdriver.Chrome(service = Service(ChromeDriverManager().install()), options = options)

EDIT
I'm not sure I'm supposed to pass the chrome drive or the actual chrome app as the options argument, but even if I set either of the below (two different locations I have the chrome driver in) I still get the exact same message.
options.binary_location = "C:\\Program Files (x86)\\chromedriver.exe"
options.binary_location = "C:\\Users\\Tom\\Projects_Python\\Instagram_Image_Scraper\\chromedriver.exe"

I get the below error message:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 80, in __init__
    super().__init__(
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/chromium/webdriver.py", line 104, in __init__
    super().__init__(
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 286, in __init__
    self.start_session(capabilities, browser_profile)
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 378, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 440, in execute
    self.error_handler.check_response(response)
  File "/mnt/c/Users/Tom/Projects_Python/Instagram_Image_Scraper/env/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 245, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at C:\Program Files\Google\Chrome\Application\chrome.exe
Stacktrace:
#0 0x56380af48d93 <unknown>
#1 0x56380ad172d7 <unknown>
#2 0x56380ad3d3b2 <unknown>
#3 0x56380ad3ba3d <unknown>
#4 0x56380ad804f4 <unknown>
#5 0x56380ad77353 <unknown>
#6 0x56380ad46e40 <unknown>
#7 0x56380ad48038 <unknown>
#8 0x56380af9c8be <unknown>
#9 0x56380afa08f0 <unknown>
#10 0x56380af80f90 <unknown>
#11 0x56380afa1b7d <unknown>
#12 0x56380af72578 <unknown>
#13 0x56380afc6348 <unknown>
#14 0x56380afc64d6 <unknown>
#15 0x56380afe0341 <unknown>
#16 0x7f1c05443609 start_thread

My chrome version is: Version 110.0.5481.97 (Official Build) (64-bit)
Machine: Windows 11
I tried to assign the Chrome web driver to the variable 'driver' but it's giving me an error, I'm expecting to pass a web driver to the 'driver' variable so I can start pulling and scraping web pages.
Alternatives tried:

*

*I tried to use a raw string to pass the chrome application location into the web driver, but this didn't work.

*I tried to use the Firefox driver, but I see a similar issue about not having a binary.

Can anyone please help?

A: *

*Try forward slash(//) instead of backslash(\) as below:

options.binary_location = "C://Program Files//Google//Chrome//Application//chromedriver.exe"

*

*Try by passing the chromedriver.exe rather than chrome.exe
options.binary_location = "<full path here>//chromedriver.exe"
In case you do not have a chrome driver, here is the download link


text:
Q: Normalize scipy sparse matrix with number of nonzero elements I want to divide each row of the csr_matrix by the number of non zero entries in that row.
For example : Consider a csr_matrix A:
A = [[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]]
Result = [[3, 0, 0, 2, 0], [1, 6, 0, 3, 0]]

What's the shortest and efficient way to do it ?

A: Get the counts with getnnz method and then replicate and divide in-place into its flattened view obtained with data method -
s = A.getnnz(axis=1)
A.data /= np.repeat(s, s)

Inspired by Row Division in Scipy Sparse Matrix 's solution post : Approach #2.
Sample run -
In [15]: from scipy.sparse import csr_matrix

In [16]: A = csr_matrix([[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]])

In [18]: s = A.getnnz(axis=1)
    ...: A.data /= np.repeat(s, s)

In [19]: A.toarray()
Out[19]:
array([[3, 0, 0, 2, 0],
       [1, 6, 0, 3, 0]])

Note: To be compatible between Python2 and 3, we might want to use // -
A.data //=  ...

A: Divakar gives an in-place method. My trial creates a new array.
from scipy import sparse
A = sparse.csr_matrix([[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]])
A.multiply(1.0/(A != 0).sum(axis=1))

We multiply the inverse values of the sum of non-zero parts in each row. Note that one may want to make sure there is no dividing-by-zero errors.
As Divakar pointed out: 1.0, instead of 1, is needed at A.multiply(1.0/...) to be compatible with Python 2.


text:
Q: Setting private variables using a getter What's the need for a separate get and set function if it's possible to combine them, like this:
class A {
private:
    int var = 0;
public:
    int& getset(){ return var; };
};

int main()
{
  A a = A();
  a.getset() = 4;
  std::cout << "Hello, " << a.getset() << "!\n";
}

I'm assuming there's something I've overlooked, but in case this is not a good idea; why is it possible to access private members this way?

A: There is no need for getters and setters at all: just make the variable public.
class A {
public:
    int var = 0;
};

If you want to hide implementation details, then the idea is that the getter is const while the setter is not. So they must be different functions
class A{
public:
    int getValue() const;
    int setValue(int new_value); // returns old value
private:
    /* implementation details: Value may be encoded other than in a simple variable */
};

A: if you don't need in any checks of values, than you should replace class to struct and remove unnecessary method:
struct A {
    int var = 0;
};

int main()
{
  A a;
  a.var = 4;
  std::cout << "Hello, " << a.var << "!\n";
}

But if you need in more difficult logic and some checks of var, than you should write separate setter and getter, not like yours. getset() is terrible idea, don't do it again.


text:
Q: bzr and zfs/zpool.cache I use Xubuntu 18.04 with zfs and etckeeper.
I added zfs/zpool.cache to .bzrignore via
vi /etc/etckeeper/update-ignore.d/01update-ignore
etckeeper update-ignore

But bzr keeps on adding/committing  zfs/zpool.cache
Does anyone know a way to handle this?

A: zpool.cache is probably not a part of the ignores that is added by "etckeeper update-ignore". You can manually get bzr to ignore it by running:
 bzr remove --keep zfs/zpool.cache
 bzr ignore zfs/zpool.cache


text:
Q: Clickable images in a canvas I am trying to make the images inside a canvas clickable, but I am confused on how to go about that, here is what I have currently, I just want pictures[0] to be clickable and that alert to occur once it is clicked, but for some reason it is not working. How can i make it so that when picture[0] is clicked the alert goes off.
 var images = document.getElementsByTagName("img");
 var c=document.getElementById("myCanvas");
 var ctx=c.getContext("2d");
 var left = c.offsetLeft;
 var top = c.offsetTop;
 var pictures = [];
  //wheel
 pictures[0] = new Image();
 pictures[0].src = 'images/Layer8.png';
//bg
 pictures[1] = new Image();
pictures[1].src = 'images/Layer0.png';
//gear
 pictures[2] = new Image();
pictures[2].src = 'images/Layer7.png';
 //speed
 pictures[3] = new Image();
pictures[3].src = 'images/Layer14.png';
//dial1
pictures[4] = new Image();
pictures[4].src = 'images/Layer18.png';
//dial2
 pictures[5] = new Image();
pictures[5].src = 'images/Layer16.png';
//dial3
 pictures[6] = new Image();
 pictures[6].src = 'images/Layer17.png';

 c.addEventListener('click', function(event){
    var x = event.pageX - left,
    y = event.pageY - top;
    pictures.forEach(function(fx,fy,fwidth,fheight,x,y) {
    if (y > fy && y < fy + fheight
        && x > fx && x < fx + fwidth) {
        alert('clicked an element');
    }
});
}, false);

function load(){
ctx.drawImage(pictures[1],0,0);
ctx.drawImage(pictures[2],468,263);
ctx.drawImage(pictures[3],89,77);
ctx.drawImage(pictures[4],146,153);
ctx.drawImage(pictures[5],278,153);
ctx.drawImage(pictures[6],206,119);
ctx.drawImage(pictures[0],fx,fy,fwidth,fheight);

}
var fx = 84;
var fy = 60;
var fwidth = 283;
var fheight = 276;

window.onload = load;

A: Ok I understand what you are trying to do.  Unfortunately, images in the canvas are not DOM elements, only the canvas itself is one. This means using jQuery you can call:
$('#myCanvas').on('click', function() {});

or natively:
c.addEventListener('click', function(){});

However, the fabricjs.com library may prove to be useful to you in this case.


text:
Q: Groupby.transform doesn't work in dask dataframe i'm using the following dask.dataframe AID:
   AID FID  ANumOfF
0    1   X        1
1    1   Y        5
2    2   Z        6
3    2   A        1
4    2   X       11
5    2   B       18

I know in a pandas dataframe I could use:
AID.groupby('AID')['ANumOfF'].transform('sum')

to get:
0     6
1     6
2    36
3    36
4    36
5    36

I want to use the same with dask.dataframes which usually uses same functions as a pandas dataframe, but in this instance gives me the following error:
AttributeError: 'SeriesGroupBy' object has no attribute 'transform'

It could either be one of two things, either that dask doesn't support it, or it's because I'm using python 3?
I tried the following code:
AID.groupby('AID')['ANumOfF'].sum()

but that just gives me the sum of each group like this:
AID
1     6
2    36

I need it to be as the above where a sum is repeated in each row. My question is, if transform isn't supported, is there another way I could achieve the same result?

A: I think you can use join:
s = AID.groupby('AID')['ANumOfF'].sum()
AID = AID.set_index('AID').drop('ANumOfF', axis=1).join(s).reset_index()
print (AID)
   AID FID  ANumOfF
0    1   X        6
1    1   Y        6
2    2   Z       36
3    2   A       36
4    2   X       36
5    2   B       36

Or faster solution with map by aggregate Series or dict:
s = AID.groupby('AID')['ANumOfF'].sum()
#a bit faster
#s = AID.groupby('AID')['ANumOfF'].sum().to_dict()
AID['ANumOfF'] = AID['AID'].map(s)
print (AID)
   AID FID  ANumOfF
0    1   X        6
1    1   Y        6
2    2   Z       36
3    2   A       36
4    2   X       36
5    2   B       36

A: Currently Dask supports transform , howerver there may be an issues with indexes (depending on original dataframe). see this PR #5327
So your code should work

AID.groupby('AID')['ANumOfF'].transform('sum')


text:
Q: Recommendation: Migrating PostgreSQL data 2 WordPress I search for easiest way for migrating from custom CMS builded upon PostgreSQL to WordPress CMS.
I don't search for ready-quick answer, but some guidance, approach explanation etc.
Also, if someone here is sure that his approach is successful, then we can work together (with some money arrangement).
Thank you


text:
Q: Coin and steps -Probabilty and Statistics Turn a coin and if it falls heads move three places to the right otherwise move 2 places left.
After 20 times you turn the coin, in what positions might you be and what is the probability to be in each of them?
Also calculate the expected position at the end of the process.
I really need some help with this problem...

A: Would it help to think about this exercise:
Move $\frac12$ place to the right, flip the coin, and then move $2\frac12$ places right or left, depending on the result of the flip.  Repeat 20 times.

A: Hint:  what is the furthest right you can be?  What is the furthest left?  Note that your final location only depends on how many heads/tails you get, not the sequence.  How much does it change if you change a head to a tail?  Can you now describe the possible ending locations?  What is the expected number of heads out of $20$ flips?

A: If you get $N$ heads, you'll get $20-N$ tails, so the position after $20$ tosses with $N$ heads is $X(N) = 3N - 2(20-N) = 5N - 40.$
There are $20 \choose N$ ways to get $N$ heads with $20$ (fair) coin tosses, and $2^{20}$ possible outcomes (including order).  So the probability of getting exactly $N$ heads is
$$P(N) = \frac{20 \choose N}{2^{20}}.$$
The most probable position is $X(10) = 5(10) - 40 = 10.$


text:
Q: C# ListView image icon size The icons in the ListView in C# are very small by default (probably 16x16px). How can I increase the size of these icons?
I tried making the source images in the ImageList larger, and also tried using the LargeImageList property, but to no avail.
I'm using C#, WinForms and .net 4.0.

A: The trick is in modifying the ImageSize propertiy of the ImageList (who would've thought)?
        listView1.View = View.LargeIcon;

        ImageList iList = new ImageList();
        iList.ImageSize = new Size(64, 64);
        iList.ColorDepth = ColorDepth.Depth32Bit;

        listView1.LargeImageList = iList;

As a bonus, remember to set the View property of the ListView to be LargeIcon and also increase the ColorDepth (if you so desire).

A: Use the LargeImageList property:
https://msdn.microsoft.com/en-us/library/system.windows.forms.listview.largeimagelist%28v=vs.110%29.aspx


text:
Q: Insert return value from dll method into HTML input I need to create a button that will call a method on a dll that is installed on the client and insert the return value into a form on an Intranet web page. I started creating a plugin for IE, but Microsoft is no longer supporting IE and Edge currently has no support for plug-ins. I thought maybe a Chrome extension, but Google is phasing out NPAPI support. Other browsers are not an option. What can I do to achieve this?

A: What I ended up doing was to create a "Native messaging host" console app that makes the call to the dll method. Then I made a Chrome extension that uses Native Messaging to communicate with the console app.
Supposedly, once Microsoft Edge supports extensions, it will be able to use extensions that were made for Chrome and Firefox too.


text:
Q: Information on what .captain.picard * #riker means for CSS I'm wondering what .captain.picard * #riker means. I'm pretty sure it means that any HTML element with class "captain picard" (a div for example) has everything inside it selected, and then in that everything selected all html elements with id "riker" are selected and styled. For example:

One

Two

Three

.captain.picard * #riker {
  color: red;
}

Then the word One should be styled, red, right? Doesn't happen. I'm confused as to why this is... if I take away the #riker selector, then all the tags word are styled red which makes complete sense. Can anybody help?

A: Just remove *, that means 'all elements'. Look how it works

.captain.picard #riker {
  color: red;
}

.captain.picard2 * {
  color: blue;
}

One

Two

Three

One

Two

Three

A: You have to removed the * as it stands for every possible element which would be between the element with the class and the id

A:
I'm pretty sure it means that any HTML element with class "captain picard" (a div for example) has everything inside it selected, and then in that everything selected all html elements with id "riker" are selected and styled.

That would be either .captain.picard *#riker (notice the space after the * is omitted), or just .captain.picard #riker.
Separating the * and id selector with a space represents two different elements, with the * being the ancestor. Add that to .captain.picard (and its descendant combinator) and you have three levels of nesting, which doesn't match the structure here.

A: oky lets be clear if you want to style only one div item you don't need to use *
simply use
  .captain  #riker {
  color: red;
  }

one class selector is fine
.picard  #riker {
 color: red;
  }

will do the same
but if you want to select all the elements under captain class then you can use *
for example
.captain  * {
color: green;

}

A: By using class like this
 .captain.picard  #riker what you have said can be accomplished i.e., within class '.captain.picard' all the id with  '#riker' changes as per style given.

.captain.picard  #riker {
  color: red;
}

One

Two

Three

four

A: Your Code:

One

Two

Three

When CSS is: .captain.picard * it goes till piecard and then targets all selectors below it. If this is written - everything below will be in red color.

// When CSS is: .captain.picard * #riker it goes till piecard and then targets all selectors below it and tries to find #riker as a child of all but doesn't finds one. Hence no red.

But, as per your CSS.
When .captain.picard * #riker it goes till piecard and then targets all selectors below it and tries to find #riker as a child of all (in this case, .something).
It finds #riker in child of *
Hence Color is Red:
or you could target is as .captain.picard *#riker
But you could easily do this without adding * as well.
Simply:
you wrote 3 level of CSS hierarchy (because you added space after * and before #riker), but in HTML - there are only two level hierarchy. Unless you add an intermediate level in your HTML, your css won't get its target.

.captain.picard * #riker {
  color: red;
}

One

Two

Three


text:
Q: Name for incrementally calculating a mean If μ = 4 and n = 2 and suddenly I have a new datum of 22 I can add 1 to n and recalculate μ as (4*2+22)/3 = 10 without even looking back at the old data. This can be used as an optimization to reduce recalculations as data grows.
But does it have a name? Ideally a name that would drive someone to a definition of the function I just used. What's a good way to describe this?
Looking for something to say to coders who didn't exactly master statistics.

A: You are looking for online-algorithms:

Online algorithms refer to computations that are performed iteratively, with data arriving during the computation. Online learning are methods which works when the data arrives.


text:
Q: Create a text and animate it downwards until it goes out of screen I am making an application and i need to create a line of text every second and then animate it downwards until it goes out of screen. This will go on like this forever. What kind of algorithm can i use?
I'm using canvas.drawtext to create the text.

A: protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    canvas.drawText(text, x, y, paintObject);

            if(y< canvas.getheight()){
                y += 10;
            }else{
                y = 0;
            }
            invalidate();
}

Invalidate makes the method run over and over again. Not sure if this will work since I am a beginner myself. But what it will do is when it will go out of the screen the text will appear above and will repeat doing it.

A:     try this..

    package com.example.animationsample;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.animation.Animation;
    import android.view.animation.AnimationUtils;
    import android.view.animation.Animation.AnimationListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity implements AnimationListener {

        TextView txtMessage;
        Button btnBlink, btnfadeout, btnfadein, btnzoomin, btnzoomout, btnmove,
                btnslideup, btnslidedown, btnroate, btnbounce, btnsequential,
                btntogether;

        // Animation
        Animation animFadein, animBlink, animfadeout, animzoomin, animzoomout,
                animmove, animslideup, animslidedown, animroate, animbounce,
                animsequential, animtogether;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            txtMessage = (TextView) findViewById(R.id.txt1);
            btnBlink = (Button) findViewById(R.id.btnblink);
            btnfadeout = (Button) findViewById(R.id.btnfadeout);
            btnfadein = (Button) findViewById(R.id.btnfadein);
            btnmove = (Button) findViewById(R.id.btnmove);
            btnzoomin = (Button) findViewById(R.id.btnzoomin);
            btnzoomout = (Button) findViewById(R.id.btnzoomout);
            btnroate = (Button) findViewById(R.id.btnrotate);
            btnslidedown = (Button) findViewById(R.id.btnsliddown);
            btnslideup = (Button) findViewById(R.id.btnslideup);
            btnsequential = (Button) findViewById(R.id.btnsquential);
            btntogether = (Button) findViewById(R.id.btntogether);
            btnbounce = (Button) findViewById(R.id.btnbounce);

            // load the animation
            animFadein = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.fade_in);
            animBlink = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.blink);
            animbounce = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.bounce);
            animfadeout = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.fade_out);
            animmove = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.move);
            animroate = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.rotate);
            animslideup = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.slide_up);
            animslidedown = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.slide_down);
            animsequential = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.squential);
            animtogether = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.together);
            animzoomin = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.zoom_in);
            animzoomout = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.zoom_out);

            // set animation listener
            animFadein.setAnimationListener(this);
            animfadeout.setAnimationListener(this);
            animzoomout.setAnimationListener(this);
            animsequential.setAnimationListener(this);
            animslidedown.setAnimationListener(this);
            animslideup.setAnimationListener(this);
            animbounce.setAnimationListener(this);
            animmove.setAnimationListener(this);
            animtogether.setAnimationListener(this);
            animroate.setAnimationListener(this);
            animBlink.setAnimationListener(this);

            // button click event
            btnBlink.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animBlink);
                }
            });
            btnbounce.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animbounce);
                }
            });
            btnfadein.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animFadein);
                }
            });
            btnfadeout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animfadeout);
                }
            });
            btnsequential.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animsequential);
                }
            });
            btnslidedown.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animslidedown);
                }
            });
            btnslideup.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animslideup);
                }
            });
            btnzoomin.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animzoomin);
                }
            });
            btnzoomout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animzoomout);
                }
            });
            btnmove.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animmove);
                }
            });
            btnroate.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    txtMessage.setVisibility(View.VISIBLE);

                    txtMessage.startAnimation(animroate);
                }
            });

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            // Take any action after completing the animation

            // check for fade in animation
            if (animation == animFadein) {
                Toast.makeText(getApplicationContext(), "Animation Stopped",
                        Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub

        }

    }

    layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btnrotate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="37dp"
        android:text="rotate" />

    <Button
        android:id="@+id/btnsliddown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnrotate"
        android:layout_toLeftOf="@+id/btnmove"
        android:text="slidedown" />

    <Button
        android:id="@+id/btnsquential"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnsliddown"
        android:layout_alignLeft="@+id/btnsliddown"
        android:text="squential" />

    <Button
        android:id="@+id/btnfadein"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnsquential"
        android:layout_alignRight="@+id/btnzoomin"
        android:layout_marginBottom="26dp"
        android:text="fadein" />

    <Button
        android:id="@+id/btnmove"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnslideup"
        android:layout_marginLeft="53dp"
        android:layout_toRightOf="@+id/btnfadeout"
        android:text="move" />

    <Button
        android:id="@+id/btnzoomout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnmove"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="19dp"
        android:text="zoomout" />

    <Button
        android:id="@+id/btnslideup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnzoomout"
        android:layout_alignRight="@+id/btnmove"
        android:text="slideup" />

    <Button
        android:id="@+id/btnzoomin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnmove"
        android:layout_alignRight="@+id/btnmove"
        android:text="zoomin" />

    <Button
        android:id="@+id/btnbounce"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnsquential"
        android:layout_centerVertical="true"
        android:text="bounce" />

    <Button
        android:id="@+id/btnfadeout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnbounce"
        android:layout_alignLeft="@+id/btnblink"
        android:text="fadeout" />

    <Button
        android:id="@+id/btnblink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnfadeout"
        android:layout_alignRight="@+id/txt1"
        android:text="blink" />

    <Button
        android:id="@+id/btntogether"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnfadeout"
        android:layout_alignRight="@+id/btnfadein"
        android:text="together" />

</RelativeLayout>


text:
Q: How to use same Choices for all Questions in Django's Polls app Sub: Django Poll Project.

There can anyone please help me understand to use same set of choices against all questions. I don't want to add choices every time for each question, instead I want to add question with date- time stamp and want that choices which are already added should reflect for my questions and I select any of those choices and vote.
2nd Option I want to work is if I want to add another choice it should allow but it should show all other choices against my question.
Thank You
Rishipal


text:
Q: Sprite Kit Button touch location error | Swift I'm trying to make a button that's an SKLabelNode. When it gets pressed, it's supposed to change scenes, but there is something wrong with the line where location is declared.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)

    let location = touches.locationInNode(self)
    let touchedNode = self.nodeAtPoint(location)

    if touchedNode.name == "startGameButton" {
        let transition = SKTransition.revealWithDirection(SKTransitionDirection.Down, duration: 1.0)

        let scene = GameScene(size: self.scene.size)
        scene.scaleMode = SKSceneScaleMode.AspectFill

        self.scene.view.presentScene(scene, transition: transition)
    }
}

The error is here on the line.
let location = touches.locationInNode(self)

It reads

'Set< NSObject>' does not have a member named 'locationInNode'

I'm not sure how to fix it. I've looked at a lot of working button templates, but mine always has an error.

A: The problem is exactly what the error states - Set<NSObject> doesn't have a method named locationInNode. What you need to do is retrieve an object out of the Set; check it's a UITouch object; if it is, you can use it to get a touch location. Try:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let location = (touches.first as? UITouch)?.locationInNode(self) {
        // ...
    }
}

Or
if let touch = touches.first as? UITouch {
    let location = touch.locationInNode(self)
    // ...
}

A: To fix it, this is the default fix, it just enumerates through all the touches.
for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        node = self.nodeAtPoint(location)
        //do something
}


text:
Q: sqlalchemy group_by error The following works
s = select([tsr.c.kod]).where(tsr.c.rr=='10').group_by(tsr.c.kod)

and this does not:
s = select([tsr.c.kod, tsr.c.rr, any fields]).where(tsr.c.rr=='10').group_by(tsr.c.kod)

Why?
thx.

A: It doesn't work because the query isn't valid like that.
Every column needs to be in the group_by or needs an aggregate (i.e. max(), min(), whatever) according to the SQL standard. Most databases have always complied to this but there are a few exceptions.
MySQL has always been the odd one in this regard, within MySQL this behaviour depends on the ONLY_FULL_GROUP_BY setting: https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html
I would personally recommend setting the sql_mode setting to ANSI. That way you're largely compliant to the SQL standard which will help you in the future if you ever need to use (or migrate) to a standards compliant database such as PostgreSQL.

A: What you are trying to do is somehow valid in mysql, but invalid in standard sql, postgresql and common sense. When you group rows by 'kod', each row in a group has the same 'kod' value, but different values for 'rr' for example. With aggregate functions you can get some aspect of the values in this column for each group, for example
select kod, max(rr) from table group by kod
will give you list of 'kod's and the max of 'rr's in each group (by kod).
That being sad, in the select clause you can only put columns from the group by clause and/or aggregate functions from other columns. You can put whatever you like in where - this is used for filtering. You can also put additional 'having' clause after group that contains aggregate function expression that can also be used as post-group filtering.


text:
Q: Would a transistor be the correct device? I am going to create the following circuits. However I need to be able to have a switch that completes the lightbulb circuit when VM1 input > 4.3v
I think a transistor may be the answer from what I have read. Please could someone give me some help. I have thought about using a relay, but this just seems to mess up the voltage to VM1
Any help is greatly appreciated.

simulate this circuit – Schematic created using CircuitLab
I believe this is the solution I was looking for. Please read this carefully before testing. POT's R1 & R2 are attached to the same wiper, so what happens to one must happen to the other. The switch SW1 is a push to break switch.
Please could you tell me if the resistors I have selected are compatible with the zener diodes I have selected. Thank you.

simulate this circuit

A: You can use a comparator to pull this off in the most flexible way. One method is to connect a known voltage reference (say from a precision Zener reference) to the minus input of the comparator, and then a voltage-divided version of VM1 to the positive input. You would select the divider values such that VM1 * divider ratio allows a voltage of 4.3V at VM1 to become a voltage of reference + a few mV. When that condition is true, the comparator will output a '1' that can be used to directly drive the gate of a transistor or some other transistor / relay circuit.
If your 5V rail is fairly stable, you could use that as your reference input by dividing it down via divider and feeding it to the minus input as well, saving the external reference.
The comparator can likely be powered off your existing 5V rail as well. Common models include the LM311. You may see a difference between open-drain and push-pull models; the open-drain types will only ever pull down actively; otherwise the output value floats to whatever you pull it too. A push-pull will actively drive high and low.
Finally, you can leave a resistor option between the output and - input to allow you to tune hysteresis in the future.
Option two (to avoid the comparator) is to use a precision analog MOSFET (from ALD, for example) with a very tight threshold voltage. Fed with a divider,  this can then trigger other devices to turn on the lamp.

A: Transistor is the correct answer but to get good control over this 4.3V threshold you may want something more than a simple transistor. Something like this:

simulate this circuit – Schematic created using CircuitLab
The LM393 in the middle is a comparator chip with open-collector output, comparing your input voltage against the reference voltage generated from the Zener diode D1 1N4731A (a 4.3V Zener diode, with R1 providing its 58mA current from a 5V supply) and shifting the signal level of 5V to 12V as required by the lamp with the pull-up resistor R3. The comparator outputs logic low when voltage on the "-" input is higher than "+" input, and high impedance (or logic high on a normal comparator, since LM393 in particular have an open-collector output) otherwise. The MOSFET M1 (any P-channel MOSFET will work here, IRF4905 is just my personal favorite) switches the lamp from the high side when it sees a low input at its gate, which is tied to the output of the comparator.

A: The "4.3V threshold with 5V supply" is a bit trippy - as it enables a tricky yet simple solution here, leveraging the fact that BJT start to conduct reliably when there is 0.7V between base and emitter.

simulate this circuit – Schematic created using CircuitLab
This circuit leverages this fact: when VIN is lower than 4.3V, Q1 start to conduct and pull the gate voltage of M1 up. Then it would start conduct and ground the gate of M4, shutting the lamp off. When VIN is higher than 4.3V Q1 cuts off, and in turn M1 cuts off, and in turn M4 switches on, allowing the lamp to be on.
What you see here is in fact a open-drain dual-supply level-shifting logic inverter with a threshold voltage of about 0.7V below low-side supply. The lamp have one of its ends tied high so it lights up when the circuit outputs low.


text:
Q: centos locale utf-8 This is my linux box:

*

*CentOS Linux release 6.0 (Final)

*x86_64

Using a text editor (vi, or pico...) I see strange characters for accented letters (è, ì, à, ù)
This is my locale:
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

If I switch to iso-8859-9 like this:
export LANG="en_US.ISO-8859-1"

I see the characters correctly, but I must use utf-8 on this server.
Any idea?

A: Your description is vague. Either your terminal does not support Unicode, or you're editing a file that's in latin1 (= iso-8859-1).
On a bash or zsh shell, with LC_CTYPE=en_US.UTF-8, run echo $'\xc3a9'. If you see é, your terminal supports UTF-8. If you see é, your terminal is showing latin1.
If your terminal doesn't support UTF-8, you need to get one that does. Or, possibly, configure yours so that it does.
If you determine that your terminal supports UTF-8, but you see things like é when you display a file that contains é, then the problem is that your files are encoded in latin1. Recode them to UTF-8.


text:
Q: Hibernate Criteria - Multiple joins on the same table I'm attempting to recreate the following piece of SQL in hibernate criteria.
select id from A join B b1 on b1.a_id = a.id and b1.name = "Some name"
                 join B b2 on b2.a_id = a.id and b2.name = "Some other name"
                 ...join B bN on bN.a_id = a.id and bN.name = "...."

The goal of which is to find only ids from A where it has all of the sought after names in table B.
I tried to use multiple aliases, but it complains about a duplicate association path on the collection.
I'm using criteria because I need this to be extensible out to N (where N is some small integer) and I've enjoyed using it in the past but I'm just completely stuck on how to get this to behave. Everything I've tried generates a single join - which doesn't produce proper results.
I'm also open to other suggestions of how to get this to work.. but if I can get away with criteria that'd be helpful.
I ended up solving this problem through the use of detached criteria and subqueries. It's not extremely efficient, but it is very very flexible.
The problem was that I had to find ids from A where some subset of its related tables B C D's had field values equal to some contains search list. The solution does 1 query for every new point where there would have been a join. The end result looks something like
Select id from A where A.id in (Select id from B where B.val in (1,2,3)) or A.id in (Select id from C where c.val in (1,2,3,4))...


text:
Q: Cascade Delete on Lookup in Unmanaged Package Salesforce has the option to enable cascade deletion for lookup relationships.  Thus, if you delete the parent in the lookup, the child will also be deleted.  However, this option must be enabled on a per-organization basis.
If I enable this option in an unmanaged package (so the option is enabled on that org), will the lookup still be cascade delete on any orgs that install the package (Even if that org has not specifically asked Salesforce to enable it)?
If not, what will happen?  Will the lookup be converted to "clear field when parent object is deleted", or will an error occur when I attempt to install the package?

A: Just because you had Cascade Delete enabled in the Org where your Unmanaged Package was created will not somehow transfer this setting to an Org where your Unmanaged Package is installed. If that happened it would be a disaster for the destination Org. There is no place in the Unmanaged Package metadata to store this setting and transfer it anyway. If you want your Unmanaged Objects to behave this way after Package Install I would use Master-Detail relationships. HOWEVER I have not actually tried this and as we all know sometimes Salesforce does surprising things.

A: I still don't have the resources to check with unmanaged packages.
However, using change sets you can move a cascade-delete lookup field from an org that has the option enabled to an org that does not.
The transferred field will maintain its cascade-delete status, and the recipient org will not have the option enabled. If the field is later changed from being cascade-delete, the option cannot be re-enabled without using a change set again.
NB: Third-party tools might choke on this operation.  At the very least, ClickDeploy.io will not allow the change to happen, giving an error telling you to enable the option on the recipient org first.


text:
Q: Ipe extensions (ipelets) I'm using ipe to draw a lot of figures and I find out that I can, for example, plot some functions.
What extensions do you use in Ipe? There are some already installed when we download it, but are there others useful?
Thanks!

A: *

*A list of useful ipelets by IPE author: https://github.com/otfried/ipe-wiki/wiki/Ipelets

*Creation of plots of functions (the most important from the list above): https://github.com/lahvak/ipeplots

*Useful stylesheets for paper sizes, dash styles, transparency and fonts: https://www.sthu.org/misc/ipe.html

*Electrical Engineering plots: https://github.com/christiankral/ElectricalEngineering.isy

*Gradients and additions: https://alga.win.tue.nl/tutorials/ipe/


text:
Q: Rolling $n$ $k$-sided dice and discarding the lowest $m$ of them. In this question I will use the notation $\Bbb{E}(n,k,m)$ to refer to the expected average of rolling $n$ $k$-sided dice and discarding the lowest $m$ of them.

The most trivial response happens when $m = 0$, in which case we discard no dice and we arrive at the result:
$$\Bbb{E}(n,k,0) = \frac{k}{2} + \frac{1}{2}$$

When $m = 1$, I considered a sample case to give some intuition for this problem. Looking at the case of $\Bbb{E}(2, 6, 1)$, I found the following pattern.

There are one $1$s, three $2$s, five $3$s, etc.
The sum of these outcomes is:
$$\sum_{i=1}^{6} i(2i-1)$$
In general, the expected outcome for $\Bbb{E}(2,k,1)$ is:
$$\frac{\sum_{i=1}^{k} i(2i-1)}{k^2} = \frac{\sum_{i=1}^{k} 2i^2 - \sum_{i=1}^{k} i}{k^2} = \frac{\frac{2k(k+1)(2k+1)}{6} - \frac{k(k+1)}{2}}{k^2} = \frac{2}{3}k + \frac{1}{2} - \frac{1}{6k}$$

Now I want to consider $\Bbb{E}(3,k,2)$. In the previous case each value $i$ occurred $2i - 1$ number of times. Where did $2i - 1$ come from?
It looks like the frequency of occurrence is the difference of consecutive squares.
$$i^2 - (i-1)^2 = 2i - 1$$
This seems intuitive based on the image I provided. We can reason that in the case of $n = 3$, the frequency of occurrence will be the difference of consecutive cubes.
$$i^3 - (i-1)^3 = 3i^2 - 3i + 1$$
The expected outcome of $\Bbb{E}(3,k,2)$ is messy, so I'll just write the initial expression and the simplified expression.
$$\frac{\sum_{i=1}^{k} i(3i^2-3i+1)}{k^3} = \frac{3}{4}k + \frac{1}{2} - \frac{1}{4k}$$

Let's finally look at the case of $\Bbb{E}(n,k,n-1)$. Based on the previous results, I conjecture that it looks like:
$$\frac{\sum_{i=1}^{k} i(i^n - (i-1)^n))}{k^n} = \frac{n}{n+1}k + \frac{1}{2} - \mathcal{O}(\frac{1}{k})$$
My two questions are this:

*

*Is my conjecture for $\Bbb{E}(n,k,n-1)$ correct, and if so, how can I prove this?

*What happens when $m \ne n-1$? How can I adjust my analysis to account for discarding dice such that I leave not just the maximum value?

A: If $M$ is the maximum value on the $n$ dice thrown, then $\mathbb{P}(M\leq x)=(x/k)^n$ so that $\mathbb{E}(M)=\sum_{x=0}^{k-1} \left(1-\left({x\over k}\right)^n\right)=k-{1\over k^n}\sum_{x=0}^{k-1}x^n.$ Using Faulhaber's formula you can show that
$$\sum_{x=0}^{k-1}x^n
={1\over n+1}\left[k^{n+1}-{1\over 2}(n+1)k^n+O(k^{n-1})\right]$$
and putting these together gives, as you expected,
$$\mathbb{E}(M)={n\over n+1}\,k+{1\over 2}+O(1/k).$$

Here is a more general argument. For any $1\leq j\leq n$ let $X_{(j)}$ be the $j$th order statistic of the $n$
dice rolls. For $0\leq x<k$, let $Y$ be the number of dice rolls that take
values in $\{1,2,\dots, x\}$. We have $X_{(j)}>x$ if and only if $Y<j$ so that
$$ \mathbb{P}(X_{(j)}>x)=\mathbb{P}(Y<j)=\sum_{y=0}^{j-1}{n\choose y} \left({x\over k}\right)^y
\left(1-{x\over k}\right)^{n-y}.$$
Therefore we have the explicit formula
$$\mathbb{E}(X_{(j)})=\sum_{x=0}^{k-1}\sum_{y=0}^{j-1}{n\choose y} \left({x\over k}\right)^y
\left(1-{x\over k}\right)^{n-y}.\tag1$$
For large $k$ asymptotics, exchange the order of summation and rewrite as
a Riemann sum to get
$$\mathbb{E}(X_{(j)})=k\sum_{y=0}^{j-1}\sum_{x=0}^{k-1}{n\choose y} \left({x\over k}\right)^y
\left(1-{x\over k}\right)^{n-y}{1\over k}\approx k\sum_{y=0}^{j-1} \int_0^1 {n\choose y} w^y(1-w)^{n-y}\,dw={k\,j\over n+1}.$$
Using the Euler-Maclaurin formula, you can get more terms in
the asymptotic expansion, for example,
$$\mathbb{E}(X_{(j)})={k\,j\over n+1}+{1\over 2}+O(1/k).$$

Asymptotics are nice, but the formula (1) also allows us to derive
the bounds
$${kj\over n+1}\leq \mathbb{E}(X_{(j)})\leq {kj\over n+1}+1.$$


text:
Q: syntax error occured in combining json string in python I have to create a json string with combined sub string.  i coded as below
import json

s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}

master = {s,'students':[s1,s2,s3]}
print(master)

i got syntax error in line
master = {s,'students':[s1,s2,s3]}

I like to get out as follows
{'class':1,'students':[{'name':'s1','age':15},{'name':'s2','age':10},{'name':'s3','age':12}]}

Kindly help.  I am newbie in python

A: Try:
master = {**s,'students':[s1,s2,s3]}

This will expand s into its keys and values so that they are directly part of master. Otherwise you have to specify keys and values directly with : between.
Note that this only works in Python 3.

A: Try this one, it working in Python2:
import json

s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}
students = {'students':[s1,s2,s3]}

master = dict(s.items() + students.items())
print(master)

And this will working for python2 and python3
master = dict(list(s.items()) + list(students.items()))

A: One more way to achieve this
s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}

master = {}
master.update(s)
master.update({'students':[s1,s2,s3]})

This should work with both the python versions

A: master = {**s,'students':[s1,s2,s3]}


text:
Q: Cannot find local variable, which is a public class I am getting a null pointer exception when running a unit test because of this line:
ClassA.getInstance().getActive();

The above line is written in some other public abstract class which gets called by the test.
Here ClassA is a public class defined in the same package of the test file and getInstance() is a public static method defined in ClassA. When I run in the debug mode I can see that I am getting

"Cannot find local variable 'ClassA'"

Error for ClassA, hence getInstance() is null.
Apologies for not publishing the full code as it is against my company policies.

A: Please check ClassA.getInstance() returns any Object? or null value.
In your code is ClassA.getInstance().getActive(); that means -> getInstance() return some object, please check it is return object or null.
I thought that your getting null that is reason your getting nullpointer exception.

A: Try to generate object with the 'static' word.
Good luck,
G.


text:
Q: Content-Length missing in HTTPModule event handler I have created an HttpModule for my MVC application that will intercept the request/responses to my MVC application.
The httpModule is aded in the webconfig as below
<system.webServer>
        <modules>
            <!--Below HTTP MOdule is  required to log req./res. traffic. -->
            <add name="MyLoggerModule" type="MyProject.HttpModule.MyModule" />
        </modules>
        <urlCompression doStaticCompression="false" doDynamicCompression="false"/>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*"/>
                <add name="Access-Control-Allow-Credentials" value="true"/>
                <remove name="X-Powered-By" />
                <remove name="Vary" />
            </customHeaders>
        </httpProtocol>
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
                 verb="GET,HEAD,POST,PATCH,DEBUG,PUT,DELETE"
                 type="System.Web.Handlers.TransferRequestHandler"
                 preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <httpErrors existingResponse="PassThrough" />
    </system.webServer>

I am trying to get the headers in the HTTPModule PreSendRequestContent eventhandler as below:-
namespace MyProject.HttpModule
{
    public class MyModule : IHttpModule
    {

        public void Dispose()
        {
            //throw new NotImplementedException();
        }
        private HttpApplication applicationContext;
        public void Init(HttpApplication context)
        {
            applicationContext = context;
            context.PreSendRequestContent += new EventHandler(context_PreSendRequestContent);
        }

        void context_PreSendRequestContent(object sender, EventArgs e)

        {
           HttpApplication requestApplicationContext = (HttpApplication)sender;
            var headers = applicationContext.Response.Headers;
            foreach (string header in headers.AllKeys)
            {
                string[] values = headers.GetValues(header);
                string encodedHeader = Util.Base64Encode(string.Concat(header, ":", string.Join(",", values)));

            }
        }

    }

}

when i call a curl to the api in my MVC web app viz.,
        [HttpDelete]
        [AcceptVerbs(HttpVerbs.Delete)]
        public void status(int statusCode)
        {
           HttpContext.Response.StatusCode = statusCode;
           HttpContext.Response.Headers.Add("ContentType", "text/html; charset=utf-8");

        }

i get the following response
DELETE http://localhost:59867/home/status/200
200
102 ms
DELETE /home/status/200 HTTP/1.1
x-test-id: delete-200
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Postman-Token: c191829f-9bc5-4d0f-9103-f95cd0db7cfa
Host: localhost:59867
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

HTTP/1.1 200 OK
Server: Microsoft-IIS/10.0
ContentType: text/html; charset=utf-8
X-SourceFiles: =?UTF-8?B?RTpcR2l0bWFyY2hQT0Ncc2FsdC1paXMtcGx1Z2luXElJU1BsdWdpblxTYWx0U2VjdXJpdHkuSHR0cE1vZHVsZUNvbnN1bWVyLlNhbXBsZVdlYkFwcFxob21lXHN0YXR1c1wyMDA=?=
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Date: Tue, 08 Mar 2022 05:57:18 GMT
Content-Length: 0

However the Content-Length header seen in the response above is missing in the HTTPContext.Response.Headers.AllKeys in the code below.
 void context_PreSendRequestContent(object sender, EventArgs e)
    {

        HttpApplication applicationContext = (HttpApplication)sender;

        var headers = applicationContext.Context.Request.Headers;

        foreach (string header in headers.AllKeys)
        {
            string[] values = headers.GetValues(header);
            string encodedHeader = Util.Base64Encode(string.Concat(header, ":", string.Join(",", values)));

        }

    }

Debugging shows that the only headers present in the context are
"Server:Microsoft-IIS/10.0","Cache-Control:private","Content-Type:text/html; charset=utf-8"

I need the content-Length header to be used in the application.Is there any way to get the content-length header that is being returned in the response?


text:
Q: Do photons "bounce off" of electrons? I've been reading a book, and in one part the author explains how electrons only absorb the wavelengths of light that can take them to an excited state, i.e. that can take the electrons to a higher orbital. The author doesn't mention where the photons that don't have enough energy go, so I assumed (and I may very well be wrong) that they were refracted, or "bounced off" of the electrons. In the a later stage of the book, the author writes that we see colors because the electrons absorb all the light to warm up the atom but also to reach an excited state. They then emit light as they fall back from their excited state and that's what we see. My question is :What's actually true here? Is the light we see the light that's being absorbed and then reemitted with the same frequency, or do we see what's not absorbed? Is all light always absorbed? Which of the explanations are correct? Is it a mix of the two?

A: It's a mix of the two. The sequence:
[incoming photon and atom; interaction; outgoing photon and atom]
is called scattering. There can be elastic scattering, where both the photon and the atom retain their energies, and inelastic scattering, where the energies change. In elastic scattering the photon 'bounces' off the atom, so as to change direction but not energy. In inelastic scattering the photon usually loses energy and the atom gains some, but if the atom was not in its ground state to begin with then it can also happen that the atom loses energy and the photon gains some. There are further possibilities, such as an atom emitting more than one photon, but let's ignore those for now.
In a typical situation all these types of process can happen, but they will happen with different probabilities. The elastic process dominates when the photon energy is off-resonance; the inelastic process dominates when the photon is resonant or near-resonant. Here by 'resonant' I mean that the photon energy matches an energy level gap in the atom. Far off resonance the elastic scatting will be weak, which means the photon mostly goes straight on through or is only steered a little bit.
When materials such as glass change the direction of incident light without absorbing it, this can be seen as an example of elastic scattering.


text:
Q: no cmake vs compiler found for msversion: 4 (windows7) apppium-doctor shows opencv4nodejs cannot be found. So I try to install opencv4nodejs with npm -g install opencv4nodejs. But I got this error:
info install opencv version: 3.4.6
info install with opencv contrib: yes
info install custom build flags:
info install
info install executing: git --version
info install git --version: git version 2.22.0.windows.1
info install
info install executing: cmake --version
info install cmake --version: cmake version 3.15.0
info install
info install CMake suite maintained and supported by Kitware (kitware.com/cmake).
info install
info find-msbuild failed to find vs2017 via powershell: unexpected powershell output
info find-msbuild attempting to find msbuild via registry query...
info find-msbuild trying the following msbuild paths:
info find-msbuild version: 4, path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
info find-msbuild version: 3.5, path: C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe
info install using msbuild: { version: 4,
info install   path:
info install    'C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe' }
ERR! Error: no cmake vs compiler found for msversion: 4
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! opencv-build@0.1.4 install: `node ./install.js`
npm ERR! Exit status 1

I got cmake v3.15 from https://cmake.org/download/. What does log mean? How can I install opencv4nodejs properly?

A: Try this: npm install --global windows-build-tools --vs2015

A: Try: npm install -g windows-build-tools before npm install opencv4nodejs


text:
Q: Why does RVM point to the wrong rubygems? I switched to RVM a few months ago, and don't recall installing any new gems until yesterday. When I require the new gem, I get:
/home/rob/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `require': no such file to load -- mspire/peak_list (LoadError)

Even though:
gem install mspire

worked just fine.
I am guessing that the issue lies in the fact that Ruby is looking for the gem in 1.9.1's rubygems instead of 1.9.2 (the version I am using). I set the version with rvm use. Is there something I am omitting?

A: Ruby >= 1.9.1 always saves its libraries in a 1.9.1. directory. This denotes that all those Ruby versions adhere to 1.9.1 compatibility. It does not denote the actual Ruby version used.
Your gems should be saved in /home/rob/.rvm/gems/ruby-1.9.2-p290/gems. There should be a directory named after the gem and the exact version in there. The paths set by RVM can be checked with rvm info. The GEM_PATH should look like /home/rob/.rvm/gems/ruby-1.9.2-p290:/home/rob/.rvm/gems/ruby-1.9.2-p290@global.
Make sure you install the gem with the exact same Ruby and gemset you are using it with. If you change the Ruby or the gemset, you have to re-install the gem.


text:
Q: Downloading source code in Trac I'm not able to directly download some source files from my project using Trac.
I understand that it's possible to use a SCM client, like git or svn to do this, but surely it can be done without leaving Trac!
Do I need some plug-in, or is there a command or configuration that I've missed?

A: You don't need a plugin for this.  When using the Repository Browser, look for a "Download In Other Formats" link at the bottom of pages.  Individual files will have an "Original Format" link that lets you download the original file, and folders will have a "Zip Archive" link to download the entire folder.
Update:
Also, make sure that you have Trac configured with the repository paths that you want to make downloadable.  In trac.ini, look for a property named downloadable_paths in the [browser] section.  The repository paths listed here (and only those listed here) will be made available for download through the web interface.  For example, my trac.ini has the following:
[browser]
downloadable_paths = /trunk, /branches/*, /tags/*

For more information about this configuration parameter, see the official Trac documentation for trac.ini.


text:
Q: how to get a script tag value with php I am trying to get a value in a script tag with PHP from a page I need to get the value of page_id with in this script tag how can I do that ?
<script type="text/javascript">
    $(document).ready(function() {   Analytics.logAndSendEventToGA(["wap:album_detail:::view","utm_content","wap:album_detail:::view","utm_page","album_detail","utm_button","","page_id","20316543"]);
});
</script>


text:
Q: If a function creates and returns an object, should it be in the autorelease pool I'm still pretty new to objective-c.
As far as I can understand, any object I do not get from alloc, new, copy, or mutableCopy should be assumed to be in the autorelease pool.
I assume that also means that if I create a function that creates and returns a new instance of an object, I should place that in the autorelease pool before returning.
For example, I have a function that parses xml, and returns an object representing the data in the xml, that object should be in the autorelease pool before returning.
My primary concern is iPhone development, but a general answer would be appreciated.

A: You can do it both ways: either return an object that is owned by the caller, or return an object that is not owned by the caller (e.g., an autoreleased object). Regardless of which strategy you choose, follow the naming conventions. For instance,
- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}

returns an NSString object that is owned by the caller. The method name is fullNameCopy, which follows the naming rules: a method that contains 'copy' in its name returns an object that's owned by the caller. The return value is not placed in the autorelease pool.
Alternatively,
- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName];
}

or
- (NSString *)fullName {
    NSString *s = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
    return [s autorelease];
}

return a string that is not owned by the caller, and the method name doesn't contain alloc, new, or copy. The return value is autoreleased, hence it will be deallocated when the corresponding autorelease pool is drained unless the caller explicitly chooses to retain it.
That said, in your particular scenario, the second strategy — returning an object that is not owned by the caller — looks like a better solution. The caller will most likely either process the object immediately (so he won't be interested in owning the object) or keep it in a property (which will most likely be either a copy or a retain property).

A: Yep, your right. If you allocated memory in your function you are also responsible for releasing it. Because you are returning the allocated object, the only way for you to release it, in this situation, is by placing it in the autorelease pool, e.g.
return [newObject autorelease];

(edit)

A: *

*You should read the Objective-C memory management guide.

*Any object returned from a new, alloc or copy method is yours. You own it and you must release it.

*Any object returned from any other method is in the autorelease pool. If you want to keep the object beyond your current scope, you must retain it.

The XML example is probably correct: If you're returning an object from a method and the name of that method does not contain new or copy in the name you should, by convention, return an autoreleased object.


text:
Q: How do I sync multiple web offline POS application in a store on the local network? I will have a web application pos system with an offline mode.
Let's say I have a store where there are 3 web pos applications to buy products.
If my internet connection is down, I'll have to sell products offline, but how do I sync with the 3 POS on my local network?
When the internet connect is available, all data will be synced with the main cloud server.
Would you please give any suggestions on how to design the architecture or how to sync multiple web pos on a local network when the internet is down?


text:
Q: Perl 5 - longest token matching in regexp (using alternation) Is possible to force a Perl 5 regexp match longest possible string, if the regexp is, for example:
a|aa|aaa

I found is probably default in perl 6, but in perl 5, how i can get this behavior?
EXAMPLE pattern:
[0-9]|[0-9][0-9]|[0-9][0-9][0-9][0-9]
If I have string 2.10.2014, then first match will be 2, which is ok; but the next match will be 1, and this is not ok because it should be 10. Then 2014 will be 4 subsequently matches 2,0,1,4, but it should be 2014 using [0-9][0-9][0-9][0-9]. I know I could use [0-9]+, but I can't.

A: General solution: Put the longest one first.
my ($longest) = /(aaa|aa|a)/

Specific solution: Use
my ($longest) = /([0-9]{4}|[0-9]{1,2})/

If you can't edit the pattern, you'll have to find every possibility and find the longest of them.
my $longest;
while (/([0-9]|[0-9][0-9]|[0-9][0-9][0-9][0-9])/g) {
   $longest = $1 if length($1) > length($longest);
}

A: The alternation will use the first alternative that matches, so just write /aaa|aa|a/ instead.
For the example you have shown in your question, just put the longest alternative first like I said:
[0-9][0-9][0-9][0-9]|[0-9][0-9]|[0-9]

A: The sanest solution I can see for unknown patterns is to match every possible pattern, look at the length of the matched substrings and select the longest substring:
my @patterns = (qr/a/, qr/a(a)/, qr/b/, qr/aaa/);
my $string = "aaa";

my @substrings = map {$string =~ /($_)/; $1 // ()} @patterns;

say "Matched these substrings:";
say for @substrings;

my $longest_token = (sort { length $b <=> length $a } @substrings)[0];

say "Longest token was: $longest_token";

Output:
Matched these substrings:
a
aa
aaa
Longest token was: aaa

For known patterns, one would sort them manually so that first-match is the same as longest-match:
"aaa" =~ /(aaa|aa|b|a)/;
say "I know that this was the longest substring: $1";

A: perl -Mstrict -Mre=/xp -MData::Dumper -wE'
  {package Data::Dumper;our($Indent,$Sortkeys,$Terse,$Useqq)=(1)x4}
  sub _dump { Dumper(shift) =~ s{(\[.*?\])}{$1=~s/\s+/ /gr}srge }
  my ($count, %RS);
  my $s= "aaaabbaaaaabbab";
  $s =~ m{ \G a+b? (?{ $RS{ $+[0] - $-[0] } //= [ ${^MATCH}, $-[0] ]; $count++ }) (*FAIL) };
  say sprintf "RS: %s", _dump(\%RS);
  say sprintf "count: %s", $count;
'
RS: {
  "1" => [ "a", 0 ],
  "2" => [ "aa", 0 ],
  "3" => [ "aaa", 0 ],
  "4" => [ "aaaa", 0 ],
  "5" => [ "aaaab", 0 ]
}

count: 5


text:
Q: ASP.NET fileupload with database file path insert I'm setting up a photography website for my sister-in-law.  What I'm looking to do is to use the ASP.NET upload control.  I've found another posting which has how to do the file upload side of things.  But, the website is going to have a database backend (SQL Server 2012) and what I want to do is write the filepath (include filename and type) into the database so that when a customer logs in the database will display all of the images that have been assigned to that customer.  So the file location field would hold something like ../images/custName/test.jpg
Anyone got any ideas how to do this?  Another option I thought of was to just store the folder location for that customer and then pull back all images in that folder, but I think this method would be less efficient.
I'm very (very!) new to ASP.NET so any help would be greatly received.  Not too fussed if the solution is in C# or VB.NET (I'm trying to learn both anyway).
UPDATE
Database Schema shown below:
[Cust].[CustImages](
    [ImageID] [int] NOT NULL PK,
    [CustomerId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [ImageFilePath] [varchar](100) NOT NULL,

The CustomerId is a FK from the Customer table so that a customer can only see photographs associated to them.  ProjectId is also a FK to the project table, this table is needed to break the M:M relationship between customer and CustImage.
So what will happen is the photographer will go out and take the pictures, then head home and edit them as required and then upload them to the website, the form they will use will have a list of customers and associated projects.  The photographer will select the customer and project and then upload the images.
After seeing some of the responses, I will create a stored procedure that will take in customerId, ProejectId and ImageFilePath as parameters and insert the details into the database.
What I don't know is how to get the ImageFilePath so that I can then pass it into the stored procedure.
Thanks
Alex

A: You will have to create a table in the SQL Server where you will store the logging of the uploads. After a customer uploads a file, then you will call an insert stored procedure which will write the needed log data to the former table.

A: I suppose you will use asp.net web form. To begin with, you will use the FileUpload to render an upload html element in the aspx file as <asp:FileUpload runat="server" ID="FupImage"/>
When you will submit the webform (usually when clicking on the submit button), an event handler method in the aspx.cs file will handle the button click event. I will advice you to save the file on another location accessible by the running website. On top of that, I advice you to invoke a stored procedure to save the new path of the image in that table If you had a button called BtnUpload, the following code will allow you to obtain the file path:
    protected void BtnUpload_Click(object sender, EventArgs e)
    {

        String newFileName = String.Concat(yourNewPath, this.FupVendeur.FileName);

        this.FupVendeur.SaveAs(newFileName);

        YourDataServiceLayer.SaveFileName(newFileName);

    }

I use Microsoft Enterprise Library to do all the database operations.


text:
Q: Remove full access permissions of all disabled users on shared mailboxes with exchange management shell I'm looking for a powershell exchange script to remove Full access permissions of all disabled users on all shared mailboxes in a specific OU.
This is what I got so far
Remove-MailboxPermission -Identity Sharedmailbox -AccessRights Fullaccess -InheritanceType all -user DisabledUser -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}

Its seems to work but I'm not sure about the last piece of het script if it will check for "accountdisabled"
Then I created a variable so it will check only one specific OU
$ou = Get-ADUser -SearchBase "OU=Functional Mailboxes,OU=Generalaccounts,DC=DOMAIN,DC=COM" -Filter * foreach ($user in $ou)

Remove-MailboxPermission -Identity "$ou" -AccessRights Fullaccess -InheritanceType all -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}

The script is checking the right OU but I'm still looking for the last part where it will automatically remove full access permissions of the disabled users ONLY.
Can someone show me the way?

A: Instead of trying to screen for disabled users after removing the mailbox permissions (which is what your Remove-MailboxPermission ... | Where-Object ... appears to be intended to do - except that the way you wrote it, it's only checking for disabled state after removing the permissions), try selecting for the disabled accounts first, then passing only the disabled accounts to Remove-MailboxPermission:
Get-ADUser -SearchBase ... -filter {Enabled -eq $false} | Remove-Mailbox ...
(replacing ... with the appropriate SearchBase or parameters for Remove-Mailbox, using $_ for the identity of the ADUser whose mailbox permissions you're removing.)