text:
Q: Android app won't connect to computer that's connected wirelessly to network The app uses sockets to connect to the computer but will only connect if the computer is connected to the network by an ethernet cable. I've tried disabling the firewalls but that makes no difference.
The code for the server on the computer:
int port = 7936;

while(true){
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client ...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected");

InputStream in = client.getInputStream();

and the code for the client on the app:
Socket socket = new Socket(address,7936);
OutputStream out = socket.getOutputStream();
String action = "2";
byte[] actByte = action.getBytes();
out.write(actByte);
socket.close();

Address is defined by user input and all the permissions needed have been set in the manifest xml file.
Thanks for the help.
Edit
Sorry for the delay in responding to the answers given. I have since been able to try the program on a different network and it works with the computer connected wirelessly so it looks like the issue was with the network rather than the code.
Thanks to everyone for answering and I'm sorry it took me so long to respond.

A: As others have mentioned, more information is needed.  When you disconnect the computer from the wired connection, I assume it is switching over to wifi and you've verified that you are online.  Your computer is likely to get a different IP address if you're DHCP as the interface changed and so wouldn't the MAC address.
Check the address on the computer and verify you have the right address.

A: What I'm thinking is that the socket is not bound to the IP address you think it is. You may wish to try using the TcpListener class, that way you can bind it to the IP address (network adapter) you want.


text:
Q: Copy sheet data to the end of another sheet I am able to copy the last row of one workbook and paste it after the last row of another workbook. I want to copy the entire data from row 2 (row 1 is header) in the first workbook and paste it after the last row of another workbook. Please advise me what changes are required in the code below to copy the entire data from row 2 instead of only the last row.
Dim lastS1Row As Long
Dim nextS2Row As Long
Dim lastCol As Long
Dim lCol As Long
Dim lCol1 As Long
Dim s1Sheet As Worksheet, s2Sheet As Worksheet
Dim source As String
Dim target As String
Dim path As String
Dim path1 As String

    source = "Students"     'Source Worksheet Name
    path1 = "H:\Shaikh_Gaus\scratch\VBA\Book17.xlsx"
    path = "H:\Shaikh_Gaus\scratch\VBA\Book16.xlsx"
    target = "Students" 'Target Worksheet Name

    Application.EnableCancelKey = xlDisabled

    Set s1Sheet = Workbooks.Open(path).Sheets(source)
    Set s2Sheet = Workbooks.Open(path1).Sheets(target)

    lastS1Row = s1Sheet.Range("A" & Rows.Count).End(xlUp).Row
    nextS2Row = s2Sheet.Range("A" & Rows.Count).End(xlUp).Row + 1
    lastCol = s1Sheet.Cells(1, Columns.Count).End(xlToLeft).Column

    For lCol = 1 To lastCol
        s2Sheet.Cells(nextS2Row, lCol) = s1Sheet.Cells(lastS1Row, lCol)
    Next lCol
    Next lCol1

    s2Sheet.Activate
    ActiveWorkbook.Close SaveChanges:=True
    s1Sheet.Activate
    ActiveWorkbook.Close

A: This adjusted version of your code should do the job:
Dim s1Sheet As Worksheet, s2Sheet As Worksheet
Dim source As String
Dim target As String
Dim path As String
Dim path1 As String
Dim rngSource As Range
Dim rngTargetStart As Range

    source = "Students"     'Source Worksheet Name
    path1 = "H:\Shaikh_Gaus\scratch\VBA\Book17.xlsx"
    path = "H:\Shaikh_Gaus\scratch\VBA\Book16.xlsx"
    target = "Students" 'Target Worksheet Name

    Application.EnableCancelKey = xlDisabled

    Set s1Sheet = Workbooks.Open(path).Sheets(source)
    Set s2Sheet = Workbooks.Open(path1).Sheets(target)
    Set rngSource = Range(s1Sheet.Range("A2"), s1Sheet.Cells.SpecialCells(xlCellTypeLastCell))
    Set rngTargetStart = s2Sheet.Range("A" & Rows.Count).End(xlUp).Offset(1)

    rngTargetStart.Resize(rngSource.Rows.Count, rngSource.Columns.Count).Value = rngSource.Value

    s2Sheet.Parent.Close SaveChanges:=True
    s1Sheet.Parent.Close

I removed something what seemed unnecessary. The main thing is that now you don't loop through columns and rows. Now you can do it with one operation.
Avoid as much as you can things like .Select, .Activate. and .Copy if you just need values to be pasted. You can simply do something similar like I did:
Target.Value = Source.Value

A: After you set s1Sheet and s2Sheet I think you should be able to use these 2 lines to copy & paste the entire range at once:
    'copy Cells A2 through last row and last column used
    s1Sheet.Range(s1Sheet.Cells(2, 1), s1Sheet.Cells(s1Sheet.Cells(s1Sheet.Rows.Count, 1).End(xlUp).Row, _
    s1Sheet.Cells(1, s1Sheet.Columns.Count).End(xlToLeft).Column)).Copy

    'paste those cells in next blank row of second sheet
    s2Sheet.Cells(s2Sheet.Cells(s2Sheet.Rows.Count, 1).End(xlUp).Row + 1, 1).PasteSpecial Paste:=xlPasteAll

A: 'Here you go:

Range("A2").End(xlDown).select
selection.End(xlRight).select
selection.copy
'then active the next sheet for e.g Sheet2.Active
last_row = range("A1048576").end(xlup).row
range("A" & last_row).paste

' Done

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark SQL- Regex to find 4 consequtive numbers I am trying to write a regex function which has consequite 4 digits and checking it as rlike(postal_code,'(?:^|\D)(\d{4})(?!\d)')=='true' but I am getting below error.
My Spark sql is :
 df_email_cleaned=spark.sql("select *,case when  postal_code like '%-%' and rlike(postal_code,'(?:^|\D)(\d{4})(?!\d)')=='true' then split(postal_code, '-')[0] \
                                                    when  postal_code like '%-%' and  rlike(postal_code,'(?:^|\D)(\d{4})(?!\d)')=='true'  then split(postal_code, '-')[1] \
                                                    when postal_code  rlike(postal_code,'(?:^|\D)(\d{4})(?!\d)')=='true'  and length(postal_code)>2 and length(postal_code)<6 then postal_code \
                                                    else '' \
                                                    end sd_ps_clean \
                                                    from df_email_cleaned_sql ")

I am getting below error:
    pyspark.sql.utils.AnalysisException: cannot resolve '(named_struct('postal_code',
df_email_cleaned_sql.`postal_code`, 'col2', '(?:^|D)(d{4})(?!d)') = 'true')'
 due to data type mismatch: differing types in '(named_struct('postal_code', df_email_cleaned_sql.`postal_code`, 'col2', '(?:^|D)(d{4})(?!d)') = 'true')' (struct<postal_code:string,col2:string> and string).; line 1 pos 343;


text:
Q: BeautifulSoup find a href in marquee I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data.
I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has.
Note: I can get the links easy peasy with selenium and chrome driver, but it takes forever.

This returns all of the marquee data:
url = 'https://drugs.globalincidentmap.com/'

response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

marquee = soup.select('div', class_='h-48')
print(marquee)

However when I try to drill down further into the data, I get the empty list or NoneType/KeyError or AttributeError.
for a in marquee.find_all('a', href=True):
    link = a.find('div', class_=':nth-child')

or
for a in marquee.find_all('a', href=True):
    link = a.find('div', class_='flex p-2')

Links in marquee

A:
I can get the links easy peasy with selenium and chrome driver

Probably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think soup.select('div', class_='h-48') gives the exact results you expect it to - select isn't really supposed to have a class_ argument - just a CSS selector string].
soup.find('div', attrs={'class':'h-48'}) or soup.select('div.h-48') can be expected to work on the html that is formed after JS loading, but you need selenium to get that...

Fortunately, I think the data you want is already in the fetched html, just in a different format - you can extract a list of dictionaries (mqCont) with
# import json

marq = soup.find('marquee', attrs={'class':'h-48'})
if marq is None: print('Could Not Find marquee.h-48')
if not marq.get(':contents'): print('marquee.h-48 has no [:contents] attr')

try: mqCont =  json.loads(marq.get(':contents', '[]'))
except Exception as e:
    mqCont = []
    print('failed to parse marquee.h-48[:contents] <---', e)

or, more shortly (if you're confident there won't be any error to debug/breakdown):
mqCont = json.loads(soup.select_one('marquee.h-48').get(':contents', '[]'))

You can get a list of links to news articles with [m['url'] for m in mqCont if 'url' in m], but since you were trying to get find with class_='flex p-2', you probably want the .../event_detail?id=... links. You can form them as below
evtUrls = [f"{url.strip('/')}/event_detail?id={m['id']}" for m in mqCont if 'id' in m]

You can also view the list of dictionaries as a table [with pandas] by doing something like:
# import pandas

omitKeys = ['domain_event_types', 'country']
for i, m in enumerate(mqCont):
    mDesc = ' '.join(w for w in BeautifulSoup(
        m['description'] if 'description' in m else ''
    ).get_text().split() if w)
    if mDesc: m['description'] = mDesc
    if 'id' in m: m['eventUrl'] = f"{url.strip('/')}/event_detail?id={m['id']}"
    mqCont[i] = {k:v for k, v in m.items() if k not in omitKeys}

mqcDF = pandas.DataFrame(mqCont).dropna(axis='columns', how='all').set_index('id')

and the first 5 rows [of 100 rows total] of mqcDF:

id
country_id
address
event_gmt_time
severity
infrastructure
tip_text
url
description
latitude
longitude
created_user_id
location_granularity_id
is_approved
created_at
updated_at
eventUrl

11919404
231
Pennsylvania, USA
2022-12-01 18:36:53
Severe
Unknown
PENNSYLVANIA - Photos - Suspects - Evidence In Multi-County Drug Bust
https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1
[69 NEWS] PENNSYLVANIA - PHOTOS: Suspects, evidence in multi-county drug bust "Authorities said they seized evidence that included 27.5 kilograms of cocaine with a potential street value of $2.7 million and 5.5 kilograms of fentanyl with a potential street value of $1.6 million." Read full article at: https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1
41.2033
-77.1945
14
8
1
2022-12-02T18:44:43.000000Z
2022-12-02T18:44:43.000000Z
https://drugs.globalincidentmap.com/event_detail?id=11919404

11919401
40
Vancouver Island, British Columbia, Canada
2022-12-01 18:33:01
Severe
Unknown
CANADA - Drugs - Guns Seized As 4 BC Men With Hells Angels Ties Face Serious Charges
https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/
[terracestandard.com] CANADA - Drugs, guns seized as 4 B.C. men with Hells Angels ties face 'serious charges' "CFSEU said the seized drugs included 7.75kg of cocaine, 4kg of cannabis, 1.9kg of methamphetamine, 248 oxycodone pills, and more." Read full article at: https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/
49.6506
-125.449
14
5
1
2022-12-02T18:36:37.000000Z
2022-12-02T18:36:37.000000Z
https://drugs.globalincidentmap.com/event_detail?id=11919401

11919397
133
Male, Maldives
2022-11-20 18:29:26
Severe
Unknown
MALDIVES - Drugs Worth Mvr 2 Mln Seized By Customs
https://avas.mv/en/125385
[avas.mv] MALDIVES - Drugs worth MVR 2 mln seized by Customs "Maldives Customs Service has seized 1.34 kg of drugs smuggled into the Maldives via courier." Read full article at: https://avas.mv/en/125385
4.1755
73.5093
14
5
1
2022-12-02T18:32:45.000000Z
2022-12-02T18:32:45.000000Z
https://drugs.globalincidentmap.com/event_detail?id=11919397

11919394
231
100 South Willow Avenue, Compton, CA, USA
2022-11-29 18:23:50
Severe
Unknown
CALIFORNIA - USD4 Million Worth Of Illegal Drugs Seized In Compton
https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton
[foxla] CALIFORNIA - $4 million worth of illegal drugs seized in Compton "A search warrant at the home resulted in the seizure of about 5.5 lbs. of suspected tar heroin, 10 kilos of suspected powder cocaine, 6 kilos of suspected powder fentanyl, 6,000 suspected ecstasy pills containing fentanyl, and 254,000 suspected fentanyl pills all worth a combined estimated street value of $4.17 million, authorities said. " Read full article at: https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton
33.896
-118.218
14
5
1
2022-12-02T18:29:25.000000Z
2022-12-02T18:29:25.000000Z
https://drugs.globalincidentmap.com/event_detail?id=11919394

11919392
166
Gwadar, Pakistan
2022-12-01 18:22:00
Severe
Unknown
PAKISTAN - Convoy Of Camels Loaded With Drugs Seized
https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/
[pakobserver.net] PAKISTAN - Convoy Of Camels Loaded With Drugs Seized "While searching the goods carried by the camels, ANF officials found them to be full of drugs (hashish). The drugs weighed around 1.4 tons." Read full article at: https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/
25.1313
62.325
14
5
1
2022-12-02T18:23:49.000000Z
2022-12-02T18:23:49.000000Z
https://drugs.globalincidentmap.com/event_detail?id=11919392

Markdown for the above table was printed with print(mqcDf.loc[mqcDf.index[:5]].to_markdown())


text:
Q: cmake add_dependencies, add_custom_command and add_custom_target not working together I have been trying to get the simple use case of getting cmake to to generate some files with a script and then build an executable out of those generated files. After spending hours reading the documentation and various stack overflow answers, it seems like this is how everything should be arranged, yet cmake refuses to configure the project.
The idea is that things are done in following steps:

*

*During configure time, the generate_files.sh is generated with correct paths

*During build time, the target gen is built first and then target test is built

Step 1 is being performed properly, however step 2 isn't. Cmake complains that the source files for target test aren't found, even though it should build gen first and then it would find the sources.
What am I doing wrong?
Directory structure:
.
├── build
├── CMakeLists.txt
├── config
│   └── generate_files.sh.in
├── extern
│   ├── CMakeLists.txt
│   └── gen
├── scripts
└── src
    ├── CMakeLists.txt
    └── main.cpp

Top level CMakeLists:
cmake_minimum_required(VERSION 3.13)
project(test VERSION 0.1.0.0)

add_subdirectory(src)
add_subdirectory(extern)

configure_file("${CMAKE_SOURCE_DIR}/config/generate_files.sh.in" "${CMAKE_SOURCE_DIR}/scripts/generate_files.sh")

src/CMakeLists:
add_executable(test main.cpp)

extern/CMakeLists:
set(generated_sources
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated.h
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated_1.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated_2.cpp
    )

set(generated_directories
    ${CMAKE_CURRENT_SOURCE_DIR}/gen)

add_custom_command(
    OUTPUT ${generated_sources}
    COMMAND "${CMAKE_SOURCE_DIR}/scripts/generate_files.sh"
    )

add_custom_target(gen
    DEPENDS ${generated_sources}
    )

add_dependencies(test gen)

target_sources(test
    PRIVATE
        ${generated_sources}
)

target_include_directories(test
    PRIVATE
        ${generated_directories}
)

config/generate_files.sh.in:
#! /bin/bash

echo " const int get_trouble_code();
const int get_higher_trouble_code();" > ${CMAKE_SOURCE_DIR}/extern/gen/generated.h
echo " #include \"generated.h\"
const int get_trouble_code(){return 1;}" > ${CMAKE_SOURCE_DIR}/extern/gen/generated_1.cpp
echo " #include \"generated.h\"
const int get_higher_trouble_code(){return 1+1;}" > ${CMAKE_SOURCE_DIR}/extern/gen/generated_2.cpp

src/main.cpp:
#include "generated.h"

int main()
{
  get_trouble_code();
  get_higher_trouble_code();

  return 0;
}

Edit: I found a way to make it work, but now I am even more confused. Adding the generated files as a library instead of custom target seems to do the trick. The following changes to extern/CMakeLists work, but could someone explain why? :
set(generated_sources
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated.h
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated_1.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/gen/generated_2.cpp
    )

set(generated_directories
    ${CMAKE_CURRENT_SOURCE_DIR}/gen)

add_custom_command(
    OUTPUT ${generated_sources}
    COMMAND "${CMAKE_SOURCE_DIR}/scripts/generate_files.sh"
    )

#comment out this stuff
#add_custom_target(gen
#   DEPENDS ${generated_sources}
#    )
#
#add_dependencies(test gen)
#
#target_sources(test
#    PRIVATE
#        ${generated_sources}
#)

#add as library instead
add_library(gen ${generated_sources})
target_link_libraries(test PRIVATE gen)

target_include_directories(test
    PRIVATE
        ${generated_directories}
)

A:
CMake complains that the source files for target test aren't found ...

This is because the source file is absent, and its GENERATED property is not set.
Normally, add_custom_command sets GENERATED property for all files listed in its OUTPUT. But before CMake 3.20 that property was local to the directory:

*

*add_custom_command is called from extern/CMakeLists.txt, but

*target test evaluates its sources in top-level CMakeLists.txt, where the target is created.
(Irrespective where target_sources is called).

In CMake 3.20 the GENERATED property becomes global (for use this feature your project should have corresponding cmake_minimum_required).
If updating CMake is not an option, then you could set GENERATED property manually in top-level CMakeLists.txt. (This will hurts locality of your CMakeLists.txt .. so it is better to update CMake.)
Technically, you trigger the problem issued in that bugreport.

A: Here's a minimal working example that I think is much less complicated and follows best practices. Here, there's no need to configure_file your generation script. There's also no need to write to the source directory, which you should never do.
The link between the custom command and your target is clearly established, too. Plus, the include paths are set up correctly.
Files
CMakeLists.txt:
cmake_minimum_required(VERSION 3.25)
project(example)

set(gendir "${CMAKE_CURRENT_BINARY_DIR}/extern/gen")

set(genfiles generated.h generated_1.cpp generated_2.cpp)
list(TRANSFORM genfiles PREPEND "${gendir}/")

add_custom_command(
  OUTPUT ${genfiles}
  COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/generate_files.sh"
)

add_executable(app main.cpp ${genfiles})
target_include_directories(app PRIVATE "${gendir}")

generate_files.sh:
#!/bin/bash

set -e -o pipefail

mkdir -p extern/gen

echo "const int get_trouble_code();
const int get_higher_trouble_code();" > extern/gen/generated.h
echo "#include \"generated.h\"
const int get_trouble_code(){return 1;}" > extern/gen/generated_1.cpp
echo "#include \"generated.h\"
const int get_higher_trouble_code(){return 1+1;}" > extern/gen/generated_2.cpp

main.cpp:
(same as above, but reproduced here for completeness)
#include "generated.h"

int main()
{
  get_trouble_code();
  get_higher_trouble_code();

  return 0;
}

Build output
Here's what I see when it builds (successfully!)
$ cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 11.3.0
-- The CXX compiler identification is GNU 11.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/alex/test/build
$ cmake --build build --verbose
[1/5] cd /home/alex/test/build && /home/alex/test/generate_files.sh
[2/5] /usr/bin/c++  -I/home/alex/test/build/extern/gen -g -MD -MT CMakeFiles/app.dir/extern/gen/generated_1.cpp.o -MF CMakeFiles/app.dir/extern/gen/generated_1.cpp.o.d -o CMakeFiles/app.dir/extern/gen/generated_1.cpp.o -c /home/alex/test/build/extern/gen/generated_1.cpp
[3/5] /usr/bin/c++  -I/home/alex/test/build/extern/gen -g -MD -MT CMakeFiles/app.dir/extern/gen/generated_2.cpp.o -MF CMakeFiles/app.dir/extern/gen/generated_2.cpp.o.d -o CMakeFiles/app.dir/extern/gen/generated_2.cpp.o -c /home/alex/test/build/extern/gen/generated_2.cpp
[4/5] /usr/bin/c++  -I/home/alex/test/build/extern/gen -g -MD -MT CMakeFiles/app.dir/main.cpp.o -MF CMakeFiles/app.dir/main.cpp.o.d -o CMakeFiles/app.dir/main.cpp.o -c /home/alex/test/main.cpp
[5/5] : && /usr/bin/c++ -g  CMakeFiles/app.dir/main.cpp.o CMakeFiles/app.dir/extern/gen/generated_1.cpp.o CMakeFiles/app.dir/extern/gen/generated_2.cpp.o -o app   && :
$ ./build/app
$ # doesn't crash


text:
Q: Graph relationships between functions and variables
Possible Duplicate:
Has anyone written any function to automatically build a  dependency graph of an arbitrary Mathematica function?

I need to make sense out of a huge notebook (17Kloc) that was probably written by more than one person.
The functions are all interdependent, and written in a procedural fashion. To help me get to grips with the work, I'd like to see a graph of how the functions (and variable, if convenient) relate to each other. What I'm envisaging is a huge graph connecting functions and variables.
I've enumerated
Names["Global`*"]

but even with this list, I'm having a hard time figuring out which way to go.
Is there a built-in function that does this? Should I convert the whole notebook to string, and look for patterns? Is there a way to identify the beginning and end of a function?
Thoughts wanted!


text:
Q: gl_NormalMatrix and gl_ModelViewProjectionMatrix in GLES 2.0 (WebGL) Are gl_ModelViewProjectionMatrix and gl_NormalMatrix matrices (or similar forms) supported in OpenGL ES 2.0? That's computed automatically by GL, provided the modelview matrix and the initial matrix and then automatically passed to the vertex shader?
Thanks,
-Ilyes

A: OpenGL ES 2.0 doesn't have any built-in matrices or variables (except for gl_Position), so you have to calculate them by yourself and upload them to the shader as uniform variables.

A: gl_ModelViewProjectionMatrix, you can use ViewProjectMatrix uniformly send from the OpenGL application to the shader.
gl_NormalMatrix, try using WorldViewInverseTranspose again send uniformly from the application.


text:
Q: How to find number of devices is in iBeacon range? Currently I'm following this tutorial https://www.appcoda.com/ios7-programming-ibeacons-tutorial/.
And created one broadcasting beacon. Other devices will detect this beacon when these users enter the region. What I want to know is who are the customers in the mall right now. Is it possible?

A: Understand that bluetooth beacons are one way transmitters.  They have no knowledge of what devices, if any, detected them.
If you have an app on each of the devices that detected the beacon, you can program something into the app that reports to a server when it saw the beacon.  Using this technique, you can calculate on.the server how many mobile devices saw the beacon  in a given time frame.

A: If your iBeacon transmitter is an iOS device such as an iPhone or iPad, you can set it to transmit and receive at the same time. If you're using a dedicated iBeacon device like Estimote, they are transmit only and will not be aware of how many clients are nearby.
Further discussion on simultaneous transmission/reception can be found here: iBeacon app - receiving/transmitting at the same time


text:
Q: How to always show titles on Windows 7 Taskbar thumbail preview? I often use the Win+n shortcuts to 'alt-tab' between windows of pinned application (i.e. Win+2 to basically 'alt-tab' multiple putty windows, where putty is pinned as app #2 on the taskbar).
The Win+n always pops up the thumbnail previews of all the windows, but sometimes it shows window titles above the thumbnail, sometimes it doesn't.  Is there any way to always show the titles (i.e. registry setting?)?

For putty sessions this would be especially nice, as the title contains the hostname, and the thumbnail is too small to determine what host that window is for.
I've noticed that the titles usually show up with there are more than ~4-6 windows of that pinned item open - but the number seems to vary - is there a threshold setting for this?
Update:  So I just noticed the titles show up whenever the taskbar buttons combine, which varies based on how many windows from other apps are open...  AFAIK, the always combine, keep labels setting doesn't exist http://www.windows7taskforce.com/view/2236, but I don't really care about combining, I just want the titles.

A: *

*Open Taskbar and Start Menu Properties (Right-click somewhere empty on the taskbar and choose Properties)

*In the Taskbar Tab, set the Taskbar buttons to: Always combine, hide labels

*Click OK

Now when you press WIN + n  or mouse over it will show all open windows of that application with their names at the top.


text:
Q: Is the space of continuous maps $Top(X,Y)$ between two topological spaces compact if $X$ is? Suppose that $X$ and $Y$ are topological spaces, and we consider $Y^X$, i.e. the space of maps from $X$ to $Y$ with the compact-open topology.  If $X$ is compact then can we say anything about $Y^X$?
Thanks!
Jon

A: Suppose $X$ is a one-point space. Then $Y^X$ is naturally homeomorphic to $Y$, so is not compact unless $Y$ is.


text:
Q: Run as another user with PyCharm remote interpreter I have PyCharm set up with a remote interpreter to a CentOS machine. After setting up the remote interpreter, everything works fine. However, there are some python scripts that I need to run with a user that is not me, what I would do, is:
sudo -u another-user python my_script.py

Is there a way that I can add the sudo -u another-user when PyCharm runs all scripts on the remote interpreter? I really don't care if it asks me for the sudo password every time.


text:
Q: MFC CListCtrl OnToolTipNotify I'm trying to override OnToolTipNotify for the CListCtrl to have tooltips that support more than 80 characters.  I want the tooltips to appear for specific cells. I've seen a bunch of posts related to this, but none have completely helped me understand the best way to do this.  Here is what I have so far, but I'm concerned with the wide char code that uses T2W.  I read T2W uses memory off the stack and when the function returns it will be cleaned up. So, lpszText will become invalid. This seems to work though and I cannot find another way to do it.
BOOL CListCtrlEx::OnToolTipNotify(UINT tooldId, NMHDR* notifMsg, LRESULT result)
{
    USES_CONVERSION;
    TOOLTIPTEXTA* tttA = reinterpret_cast<TOOLTIPTEXTA*>(notifMsg);
    TOOLTIPTEXTW* tttW = reinterpret_cast<TOOLTIPTEXTW*>(notifMsg);
    ...
    int row, col;
    cellHitTest(row, col);
    CString tipStr;

    // Note getTooltip() returns const ref to cell's tooltip string
    if (-1 < row && -1 < col)
        tipStr = m_Data[row]->colvals[col]->getTooltip();

    if (tipStr.IsEmpty()) return FALSE;

    if (TTN_NEEDTEXTA == notifMsg->code)
    {
        tttA->lpszText = tipStr.GetBuffer();
        tttA->hinst = 0;
    }
    else
    {
        // Question: Is this a problem?  Will the buffer pointed to
        // by tttW->lpszText be deleted after this function ends
        // making the pointer invalid?
        tttW->lpszText = T2W(tipStr.GetBuffer());
        tttW->hinst = 0;
    }

    ...
}

A: I tried to understand your question with my best efforts. All you are saying that CString can be used, but the wide conversion cannot be used directly without T2W conversion macro. If this is the question, you can simply use CStringW - assign tipStr to a variable of this type, and pass it to lpszText.
But, I see problem with your code - you are assuming that if code is not TTN_NEEDTEXTA, it must be TTN_NEEDTEXTW- this assumption is wrong.
EDIT: From this article, I found out that you need to allocate it dynamically. Hope this helps!

If using the TTN_NEEDTEXT message handler and one wants to display
  tooltip longer than 80 characters, then one must allocate the wanted
  text buffer and set the TOOLTIPTEXT::lpszText pointer to this
  text-buffer in the message handler (one has to deallocate this text
  buffer manually):

A: This is the code I use:
tiptext is the CString containing the text I want to show
m_pchTip and m_pwchTip are members of my list control.
    if(m_pchTip != NULL)
    {
        delete[] m_pchTip;
        m_pchTip = nullptr;
    }

    if(m_pwchTip != NULL)
    {
        delete[] m_pwchTip;
        m_pwchTip = nullptr;
    }

        if(pNMHDR->code == TTN_NEEDTEXTA)
        {
            TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
            m_pchTip = new char[tiptext.GetLength() + 1];
            lstrcpyn(m_pchTip,tiptext,tiptext.GetLength() + 1);
            m_pchTip[tiptext.GetLength()] = 0;
            pTTTA->lpszText = m_pchTip;
        }
        else
        {
            TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
            m_pwchTip = new WCHAR[tiptext.GetLength() + 1];
            _mbstowcsz(m_pwchTip,tiptext,tiptext.GetLength() + 1);
            m_pwchTip[tiptext.GetLength()] = 0;
            pTTTW->lpszText = (WCHAR*)m_pwchTip;
        }

A: Here is what I ended up doing. Since I could not find a case in my applications where I need to handle the TTN_NEEDTEXTA == notifMsg->code case I'm not supporting it.  I removed ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA...) from the message map and in CListCtrlEx::OnToolTipNotify I return FALSE if TTN_NEEDTEXTA == notifMsg->code. I will revisit it when I better understand ANSI vs. UNICODE.
In my cell class I changed the CString tooltip member to CStringW as @IInspectable suggested.  The CListCtrlEx::OnToolTipNotify function has access to the cell's CStringW member, so I set lpszText = const_cast<LPWSTR>((LPCWSTR)m_Data[row]->colvals[col]->tooltip).


text:
Q: Clarifying a right angle in a bisected triangle Here is a question that I was doing this morning:

Part of the mark scheme makes use of the following:

My question: How do we know that the bisector of the angle DAB meets the midpoint at a right angle?
Thanks.


text:
Q: FireServer() Doesn't fire the remote event i was making a script that changes a value when the player dies, i did it with remote events but it didn't work.
Local Script:
local plr = game:GetService('Players').LocalPlayer
wait(2)
local char = plr.Character
local humanoid = char:WaitForChild("Humanoid")

humanoid.Died:Connect(function(death)
    print('death')
    game:GetService('ReplicatedStorage').setPlayerInLobby:FireServer()
    print('fired')
end)

Server script:
rs.setPlayerInLobby.OnServerEvent:Connect(function(plr)
    print("works i guess?")
    plr.InLobby.Value = true
end)

It printed out "death" and "fired" but it didn't do anything else.

A: You never defined the rs variable in your server Script.
local rs = game:GetService("ReplicatedStorage")

A: local plr = game:GetService('Players').LocalPlayer

local char = plr.Character
local humanoid = char:WaitForChild("Humanoid")
if plr.Character.Humanoid.Health == 0 then
  print("Bla bla")
end

So you can use it on a local script i guess


text:
Q: How do I use a custom widget (Network Image) in GButton (google_nav_bar)? I am using google_nav_bar.dart package for a BottomNavigationBar. I want to have a custom widget (Network Image) instead of an Icon. I tried a lot of things but nothing is working.
Package: https://pub.dev/packages/google_nav_bar
My Code Snippet where I want to use NetworkImage.
GButton(
    icon: LineIcons.user,
    text: 'Profile',
),

A: Use the leading property:
GButton(
  leading: SizedBox(
    width: 24,
    height: 24,
    child: Image.network("http://via.placeholder.com/24x24"),
  ),
  text: 'Profile',
),

I'd recommend using CachedNetworkImage
https://pub.dev/packages/cached_network_image
GButton(
  text: 'Search',
  leading: SizedBox(
    width: 24,
    height: 24,
    child: CachedNetworkImage(
      imageUrl: "http://via.placeholder.com/24x24",
      placeholder: (context, url) => CircularProgressIndicator(),
      errorWidget: (context, url, error) => Icon(Icons.error),
    ),
  ),
)


text:
Q: Ubuntu 14.04.05 + nvidia proprietary + UEFI = taints kernel? I have well-known issue when after nvidia driver installation - system starts with black screen. If I log into command line, I can check logs:

*

*in xorg.log I see that "nvidia driver not found"

*in dmesg: "nvidia taints kernel"

What I have tried:

*

*installed driver from Ubuntu settings (drivers tab)

*installed driver from nvidia package (.run file)

*installed different kernels: 3.x.x and 4.8.15

*compiled custom kernel without signature verification

*disabled verification by mokutil

*installed ubuntu without secure boot (=disabled)

*all this was done on clean ubuntu each time
And NOTHING works.

But on Ubuntu 16 nvidia works from the box without issues on UEFI.
Problem that I really need Ubuntu 14.04 LTS for work (I use proprietary software which does not support Ubuntu 16).
Any ideas and/or working guide? I believe that it could be solved somehow. I do not need this license/secure issues, it is development system.


text:
Q: Searching for base CMS I'm searching for a PHP/MySQL based CMS with some basics like Register/Login.
It shouldn't be that complex like TYPO3.
Drupal and Joomla I don't want.

A: This is a list of notable Content Management Systems:

*

*Wikipedia: List of content management systems
We could pick one for you, but most probably it would be a better idea if you check their features from that list in order to be in a position to make a better informed decision.

A: Two that have been very good to me:

*

*Symphony CMS (not Symfony -- that's different) Symphony has a great community behind it, which is super uesful

*Frog CMS

A: You can try either of CMS Made Simple or One Page CMS

A: Another micro CMS: snewscms.com


text:
Q: Filter out dates in one worksheet if they are not in other worksheet in Tableau (EDITED FOR CLARITY)
I have a dashboard that compares a company selected by the user (Company A) to another group (Company B). One worksheet is their company (Company A), and the second worksheet is any other company selected by the user (Company B). These metrics are compared over time in a bar chart, however, some companies are missing data from some years. This means that one set of bar charts will have more bars than the other, creating an uneven looking visualization. Is there a way to filter out data points for the comparison companies (Company B) if there is no data in that year for the user's company (Company A)?
So the issue here is that Company B only has Var1, Var2, and Var3 for years 2012 and 2014, compared to company A which has all of the vars. The visualization works when there are all vars for the same years, but it breaks down when a Company is missing some of this information. I want it to be usable with a filter that the user can use from a drop down list, so I can't just hide things manually.

A: Instead of omitting values from one chart to make it "visually equivalent", you should show the missing values.
If your date field has the data type as Date - and not String / Numeric - you should be able to right-click the date axis and choose the "Show Missing Values" option, as both images below show:

If your field is set to String / Numeric, you'll need to change it either manually in the dataset or in Tableau by right-clicking and changing it to Date or Date/Time.
In the case you only have the year as value (e.g. 2012; 2013; 2014) - thus making it Numeric - you might want to use this workaround to create a new Date field:
DATE("1/1/" + STR(RIGHT( [Year] , 4)))


text:
Q: Drools Core DRL - Fire only one rule with the highest salience, skip other rules I have simple JAVA bean with two int fields: 'a' and 'b'.
I have two rules:
rule "First rule"
salience 10
when
    $bean : Bean ( a == 1)
then
    $bean.setB(10);
end

rule "Second rule"
salience 20
when
    $bean : Bean ( a == 1)
then
    $bean.setB(20);
end

Actual results: "Second rule" is fired first (higher salience), "First rule" is fired second.
Expected results: Only one rule (with the highest salience) is fired. Other rules are ignored. How to do this? Is it possible in Drools? I am using Drools 6.0.0 Final.
Requirements:
1. I can't use 'activation-group'.
2. I don't want to use 'retract' on each bean.
UPDATE
Really thanks for your answers.
Probably I should describe my problem in details.
I have a set of 1500 rules. Each rule:

*

*works with the same bean - this bean has a lot of fields (properties),

*has salience,

*has a lot of conditions,

*has only one action - setting one (always the same) boolean flag in my bean.

What I want to get?
When I have conflict (the input fact is matched by two or more rules) I want to fire only one rule with the highest salience. Other matched rules for this one fact should be ignored. The most important thing is performance - this should work as fast as possible.
What I do?
At the moment I have two solutions but I don't know which one is better or maybe I should solve this problem in different way.
Solution 1 - Statefull session
Java code:
for (Object fact : facts) {
    FactHandle fh = session.insert(fact);
    session.fireAllRules(1);
    session.delete(fh);
}

Solution 2 - Stateless session
Java code:
for (Object fact : facts) {
    session.execute(fact);
}

DRL file for solution 2:
I added to each rule the same activation-group:
rule "Rule"
activation-group "group"
salience X
when
    ...
then
    ...

A: Based on your question, I'm worried you might be misunderstanding the point of salience. Salience is a prioritization value. Drools uses it in order figure out which drool to fire first when it is the case that the constraints for more than one rule are satisfied.
The problem of [firing rule P under certain circumstances and NOT rule Q when rule P is fired] is a common one. Your object model should be set up such that this is a natural consequence of reasoning over your concept space. For the literal situation you have listed, you might try inserting a new fact into working memory ("RuleFiredFact" with a value of "2nd", or whatever). You would then check for this fact in your first rule constraints. If it is true, the first rule doesn't fire.
UPDATE:
To be clear, "RuleFiredFact" is an abstract placeholder for some concrete fact in your fact model. Part of the point of drools is not using abstract stuff in the drools DSL.
UPDATE:
Whether or not stateful vs. stateless session is appropriate is going to depend a lot on your available computer resources, object model, team, the list goes on. If you don't know which to use, you should refer to a discussion on the topic. You might try this older mailing list post http://drools.46999.n3.nabble.com/Advice-sought-on-choosing-Stateful-or-Stateless-sessions-td57069.html
Whichever you go with, I strongly suspect your object model is too shallow. It is very uncommon to create a drools system which contains one fact, then never creates any more. The point of drools is to reason over a number of facts. The way to tackle this is probably going to be something like moving through your object and inserting the information within it into the drools working memory as facts. You would then write rules which only fire under the constraints you want.
In a circumstance like what I describe, there are many ways of making sure only a single rule fires. Your rules may all be on the lookout for a "factWasAlreadyReasonedOverFact" with a reference to the fact which triggered the execution. This is a pretty rough example. Hopefully it gives you an idea.

A: First of all let me tell you that you have some weird scenario right here :)
There are multiple solutions for this problem:

*

*Use another attribute of Bean class to mark already 'processed' facts.

*Use a custom AgendaFilter

*Use ksession.fireAllRules(1);

Hope it helps,

A: You can use drools.halt(); in your highest salience rule.
What this do is it terminate the flow and come out of rule execution (exactly what you need).

A: I would solve this using activation-group with salience as you have described in Solution 2

A: One solution you can try is the "lock-on-active" attribute to avoid infinite execution loops involving one or more rules.
Lock-on-active is scoped by a rule-group and will prevent rules from re-firing as long as the group is focused. It does not depend on new facts, or updates to the existing ones, but only on the agenda focus. If you do not manipulate groups, this may be an option.


text:
Q: Error importing mahotas in python (missing dll file) I installed the mahotas library as the site says to but i keep getting the same error when i try to import the module:
Could not import submodules (exact error was: DLL load failed: The specified module could not be found.).

There are many reasons for this error the most common one is that you have
either not built the packages or have built (using `python setup.py build`) or
installed them (using `python setup.py install`) and then proceeded to test
mahotas **without changing the current directory**.

Try installing and then changing to another directory before importing mahotas.

Someone knows what i'm doing rong?

A: You seem to be on Windows.
For that platform, I recommend you try these compiled packages: http://www.lfd.uci.edu/~gohlke/pythonlibs/
(I'm the author of mahotas)


text:
Q: Delphi program prevents windows shutting down properly I have a small program which simply reads a diary text file and displays it in a memo - thats it - no buttons you double click on the form to shut it down if you want it to disappear.  When it has been run (even if you close it) windows XP gets as far as "Windows is shutting down" ie. after "Saving User Settings" etc and then it hangs.  I have examined the code which appears little different from other programs I have written which were much more complicate but can see nothing wrong - the close routine for example contains application.terminate which (I think) should clear anything wrong out of memory anyway.  Any ideas since I seem to have run out of them?

A: Based on what you've described, the program should have a single line of programmer-added code, which is to call Memo1.Lines.LoadFromFile. That's what it means when you say, "That's it."
That program doesn't even need a "close routine." (I assume you mean the form's OnClose event.) When the main form closes, the application terminates itself automatically. That's how all Delphi programs work. If you're putting more on top of that, you're doing too much.

A: Just a few suggestions, because it is not entirely clear what your problem is.
Does your application has problems with closing, or does it hang during windows shutdown?

*

*Have you tried putting a breakpoint on application.Terminate? And does that provide extra information.

*From within the mainform, you can use Close and not Application.Terminate.

A: Apps can inhibit shutdown if they are using up CPU time, although a 'modern' OS like Vista and W7 should show a dialog telling you about this after a period and offering to let you abort the app. Check that your app is showing 0% CPU when its idle by looking in task manager and viewing 'processes'.
Bri

A: The following code reacts on the windows shutdown message und closes the program.
TForm1 = class(TForm)
    ...
private
    procedure WMEndSession(var Message: TWMEndSession); message WM_ENDSESSION;
    ...
end;

procedure TForm1.WMEndSession(var Message: TWMEndSession);
begin
    close;
end;


text:
Q: Rails Query Unique Items I have a search bar which works fine but it produces a duplicate every time it shows the correct result.
if params[:nav_search]
  @art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).page(params[:page]).per_page(18)
end

Any clue where I'm going wrong?

A: Try to the following
@art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)

To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
You can see this Rails Guide for very well understand

A: include .uniq
try this,
if params[:nav_search]
  @art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).uniq.page(params[:page]).per_page(18)
end

A: Use uniq or distinct to avoid duplicate records. In your case, you should use distinct:
if params[:nav_search]
  @art = Art.where(["style_number LIKE ? OR name LIKE ?", "%#{params[:nav_search]}%", "%#{params[:nav_search]}%"]).distinct.page(params[:page]).per_page(18)
end


text:
Q: jQuery: My click-event-method function is being entered only for some buttons, although they all have the exact same class I have a few forms rendered from a Django modelFormset. For each form I create an "Insert" button next to it to add a new form after it. When I load the page, the forms are rendered from the database rows, then I click on any insert button and my new form is added. Now, when I click on the insert button that's next to that newly created form, nothing happens, the function inside my click-event method is not even entered. These buttons have all the same class.
I'm creating the new form by cloning the div element that contains it, then changing its attributes, and then inserting it.
Here's what my template looks like before adding a new form. I only have two rows in my database table right now, the ones I created manually for testing.

    <form method="POST" class="note-form">
        <input type="hidden" name="csrfmiddlewaretoken" ...>

...

                <input type="number" name="form-0-note_number" value="1" class="disabled" readonly="readonly" id="id_form-0-note_number">
                <textarea name="form-0-note_text" cols="100" rows="8" id="id_form-0-note_text">This is the first note</textarea>
                <button id="ins-after-1" class="ins-note-after" type="button" value="ins-after-1">Insert</button>
                <input type="hidden" name="form-0-id" value="60" id="id_form-0-id">

                <input type="number" name="form-1-note_number" value="2" class="disabled" readonly="readonly" id="id_form-1-note_number">
                <textarea name="form-1-note_text" cols="100" rows="8" id="id_form-1-note_text">This is the second note</textarea>
                <button id="ins-after-2" class="ins-note-after" type="button" value="ins-after-2">Insert</button>
                <input type="hidden" name="form-1-id" value="61" id="id_form-1-id">

    </form>

This is my JavaScript to add the buttons to the form and create the new forms.
It's probably not very clean. I'm still a beginner with JavaScript.

After clicking on any of those two buttons, a new form is added properly. Like this:
(Please see the comments)

    <form method="POST" class="note-form">
        <input type="hidden" name="csrfmiddlewaretoken" ...>

...

                <input type="number" name="form-0-note_number" value="1" class="disabled" readonly="readonly" id="id_form-0-note_number">
                <textarea name="form-0-note_text" cols="100" rows="8" id="id_form-0-note_text">This is the first note</textarea>
                <button id="ins-after-1" class="ins-note-after" type="button" value="ins-after-1">Insert</button>
                <input type="hidden" name="form-0-id" value="60" id="id_form-0-id">

                <input type="number" name="form-1-note_number" value="2" class="disabled" readonly="readonly" id="id_form-1-note_number">

                <textarea name="form-1-note_text" cols="100" rows="8" id="id_form-1-note_text"></textarea>
                <button id="ins-after-2" class="ins-note-after" type="button" value="ins-after-2">Insert</button>
                <input type="hidden" name="form-1-id" value="61" id="id_form-1-id">

                <input type="number" name="form-2-note_number" value="3" class="disabled" readonly="readonly" id="id_form-2-note_number">

                <textarea name="form-2-note_text" cols="100" rows="8" id="id_form-2-note_text">This is the second note</textarea>
                <button id="ins-after-3" class="ins-note-after" type="button" value="ins-after-3">Insert</button>

                <input type="hidden" name="form-2-id" value id="id_form-2-id">

    </form>

I can click the insert button at the first note again and another new note will be added after it, or at the last note, and a new note will be added after it too. The problem is when clicking the buttons of the notes that were added with this code. Nothing happens, the function is not entered. I'm making sure their class is exactly the same, but still, the function is not even entered.


text:
Q: php qr code not generating on server by using google api gives a file with nothing in it i am using Google API for creating QR Codes but it gives me a file with nothing in it.
my code something like that
$file = file_get_contents('https://chart.googleapis.com/chart?cht=qr&chs=177x177&chl=Hello World');
move_uploaded_file($file, $path.$file);

i tried most of the thing but clueless
please if anyone can help me. thanks in advance.

A: Google Chart API can create QR for you. but you need some conversion and stick to the basics if you want accurate response from API
i can see you are saving the response in $file can may be a reason to save the name in db.
so why not do it like this
$path = $folder_path.$file;
//Note:  you need to give the server path; not the URL

but wait... you are creating a QR code for a String saying "Hello World", there is a blank space in the string and you are passing that string with the get method in the url so you need url encoding to encode the spaces to "%20" and so on... for correct url passing.
adding this will solve the problem
$my_qr_string = urlencode("Hello World");

another thing you are missing is character support for the QR
try using "UTF-8" character encoding to avoid any issues.
for uploading use file_put_contents() method for assured upload
in the end you got
file_put_contents($path, file_get_contents('https://chart.googleapis.com/chart?cht=qr&chs=177x177&choe=UTF-8&chl='.$my_qr_string));


text:
Q: Combinatorial identity: summation of stars and bars I noticed that the following identity for a summation of stars and bars held for specific $k$ but I was wondering if someone could provide a general proof via combinatorics or algebraic manipulation. I wouldn't be surprised if this is a known result; it looks very similar to the Hockey Stick identity.
$$\sum_{i=0}^k {d+i-1 \choose d-1} = {d+k \choose k}$$
The left can be immediately rewritten as $\sum_{i=0}^k {d+i-1 \choose i}$ if it helps inspire intuition.

A: Consider the set $S=\{1,2,\ldots,d,d+1,\ldots,d+k\}$. The right hand side gives us the number of ways selecting a subset of $S$ of $d$ elements.
If we choose such a subset $X$ of $S$ of $d$ elements, the highest element of $X$ can be $d,d+1,\ldots,d+k$. If the highest element of $X$ is $d+i$ then we can find $d-1$ more elements of $X$ from $\{1,2,\ldots,d+i-1\}$. The number of ways that we can do that is ${d+i-1\choose d-1}$. By running $i$ from $0$ to $k$ we have the left hand side of the identity.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\sum_{i = 0}^{k}{d + i - 1 \choose d - 1} =
{d + k \choose k}:\ {\LARGE ?}}$.

\begin{align}
&\bbox[10px,#ffd]{\sum_{i = 0}^{k}{d + i - 1 \choose d - 1}} =
\sum_{i = 0}^{k}{d + i - 1 \choose i}
\\[5mm] = &\
\sum_{i = 0}^{k}{-\bracks{d + i - 1} + i - 1 \choose i}
\pars{-1}^{i} =
\sum_{i = 0}^{k}\pars{-1}^{i}{-d \choose i}
\\[5mm] = &\
\sum_{i = 0}^{k}\pars{-1}^{i}\bracks{z^{i}}\pars{1 + z}^{-d} =
\bracks{z^{0}}\pars{1 + z}^{-d}
\sum_{i = 0}^{k}\pars{-\,{1 \over z}}^{i}
\\[5mm] = &\
\bracks{z^{0}}\pars{1 + z}^{-d}\,
{\pars{-1/z}^{k + 1} - 1 \over \pars{-1/z} - 1}
\\[5mm] = &\
\bracks{z^{0}}\pars{1 + z}^{-d}\,
{z \over z^{k + 1}}\,{\pars{-1}^{k + 1} - z^{k + 1} \over -1 - z}
\\[5mm] = &\
\bracks{z^{k}}\pars{1 + z}^{-d - 1}\,
\bracks{z^{k + 1} - \pars{-1}^{k + 1}} =
\pars{-1}^{k}\bracks{z^{k}}\pars{1 + z}^{-d - 1}
\\[5mm] = &\
\pars{-1}^{k}{-d - 1 \choose k} =
\pars{-1}^{k}\braces{%
{-\bracks{-d - 1} + k - 1 \choose k}\pars{-1}^{k}}
\\[5mm] = &\ \bbx{d + k \choose k} \\ &
\end{align}

A: Starting from
$$\sum_{q=0}^k {d+q-1\choose d-1}$$
we get
$$\sum_{q\ge 0} {d+q-1\choose d-1} [[0\le q\le k]]
= \sum_{q\ge 0} {d+q-1\choose d-1} [z^k] \frac{z^q}{1-z}
\\ = [z^k] \frac{1}{1-z} \sum_{q\ge 0} {d+q-1\choose d-1} z^q
= [z^k] \frac{1}{1-z} \frac{1}{(1-z)^d}
\\ = [z^k] \frac{1}{(1-z)^{d+1}}
= {d+k\choose k}.$$


text:
Q: Angular ngIf removes input checked value Take the following ngIf conditional:
ms-aside.component.html
<div *ngIf="showFilters">
  ...
  <input type="checkbox" checked="" />
  <input type="checkbox" checked="checked" />
  <input type="checkbox" checked="checked" />
  ...
</div>

Whenever the showFilters variable is changed to a falsy value, my input checked value states are lost. As in, when I re-assign the showFilters variable to a truthy value, the checked values are reset to none.
Can anyone shed some light on why that is, and how I can work around this issue?

A: The reason is actually pretty simple: The children of an element with *ngIf === false are removed from the DOM.
So, whenever you change showFilters to false, the inputs are removed. And when you change it to true, new instances are then added to the DOM.
To fix this, you will have to control them, i.e. store the value of the checked state in your component and bind it to the inputs.

A: When you use *ngIf, the following element is removed from the DOM if the condition is false. If you want to retain the states [hidden] might work for you as it just hides the element but does not remove the element from DOM.


text:
Q: how to iterate through hashmap and store entities into mysql sorry I am a newbie I have been looking for an example on how I can iterate hashmap and store the entities into MySQL database. the blow code downloads currency rate which I would like to store into my database. the output is
{CCY=USD, RATE=1.5875}
{CCY=EUR, RATE=1.1919}
{CCY=ALL, RATE=166.2959}
{CCY=AMD, RATE=645.4025}

how  can I iterate the HashMap and store it into my database? an illustration would be nice or source similar to this scenario.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Rate {
    /** list of string array containing IOSCurrencyCodes*/
        final String[] CURRENCY = new String[] { "USD","EUR","ALL","AMD",};

        @SuppressWarnings("rawtypes")
        void checkRateAllAtEnd() throws Exception {
                List<Callable<HashMap>> tasks = new ArrayList<Callable<HashMap>>();
                for (final String ccy : CURRENCY) {
                        tasks.add(new Callable<HashMap>() {
                                public HashMap<String, Comparable> call() throws Exception {
                                        return getRates(ccy);
                                }
                        });
                }
                ExecutorService executorPool = Executors.newCachedThreadPool();
                final List<Future<HashMap>> listRates = executorPool.invokeAll(tasks, 3600, TimeUnit.SECONDS);

                for (Future<HashMap> rate : listRates) {
                        HashMap ccyRate = rate.get();

                        System.out.println(ccyRate);
                     }
                }
                @SuppressWarnings("rawtypes")
                public HashMap<String, Comparable> getRates(String ccy) throws Exception {
                        URL url = new URL("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=GBP"
                                                        + ccy + "=X");
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        url.openStream()));

                        String data = reader.readLine();
                        String[] dataItems = data.split(",");
                        Double rate = Double.valueOf(dataItems[1]);

                        HashMap<String, Comparable> ccyRate = new HashMap<String, Comparable>();
                        ccyRate.put("CCY", ccy);
                        ccyRate.put("RATE", rate);

                        return ccyRate;
                }
        public static void main(String[] args) {
            Rate ccyRate = new Rate();
                try {
                       //ccyConverter.checkRateSequential();
                       ccyRate.checkRateAllAtEnd();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}

A: Map provides entrySet method which is very useful to iterate over a map.

Map#entrySet  returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress.
ref - link

Code -
HashMap<String, Comparable> ccyRate = new HashMap<String, Comparable>();
for(Map.Entry<String, Comparable> entry: ccyRate.entrySet){
    System.out.println(entry.getKey()+" - "+entry.getValue());
}


text:
Q: Looking for the simplest way to connect kivy front end/UI to back-end python for chess game? I wrote a command line-chess game in Python and am searching for the simplest way to add a Kivy UI to it so it can be played on desktop.  The game state is stored in my python program as a list of lists and values are updated/replaced etc when players make a move.  Here is how it is stored:
Chess - setup_grid ## [[],[]...]
  ________________________
8[r, n, b, q, k, b, n, r]
7[p, p, p, p, p, p, p, p]
6[ ,  ,  ,  ,  ,  ,  ,  ]
5[ ,  ,  ,  ,  ,  ,  ,  ]
4[ ,  ,  ,  , P,  ,  ,  ]
3[ ,  ,  ,  ,  ,  ,  ,  ]
2[P, P, P, P,  , P, P, P]
1[R, N, B, Q, K, B, N, R]
  ________________________
 [A, B, C, D, E, F, G, H]

I would like to connect a Kivy UI to this game state so that a chessboard is displayed and images of pieces appear on top of their correct square(i.e. whitepawn.jpeg appears over each square corresponding to "P", etc).  Piece values would be retrieved via thir list indices in setup_grid above.
For anyone knowledgeable about the capabilities of Kivy, what would be simplest way to do this?  I've considered the following:

*

*Creating a Background Image of a chessboard and then having piece images move in relative position to the background image.

*Creating a list of 64 buttons with black and white backgrounds whose image values change.
3.......?

I've never built a UI of any kind and I feel like I'm overcomplicating this significantly so would love to know if anyone has an easier idea of how to do this efficiently.  Thanks!
I attempted #2 --Creating a list of 64 buttons with black and white backgrounds whose image values change.
When I tried this, I could get the chess squares (as buttons) to have black and white backgrounds correctly.  However, if I tried to add an image over top of it, it would negate the entire background color (so it would appear as either a black/white square OR as a picture of a pawn, but not a pawn on top of a black/white background.
I was expecting to be able to simply have fixed background colors for the buttons and dynamic/changing image background values to be superimposed on top.  It does not appear to be possible.


text:
Q: How to set defalult selected items in selectOneRadio/selectCheckboxMenu by beans in primefaces I want to create selectOneRadio list and selectCheckboxMenu which items get from related bean objects.
For non selected list it is working well.But how can i provide these lists with some item(s) selected by default.
My current selectCheckboxMenu code is like this.
<p:selectCheckboxMenu id="trdays"
             value="#{mybean.selectedDay}"
             label="Select Days">
      <f:selectItems value="#{mybean.dayList}" var="day"
       itemValue="#{day.value}" itemLabel="#{day.name}"/>
</p:selectCheckboxMenu>

it should look like this when page loaded and user haven't done anything yet.

EDIT
Day Class :-
public class Day{

  private String name;
  private String value;

  //getters and setters

}

A: Value attribute of selectCheckboxMenu component should get the your default values.
On bean side you should write a getter for selectedDayList and all daylist.
Example:
@PostConstruct
public void init() {
            dayList= new ArrayList<String>();
            dayList.add("Mon");
            dayList.add("Tue");
            dayList.add("Wed");
            dayList.add("Thu");
            dayList.add("Fri");
            dayList.add("Sat");
            dayList.add("Sun");

            selectedDayList= new ArrayList<String>();
            selectedDayList.add("Tue");
            selectedDayList.add("Wed");
}

public List<String> getDayList()
    {
        return dayList;
    }

public List<String> getSelectedDaylist()
    {
        return selectedDayList;
    }

.xhtml page should be like this.
<p:selectCheckboxMenu id="trdays"
             value="#{mybean.selectedDaylist}"
             label="Select Days">
      <f:selectItems value="#{mybean.dayList}" var="day"
       itemValue="#{day.value}" itemLabel="#{day.name}"/>
</p:selectCheckboxMenu>

Good Luck!

A: Just add default values in the selectedDay list (or array) in init method (with @PostConstruct annotation). These values should have same value as corresponding itemValue attribute (in your case this is day.value).


text:
Q: Telerik RadTreeView And Client-Side Expand/Collapse I'm following this approach to expanding and collapsing all nodes in client JavaScript: http://www.telerik.com/help/aspnet/treeview/tree_expand_client_side.html
However, it's taking a  REALLY long time to process this, and after expanding then collapsing, I get the "script unresponsive" error, so I was wondering if there was a way to speed this up for a rather large tree?  Is there a better way to parse it?  Currently, the tree is 4 levels deep.
Thanks.

A: Start off getting your nodes with yourtreeViewInstance.get_nodes(), and then the child nodes as eachChildNode.get_nodes() and so on down the hierarchy.
Then you can expand each item by calling .set_expanded(true); on each node you want to expand.

A: I got around the "script unresponsive" errors by expanding and collapsing the tree asynchronously. In addition, I expand from the bottom (so you can see the nodes expand) and collapse from the top, but only when it gets to the last node in each branch, so visually it's far more interesting to the user. They can actually see it happen, and if it's not fast (IE7 and before is particularly slow), it's at least entertaining while they wait.
var treeView, nodes;

function expandAllNodesAsynchronously() {
    if (<%= expandedLoaded.ToString().ToLower() %>) {
        treeView = $find("<%= tv.ClientID %>");
        nodes = treeView.get_allNodes();
        if (nodes.length > 1) {
            doTheWork(expandOneNode, nodes.length);
        }
        return false;
    } else
        return true;
}

function expandOneNode(whichNode) {
    var actualNode = nodes.length - whichNode;
    if (nodes[actualNode].get_nextNode() == null) {
        nodes[actualNode].get_parent().expand();
    }
}

function collapseAllNodesAsynchronously() {
    treeView = $find("<%= tv.ClientID %>");
    nodes = treeView.get_allNodes();
    if (nodes.length > 1) {
        doTheWork(collapseOneNode, nodes.length);
    }
}

function collapseOneNode(whichNode) {
    if (nodes[whichNode].get_nextNode() == null && nodes[whichNode].get_parent() != nodes[0]) {
        nodes[whichNode].get_parent().collapse();
    }
}

function doTheWork(operation, cycles) { //, callback
    var self = this, // in case you need it
        cyclesComplete = 1,
        batchSize = 10; // Larger batch sizes will be slightly quicker, but visually choppier

    var doOneBatch = function() {
        var c = 0;
        while(cyclesComplete < cycles) {
            operation(cyclesComplete);
            c++;
            if(c >= batchSize) {
                // may need to store interim results here
                break;
            }
            cyclesComplete++;
        }
        if (cyclesComplete < cycles) {
            setTimeout(doOneBatch, 1); // "1" is the length of the delay in milliseconds
        }
        else {
            // Not necessary to do anything when done
            //callback(); // maybe pass results here
        }
    };

    // kickoff
    doOneBatch();
    return null;
};


text:
Q: Visual Studio Shell And F# (invalid license) Does anyone have any experience with installing the Visual Studio Isolated Shell and using it with F#?
It installed successfully, but when I click on the devenv.exe, it opens VS, but gives me the error "Invalid License Data. Reinstall is required". I have done that many times to no avail.
Googling for this issue, I find that devenv.exe is not supposed to work in this isolated mode directly, but rather, I should have another custom executable that targets the VS Shell. This seems to be true for IronPython Studio which I downloaded and works fine.
However, I cannot believe there isn't anything similar for F#. Any input in this matter is greatly appreciated.

A: F# requires the VS Integrated Shell.
See also
https://stackoverflow.com/questions/196765/what-is-the-minimum-list-of-tools-required-to-work-on-f-does-express-edition-wo


text:
Q: Attaching all documents in a drive folder then send it as an email I've spent several days searching this and I find answers pretty close to what I'm looking for but not exactly it. I'm new to coding and trying to learn based on need + researching on the side.
Open Google sheet, inside would have a button that runs this script (I can do this now).
This sheet is used repeatedly and can be saved in different folders. It's used as a request form, in the same folder are additional documentations for the request.
I want the script to send the Active Sheet as well as 'All' other files in the same folder as an email attachment (could possibly use a link but rather the entire file).
It will then be sent to the recipients (that part of the code is not listed below)
Below is what I have so far: (This lists all files in the active folder and puts it in the Sheet, this is not necessary if there is another way). I then need it to attach each file-ID as an attachment. The folder structure is something like
Also, I'm still trying to understand setting the MIME, is there a way that can capture several different file types? PDF, JPG and XLSX...?
root\Person_Name\UniqueFolderName\
function listFiles() {

var ss = SpreadsheetApp.getActiveSheet();
var ssID = SpreadsheetApp.getActive().getId();
var folderID = DriveApp.getFolderById(ssID).getParents();
var foldernewID = folderID.next().getId();
var files = DriveApp.getFolderById(foldernewID).getFiles();
var list = [];

list.push(['Name', 'ID', 'Size']);

while (files.hasNext()){
file = files.next();
var row = [];
row.push(file.getName(),file.getId(),file.getSize())
list.push(row);
}

ss.getRange(1,1,list.length,list[0].length).setValues(list);
Logger.log(list);
}

Also, the additional file types in the folder are .xlsx and .pdf
Any help would be greatly appreciated or pointing me in the right direction, I've tried several sites and most show attaching 1-2 files using their ID built in the script, my IDs will always be new and there could be more than 2-3+ so need a loop or something.
Thank you


text:
Q: Simulate a rope bridge I've been modeling a rope bridge, and I wanted to simulate someone walking on it, with the bridge movement and so on. For that, I've tried creating some ropes to wrap the planks and so on, and add physics to the ropes and planks, but they don't work not even by chance, either they keep shaking until they fall, or they explode and any other situation you can imagine.
I also thought about adding an armature but deformations are ugly, and the armature goes in one direction so if I try to move the opposite side of the bridge it doesn't look realistic either.
Then I've thought about constraints, but it's not feasible for the ropes unless I split them into million pieces (unless I'm missing something).

A: You can apply rigidbody physics on the planks and softbody physics on the rope. Adjust the stiffness of the rope until it  works fine. make sure to change the deformation of the planks from convex hull to mesh. If there is still some problem like blowing up or breaking apart, try lowering the weight of the planks and try scaling up everything.


text:
Q: pandas read_csv cannot use dtype does not work on the column names I have the following data
PERMNO Names,Date,Ticker Symbol,Company Name,CUSIP Header
10000,19851231,,,68391610
10000,19860331,OMFGA,OPTIMUM MANUFACTURING INC,68391610
10001,19851231,,,36720410
10001,19860131,GFGC,GREAT FALLS GAS CO,36720410
10001,19860228,GFGC,GREAT FALLS GAS CO,36720410

I have the following data
PERMNO Names,Date,Ticker Symbol,Company Name,CUSIP Header
10000,19851231,,,68391610
10000,19860331,OMFGA,OPTIMUM MANUFACTURING INC,68391610
10001,19851231,,,36720410
10001,19860131,GFGC,GREAT FALLS GAS CO,36720410
10001,19860228,GFGC,GREAT FALLS GAS CO,36720410

I am coming this command
pd.read_csv(csv_file_path, index_col=["CUSIP Header"],
            dtype = {"CUSIP Header": str}, usecols =["Date", "CUSIP Header"],
            parse_dates=['Date'])

however, it seems like the CUSIP Headers are not parsed as str but as floats. Indeed when I tried to call
print (actual.xs("68391610"))

I got a key error.

A: It is bug 9435, so remove index_col parameter and use set_index:
df = pd.read_csv(csv_file_path,
            dtype = {'CUSIP Header': str}, usecols =["Date", "CUSIP Header"],
            parse_dates=['Date']).set_index('CUSIP Header')

print (df)
                   Date
CUSIP Header
68391610     1985-12-31
68391610     1986-03-31
36720410     1985-12-31
36720410     1986-01-31
36720410     1986-02-28

print (df.index)
Index(['68391610', '68391610', '36720410', '36720410', '36720410'],
       dtype='object', name='CUSIP Header')


text:
Q: What happens when mongoDB is shut down? I'm new to Node and MongoDB and recently began using the database for my project. When I shut down the server with the following commands

*

*use admin

*db.shutdownServer()

and then again restart the server with the mongod command I find the databases I have created to be deleted. Why does this happen? What is the way to store the databases permanently?


text:
Q: Convexity in each argument and directional derivative Let $f(x,y)$ be a continuous function, convex in each argument separately. Does this imply the existence of one-sided directional derivatives in any direction? For example, does there exist (finite or infinite) $\lim\limits_{t\to 0+} \frac{f(t,t)-f(0,0)}{t}$?

A: Any convex function $f:\mathcal{D}\mapsto\mathbb{R}$ is directionally-differentiable (in any direction) on its relative interior, where $\mathcal{D}\subset\mathbb{R}^n$. Stated symbolically: $$\forall x \in \mathbf{relint}\mathcal{D}, v\in\mathbb{R}^n: f^\prime(x;v) \text{ exists}$$ and $|f^\prime(x;v)| < \infty$.
Just as a side note: If $f$ is convex, then the directional derivative $f^\prime(x;v)$ is convex in its second argument, the direction. For this, check out this other stack exchange question.


text:
Q: How to show appropriate page on mobile I want to capture some blog from some blog sites. I know to use HttpClient to get the html string, and then use Html Agility Pack to capture the content under the specific html tag. But if you use WebView to show this html string, you will find that it's not good in mobile. For example, css style will not be loaded correctly. Some code-blocks will not auto wrap. Some pictures will not show (It will show x).
Some advertisements also will show, but I don't want it.
Do anyone know how to get it? Any suggestions will be apprieciate.

A: Try running the html string through something like Google Mobilizer.  This should make a more mobile friendly html string which you can then use the Agility pack to 'unpack'

A: Ideally you should capture the HTML page and all its associated resources: CSS files, images, scripts, ...
And then updates the HTML content so that resources are retrieved from your local data storage (for example, relative URL will not work anymore if you saved the HTML page locally).
You may also send your HTTP Request with a User-Agent header that corresponds to the one used by Microsoft browser in order to obtain the corresponding version from the website (if they do some kind of User-Agent sniffing).


text:
Q: Number of Ways To arrange Sequence I am having a M character, from these character i need to make a sequence of length N such that no two consecutive character are same and also first and last character of the sequence is fix. So i need to find the total number of ways.
My Approach:
Dynamic programming.
If first and last character are '0' and '1'
dp[1][0]=1 , dp[1][1]=1

for(int i=2;i<N;i++)
    for(int j=0;j<M;j++)
         for(int k=0;k<M;k++)
                  if(j!=k) dp[i][j]+=dp[i-1][k]

So final answer would summation dp[n-1][i] , i!=1
Problem:
Here length  N is too large around 10^15 and M is around 128, how find the number of permutation without using arrays ?

A: Assume M is fixed. Let D(n) be the number of sequences of length n with no repeated characters where the first and last character differ (but are fixed). Let S(n) be the number of sequences of length n where the first and last characters are the same (but are fixed).
For example, D(6) is the number of strings of the form a????b (for some a and b -- noting that for counting it doesn't matter which two characters we chose, and where the ? represent other characters). Similarly, S(6) is the number of strings of the form a????a.
Consider a sequence of length n>3 of the form a....?b. The ? can be any of m-1 characters (anything except b). One of these is a. So D(n) = S(n-1) + (m-2)D(n-1). Using a similar argument, one can figure out that S(n) = (M-1)D(n-1).
For example, how many strings are there of the form a??b? Well, the character just before the b could be a or something else. How many strings are there when it's a? Well, it's the same as the number of strings of the form a?a. How many strings are there when it's something else? Well it's the same as the number of strings of the form a?c multiplied by the number of choices we had for c (namely: m-2 -- everything except for a which we've already counted, and b which is excluded by the rules).
If n is odd, we can consider the middle character. Consider a sequence of length n of the form a...?...b. The ? (which is in the center of the string) can be a, b, or one of the other M-2 characters. Thus D(2n+1) = S(n+1)D(n+1) + D(n+1)S(n+1) + (M-2)D(n+1)D(n+1). Similarly, S(2n+1) = S(n+1)S(n+1) + (M-1)D(n+1)D(n+1).
For small n, S(2)=0, S(3)=M-1, D(2)=1, D(3)=M-2.
We can use the above equations (the first set for even n>3, the second set for odd n>3, and the base cases for n=2 or 3 to compute the result you need in O(log N) arithmetic operations. Presumably the question asks you to compute the result modulo something (since the result grows like O(M^(N-2)), but that's easy to incorporate into the results.
Working code that uses this approach:
def C(n, m, p):
    if n == 2:
        return 0, 1
    if n == 3:
        return (m-1)%p, (m-2)%p
    if n % 2 == 0:
        S, D = C(n-1, m, p)
        return ((m-1) * D)%p, (S + (m-2) * D)%p
    else:
        S, D = C((n-1)//2+1, m, p)
        return (S*S + (m-1)*D*D)%p, (2*S*D + (m-2)*D*D)%p

Note that in this code, C(n, m, p) returns two numbers -- S(n)%p and D(n)%p.
For example:
>>> p = 2**64 - 59  # Some large prime
>>> print(C(4, 128, p))
>>> print(C(5, 128, p))
>>> print(C(10**15, 128, p))

(16002, 16003)
(2032381, 2032380)
(12557489471374801501, 12557489471374801502)

Looking at these examples, it seems like D(n) = S(n) + (-1)^n. If that's true, the code can be simplified a bit I guess.
Another, perhaps easier, way to do it efficiently is to use a matrix and the first set of equations. (Sorry for the ascii art -- this diagram is a vector = matrix * vector):
(D(n)) = (M-2  1) * (D(n-1))
(S(n)) = (M-1  0)   (S(n-1))

Telescoping this, and using that D(2)=1, S(2)=0:
(D(n)) = (M-2  1)^(n-2) (1)
(S(n)) = (M-1  0)       (0)

You can perform the matrix power using exponentiation by squaring in O(log n) time.
Here's working code, including the examples (which you can check produce the same values as the code above). Most of the code is actually matrix multiply and matrix power -- you can probably replace a lot of it with numpy code if you use that package.
def mat_mul(M, N, p):
    R = [[0, 0], [0, 0]]
    for i in range(2):
        for j in range(2):
            for k in range(2):
                R[i][j] += M[i][k] * N[k][j]
                R[i][j] %= p
    return R

def mat_pow(M, n, p):
    if n == 0:
        return [[1, 0], [0, 1]]
    if n == 1:
        return M
    if n % 2 == 0:
        R = mat_pow(M, n//2, p)
        return mat_mul(R, R, p)
    return mat_mul(M, mat_pow(M, n-1, p), p)

def Cmat(n, m, p):
    M = [((m-2), 1), (m-1, 0)]
    M = mat_pow(M, n-2, p)
    return M[1][0], M[0][0]

p = 2**64 - 59
print(Cmat(4, 128, p))
print(Cmat(5, 128, p))
print(Cmat(10**15, 128, p))

A: You only need to count the number of acceptable sequences, not find them explicitly. It turns out that it doesn't matter what the majority of the characters are. There are only 4 kinds of characters that matter:

*

*The first character

*The last character

*The last-used character, so you don't repeat characters consecutively

*All other characters

In other words, you don't need to iterate over all 10^15 characters. You only need to consider the four cases above, since most characters can be lumped together into the last case.


text:
Q: Spivak Calc Ch 1 Problem 4(iii) I would like to follow up on a similar question.
Find all numbers  $x$ for which $$5 - {x}^{2} < -2$$
Omitting the intermediate steps, we get $${x}^{2} > 7$$
Now, I would like to rigidly proceed.
My approach was ${x} > \pm  \sqrt{7}$, which correctly gives me ${x} > \sqrt{7}$, but following my logic would also give me ${x} > - \sqrt{7}$, which is clearly incorrect.
So, assuming at this point I have no knowledge of quadratic functions, or plotting the points on a number line, or upward, downward facing graphs,  can someone guide to the correct answer of $x > \sqrt{7}$ or $x < -\sqrt{7}$
Thanks in advance.

A: What is needed is a standard way of attacking a problem similar to $x^2 > 7.$
Note 1:
If $0 < r,s, k$ then
$r < s \iff r^k < s^k.$
This holds for all positive real numbers $r,s, k$.
This assertion is based on the idea that for $x > 0, f(x) = x^k$
is a strictly increasing function.
The assertion is basic to Calculus.  In the pre-Calculus world, you can simply consider what the graph of $f(x) = x^k ~: ~0 < x,k ~: ~$ looks like.
Note 2:
If you have an inequality, and you multiply both sides of the inequality by a negative number, then you reverse the direction of the inequality.
For example, if $0 < a,b$, then you have that
$a < b \iff (-a) > (-b).$
Note 3:
When comparing a variable $x$ to the expression $\sqrt{x^2}$, you have the convention that the square root function always unambiguously refers to a non-negative value.
Thus, if $x \geq 0$, then $x = \sqrt{x^2}.$
If $x < 0$, then $(-x) = \sqrt{x^2}.$

Consider the problem $x^2 > 7.$
Based on note 1, this implies that
$$\sqrt{x^2} > \sqrt{7}.\tag 1$$
You now have to break the problem into two cases, depending on whether $x \geq 0$, or $x < 0$.  Each case becomes a separate inequality to be solved.

$\underline{\text{Case 1:} ~x \geq 0}.$
By Note 3, inequality (1) above becomes
$x > \sqrt{7}.$
This means that in order to find values of $x$ that satisfy the inequality under Case 1, two separate constraints must be simultaneously satisfied:

*

*$x \geq 0.$

*$x > \sqrt{7}$.

If the 2nd constraint above is satisfied, then the 1st constraint above will automatically be satisfied.  Therefore, the Case 1 solution is that
$x > \sqrt{7}$.

$\underline{\text{Case 2:} ~x < 0}.$
By Note 3, inequality (1) above becomes
$(-x) > \sqrt{7}.$
Using Note 2 above, the constraint may be re-expressed as
$x  = (-1) \times (-x) < (-1) \times \sqrt{7} = -\sqrt{7}.$
This simplifies to $x < -\sqrt{7}.$
This means that in order to find values of $x$ that satisfy the inequality under Case 2, two separate constraints must be simultaneously satisfied:

*

*$x < 0.$

*$x < -\sqrt{7}$.

If the 2nd constraint above is satisfied, then the 1st constraint above will automatically be satisfied.  Therefore, the Case 2 solution is that
$x < -\sqrt{7}$.

Therefore, when the values of $x$ that satisfy Case 1 are combined with the values of $x$ that satisfy Case 2, you have that
$$ x > \sqrt{7} ~~\text{or}~~ x < -\sqrt{7}.$$

A: $X^2<7 \implies (x+\sqrt{7})(x-\sqrt{7}) >0$
$AB>0 \implies (1) A>0 \& B>0$. OR (2) A<0 & B<0$
So (1): $x>-\sqrt{7} ~\& ~ x>\sqrt{7} \implies  x> \sqrt{7}$.
(2): $x<-\sqrt{7} ~\&~ x <\sqrt{7} \implies x <-\sqrt{7.}$
Finally the solution is $x \in (-\infty;-\sqrt{7}) \cup (\sqrt{7}, \infty)$ Or alternatively $x<-\sqrt{7}$ or $x>\sqrt{7}$.

A: In general, in real analysis, $$x^2>p^2\iff |x|>|p|.$$
Therefore, $$x^2>7\\\iff x^2>(\sqrt7)^2\\\iff|x|>|\sqrt7|=\sqrt7\\\iff x<-\sqrt7\quad\text{or}\quad x>\sqrt7.$$
Alternatively, $$x^2>7\\\iff x^2>(-\sqrt7)^2\\\iff|x|>|-\sqrt7|=\sqrt7\\\iff x<-\sqrt7\quad\text{or}\quad x>\sqrt7.$$


text:
Q: trouble with workflow when saving a record I'm working on a workflow on audit module, I added the workflow into the view as follows:
in audit.xml:
<header>
<button name="button_close" string="Close" states="opened" icon="gtk-jump-to" type="object"/>
<button name="button_open" string="Open" states="draft" type="object"/>
<button name="button_validate" string="Validate" states="done" icon="gtk-jump-to" type="object"/>
<field name="state" widget="statusbar" select="1" readonly="1" clickable="True"/>

in audit.py I have:
'state': fields.selection(
        [
            ('draft', 'Draft'),
            ('opened', 'Opened'),
            ('done', 'Closed'),
            ('validated','Validated')
        ],
        'State',
    ),
_defaults = {
    'state': 'draft'
}
def button_open(self, cr, uid, ids, context=None):
    self.message_post(cr, uid, ids, _("Audit created"), context=context)
    return self.write(cr, uid, ids, {'state': 'opened'})
def button_close(self, cr, uid, ids, context=None):
    """When Audit is closed, post a message to followers' chatter."""
    self.message_post(cr, uid, ids, _("Audit closed"), context=context)
    return self.write(cr, uid, ids, {'state': 'done'})
def button_validate(self, cr, uid, ids, context=None):
    """When Audit is validated, post a message to followers' chatter."""
    self.message_post(cr, uid, ids, _("Audit validated"), context=context)
    return self.write(cr, uid, ids, {'state': 'validated'})

I want the state stays as it is in the workflow but when I save a new record the state changes automatically to 'validated'.

A: Try this:
def create(self, cr, uid, ids, vals, context=None):
 # write your logic here

 return super(my_model_name, self).create(cr, uid, ids, {'state':'validated'}, context=context)


text:
Q: if and elseif condition in PHP If I select fruit and mix fruit it will show alert "You have selected Fruit's favour and Fruit's topping, are you sure?"
but my code it show "You have selected chocolate's favour and chocolate's topping, are you sure?"
It wont go to else.
if(isset($_POST['submit'])){

    if($favour=="Chocolate"and $topping=="Chocolate Chip"){
        ?>
        <script type="text/javascript">
            if(window.confirm("You have selected chocolate's favour and chocolate's topping, are you sure?")) { alert("You have apply successfully");window.location="index.php";
            } else {
                window.location="customization.php";
            }
        </script>
        <?php
    }

    elseif($favour=="Fruit"and $topping=="Mix Fruit"){
        ?>
        <script type="text/javascript">
            if(window.confirm("You have selected Fruit's favour and Fruit's topping, are you sure?")) { alert("You have apply successfully");window.location="index.php";
            } else {
                window.location="customization.php";
            }
        </script>
    <?php
    }
else{
    $cakesize=$_POST['cakesize'];

    $favour=$_POST['favour'];
    $topping=$_POST['topping'];
    $color=$_POST['color'];
    $cmessage=$_POST['cmessage'];
    $cumessage=$_POST['customize_message'];
    $date=date("Y-m-d");
    ?>
    <script type="text/javascript">
        alert("You have apply successfully");
        window.location = "index.php"
    </script>
    <?php

    mysql_query("INSERT INTO customization (cakesize,cfavour,topping, ccolor, cmessage,customizeMessage, C_date, Member_ID,status) VALUES ('$cakesize','$favour' ,'$topping', '$color' ,'$cmessage','$cumessage', '$date', '$uname','pending')");
}
}

A: When checking conditions, you need to use a equality operator: ==
$favour=$_POST['favour'];
$topping=$_POST['topping'];

if($favour=="Chocolate"and $topping=="Chocolate Chip"){
    ?>
    <script type="text/javascript">
        if(window.confirm("You have selected chocolate's favour and chocolate's topping, are you sure?")) { alert("You have apply successfully");window.location="index.php";
        } else {
            window.location="customization.php";
        }
    </script>
    <?php
}

You also need to make sure the variables you are checking are set to a value before you check them. I've edited the above code to reflect this.

A: You are writing = instead of ==.


text:
Q: Net user command incorrectly displays password expiration date; script that reads field and outputs if expired is incorrect. Possible workaround? Ok, so here is what I have so far:
@echo off

powershell "$uid=(Read-Host -Prompt 'Enter UserID');$u = (net user $uid /domain);$u;$lockout=($u | select-string -pattern 'Account active.*Locked');$expired=((get-date ([String]($u | select-string 'Password expires')).Substring(16).Trim()) -lt (get-date));if ($lockout) { Write-Host 'Account locked out' -Foreground 'Red' } else { Write-Host 'Account not locked out' -Foreground 'Green' } if ($expired) { Write-Host 'Password Expired' -Foreground 'Red' } else { Write-Host 'Password not expired' -foreground 'Green' }"

pause

A little background if you'd like it, otherwise skip down a little.
I'm a level 1 service desk analyst, my users will call in saying they think their password is expired or account is locked. I've been doing this a while so it isn't an issue for me to look up their account in active directory. I'm part of what is a dedicated team, meaning we serve only 1 client. We have what is called leverage teams that take calls when dedicated is busy. I'm making this to help the leverage guys have an easier time as they don't always have the AD resource loaded.
Skip to here if you don't care about back story:
The issue I'm running into, is our active directory incorrectly displays the password expiration date when performing "net user %username% /domain". It shows as 1 year from the password last set field when it should be 90 days from the last set date. Making the part of my batch file that outputs if it is expired always incorrect.
Can I grab the password last set field, add 90 days, and have it output the date the password expires? Or compare that date to the current date, and determine if it has passed already? Maybe subtract a year and add 90 days to the password expiration date field? This is all very foreign to me as I have pieced most of it together from google searches, this site, reddit, and some colleagues here at work. So I'm open to suggestions.
I great appreciate any assistance you can provide, and if this is the wrong location for this, my apologies.
Edit1: So I tried something and changed a line;
I changed:
$expired=((get-date ([String]($u | select-string 'Password expires')).Substring(16).Trim()) -lt (get-date))

to
$expired=((get-date ([String]($u | select-string 'Password last set')).Substring(16).Trim()) -lt (get-date).AddDays(30))

but now I get an error.
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "t            10/18/2018 8:13:05 AM" to type
"System.DateTime". Error: "The string was not recognized as a valid DateTime. There is an unknown word starting at
index 0."
At line:1 char:156
+ ... =((get-date ([String]($u | select-string 'Password last set')).Substr ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

This is what I ended up with and it works perfectly in the environment I need it.
@echo off
powershell "$uid=(Read-Host -Prompt 'Enter UserID');$u = (net user $uid /domain);$u;$lockout=($u | select-string -pattern 'Account active.*Locked');$expiredate=get-date ([String]($u | select-string 'Password expires')).Substring(16).Trim();$expired=$expiredate.AddDays(-275) -lt (get-date);if ($lockout) { Write-Host 'Account locked out' -Foreground 'Red' } else { Write-Host 'Account not locked out' -Foreground 'Green' } if ($expired) { Write-Host 'Password Expired' -Foreground 'Red' } else { Write-Host 'Password not expired' -foreground 'Green' }"
pause

A: Yup, You could try some LDAP search.
$Searcher=New-Object DirectoryServices.DirectorySearcher
$Searcher.Filter="(&(samaccountname=username))"
$Results=$Searcher.findone()
$Results.Properties

will give you a lot of information and password last set is one among them.
I would suggest you to give the support team a PowerShell script instead of a batch file.

A: If you want to get the password expiration for a user, you can convert the attribute msDS-UserPasswordExpiryTimeComputed to DateTime
Below I put together an example to go into more details. The variable names should be self-explanatory to what they are. If you run the example, you will notice that the attribute msDS-UserPasswordExpiryTimeComputed should give you the expired date needed. However, the other options (adding 90 days) are included in the example.
Example (updated):
    [string]$Identity = "User Account"
    $expiredDate = [DateTime]::FromFileTime($((Get-ADUser -Identity $Identity -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed'))
    $lastSetDate = [DateTime]::FromFileTime($((Get-ADUser -Identity $Identity -Properties 'pwdLastSet').'pwdLastSet'))
    Write-Host "Exipred Date: " $expiredDate
    Write-Host "Last Set Date: " $lastSetDate

    $lastDate_Plus90 = $lastSetDate.AddDays(90)

    Write-Host "Last Set + 90 days: " $lastDate_Plus90


text:
Q: Linker command failed with exit code 1; undefined symbols for architecture armv7s. This is a first time I've been trying to upload binary (new version of an iOS App, not a completely new app) to the iTunes store. When I attempt to create an archive, I receive three Apple Mach-o linker errors, which show up red in issue navigator.
This is what shows up:
ld: warning: ignoring file /Users/alinam/Library/Developer/Xcode/DerivedData/Latina_1-bklvousdwnrhhgenrxpftegwerkb/Build/Intermediates/ArchiveIntermediates/Latina 1/BuildProductsPath/Release-iphoneos/libCordova.a, file was built for archive which is not the architecture being linked (armv7s): /Users/alinam/Library/Developer/Xcode/DerivedData/Latina_1-bklvousdwnrhhgenrxpftegwerkb/Build/Intermediates/ArchiveIntermediates/Latina 1/BuildProductsPath/Release-iphoneos/libCordova.a
Undefined symbols for architecture armv7s:
"_OBJC_METACLASS_$_CDVViewController", referenced from:
  _OBJC_METACLASS_$_MainViewController in MainViewController.o
"_OBJC_CLASS_$_CDVViewController", referenced from:
  _OBJC_CLASS_$_MainViewController in MainViewController.o`

ld: symbol(s) not found for architecture armv7s
clang: error: linker command failed with exit code 1 (use -v to see invocation)`

In one of the existing discussions I read that it might have something to do with linking binary with libraries.
Well, under Build Phases -> Link Binary With Libraries the libCordova.a shows up red (missing?).
If so, how and where do I get it and what do I do with it then?
Update:
I resolved the issue of not being able to archive the app by removing armv7s and arm64 (and leaving only armv7) in the app's Build Settings -> Architectures -> Valid Architectures.
Now it looks like this.
I've left everything as it was under CordovaLib.xcodeproj -> Build Settings -> Architectures, which looks like this.
So I have a new question: can I really simply remove armv7s and arm64 from Valid Architectures without any consequences? Will the app run on all the devices it should? In all the related discussions I've read through I couldn't find a definite answer to this.