text:
Q: how to replace logo's(images) based on the background theme I have two different images(logo), one for dark theme(it has light colored logo) and one for light theme(it has dark colored logo).
User has freedom to choose either dark theme or light theme.
But i am facing difficulty while replacing logo's. Can anybody please help me out with this?
My two .png images are named as lightlogo.png and darklogo.png. When the page loads user gets to see dark themed UI.
Here is my code to display logo

    <image  src="../images/lightlogo.png" alt="image" id="imag"   class="hidden-xs " />

Here is my code for theming

    loop

    <input type="button" id="light" value="light-theme"/>

Here is my js where user can change the theme and i am trying to add image for light background(light theme)
$('#light').click(function() {
  if ($(this).val() == "light-theme") {
    $(this).val("dark-theme");
    changeCSS("styleLight.css", 0)
  }
  else {
    $(this).val("light-theme");
    changeCSS("styleDark.css", 0).attr("src" , "../images/darklogo.png");
  }
});

function changeCSS(cssFile, cssLinkIndex) {

  var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

  var newlink = document.createElement("link");
  newlink.setAttribute("rel", "stylesheet");
  newlink.setAttribute("type", "text/css");
  newlink.setAttribute("href", "/stylesheets/"+cssFile);

  document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}

A: Try this, I have removed changing image src inside javascript function.
$('#light').click(function() {
  if ($(this).val() == "light-theme") {
    $(this).val("dark-theme");
    changeCSS("styleLight.css", 0)
    $('#imag').attr('src', "../images/darklogo.png");
  } else {
    $(this).val("light-theme");
    changeCSS("styleDark.css", 0)
    //.attr("src" , "../images/darklogo.png");
    $('#imag').attr('src', "../images/lightlogo.png");
  }
});

function changeCSS(cssFile, cssLinkIndex) {

   var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

   var newlink = document.createElement("link");
   newlink.setAttribute("rel", "stylesheet");
   newlink.setAttribute("type", "text/css");
   newlink.setAttribute("href", "/stylesheets/"+cssFile);

}

Problem is you cannot use attr() for javascript function.

A: You can do it like this, just have a wrapper class for the theme and then change the logo src attribute when changing theme.

$('#changeTheme').click(function() {
 var themeWrapper = $('#themeWrapper');
  var themeLogo = $('#themeLogo');

  if (themeWrapper.attr('class') === 'light-theme') {
    themeWrapper.attr('class', 'dark-theme');
    themeLogo.attr('src', '../images/darklogo.png');
  }
  else {
    themeWrapper.attr('class', 'light-theme');
    themeLogo.attr('src', '../images/lightlogo.png');
  }
});
#themeWrapper {
  padding: 20px;
}
.light-theme {
  background-color: #999;
  color: black;
}
.dark-theme {
  background-color: #333;
  color: white;
}

      <image  src="../images/lightlogo.png" alt="Theme logo" id="themeLogo" class="hidden-xs" />

Random text...

  <button type="button" id="changeTheme">Change theme</button>

Note: The logo has no working src in this example, but the src attribute changes.

A: Make a simple function that just changes the src of the icon, and that's it.
And call it from the same button that changes the theme.

function change(){
    if($("#imag").attr('src') != "http://www.thetechnologygeeks.com/images/icons/icon_mad.png"){
      $("#imag").attr("src","http://www.thetechnologygeeks.com/images/icons/icon_mad.png");
    } else {
      $("#imag").attr("src","https://filmscoremonthly.com/board/pics/icon6.gif");
    }
}

<image  src="https://filmscoremonthly.com/board/pics/icon6.gif" alt="image" id="imag"   class="hidden-xs " />

<button type="button" onclick="change()">Click Me!</button>


text:
Q: selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 298,437 I am doing web scraping using selenium in python using the following code:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_all_search_details(URL):
    SEARCH_RESULTS = {}

    options = Options()
    options.headless = True
    options.add_argument("--remote-debugging-port=9222")

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

    driver.get(URL)
    print(f"Scraping {driver.current_url}")
    try:
        medias = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'result-row')))
    except:
        print(f">> Selenium Exception: {URL}")
        return

    for media_idx, media_elem in enumerate(medias):
        outer_html = media_elem.get_attribute('outerHTML')

        result = scrap_newspaper(outer_html) # some function to extract results
        SEARCH_RESULTS[f"result_{media_idx}"] = result
    return SEARCH_RESULTS

if __name__ == '__main__':
    in_url = "https://digi.kansalliskirjasto.fi/search?query=%22heimo%20kosonen%22&orderBy=RELEVANCE"
    my_res = get_all_search_details(in_url)

I applied try except to ensure I would not get trapped in selenium timeout exception , however, here is the error I obtained:
Scraping https://digi.kansalliskirjasto.fi/search?query=%22heimo%20kosonen%22&orderBy=RELEVANCE
>> Selenium Exception: https://digi.kansalliskirjasto.fi/search?query=%22heimo%20kosonen%22&orderBy=RELEVANCE
Traceback (most recent call last):
  File "nationalbiblioteket_logs.py", line 274, in <module>
    run()
  File "nationalbiblioteket_logs.py", line 262, in run
    all_queries(file_=get_query_log(QUERY=args.query),
  File "nationalbiblioteket_logs.py", line 218, in all_queries
    df = pd.DataFrame( df.apply( check_urls, axis=1, ) )
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/frame.py", line 8740, in apply
    return op.apply()
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/apply.py", line 688, in apply
    return self.apply_standard()
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/apply.py", line 812, in apply_standard
    results, res_index = self.apply_series_generator()
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/pandas/core/apply.py", line 828, in apply_series_generator
    results[i] = self.f(v)
  File "nationalbiblioteket_logs.py", line 217, in <lambda>
    check_urls = lambda INPUT_DF: analyze_(INPUT_DF)
  File "nationalbiblioteket_logs.py", line 200, in analyze_
    df["search_results"] = get_all_search_details(in_url)
  File "/home/xenial/WS_Farid/DARIAH-FI/url_scraping.py", line 27, in get_all_search_details
    driver.get(URL)
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 441, in get
    self.execute(Command.GET, {'url': url})
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "/home/xenial/anaconda3/envs/py37/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 298,437
  (Session info: headless chrome=109.0.5414.74)
Stacktrace:
#0 0x561d3b04c303 <unknown>
#1 0x561d3ae20d37 <unknown>
#2 0x561d3ae0b549 <unknown>
#3 0x561d3ae0b285 <unknown>
#4 0x561d3ae09c77 <unknown>
#5 0x561d3ae0a408 <unknown>
#6 0x561d3ae1767f <unknown>
#7 0x561d3ae182d2 <unknown>
#8 0x561d3ae28fd0 <unknown>
#9 0x561d3ae2d34b <unknown>
#10 0x561d3ae0a9c5 <unknown>
#11 0x561d3ae28d7f <unknown>
#12 0x561d3ae95aa0 <unknown>
#13 0x561d3ae7d753 <unknown>
#14 0x561d3ae50a14 <unknown>
#15 0x561d3ae51b7e <unknown>
#16 0x561d3b09b32e <unknown>
#17 0x561d3b09ec0e <unknown>
#18 0x561d3b081610 <unknown>
#19 0x561d3b09fc23 <unknown>
#20 0x561d3b073545 <unknown>
#21 0x561d3b0c06a8 <unknown>
#22 0x561d3b0c0836 <unknown>
#23 0x561d3b0dbd13 <unknown>
#24 0x7f80a698a6ba start_thread

Is there a better alternative to get rid of such selenium timeout exception? To be more specific, I added:
options.add_argument("--disable-extensions")
options.add_argument("--no-sandbox")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

But they were not helpful to tackle selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 298,437!
Here are some more details regarding libraries I use:
>>> selenium.__version__
'4.5.0'
>>> webdriver_manager.__version__
'3.8.4'

A: I think the problem in this url
https://digi.kansalliskirjasto.fi/search?query=%22heimo%20kosonen%22&orderBy=RELEVANCE it is not fetching the expected data and showing no records.
Try with this url
https://digi.kansalliskirjasto.fi/search?query=heimo%20kosonen&orderBy=RELEVANCE

in_url = "https://digi.kansalliskirjasto.fi/search?query=heimo%20kosonen&orderBy=RELEVANCE"

A: Here is how I fixed the problem:
I added more exception blocks and rearranged and moved for loop inside the try block to ensure it would not get stuck in TimeoutException or StaleElementReferenceException as mentioned in here:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common import exceptions

def get_all_search_details(URL):
    SEARCH_RESULTS = {}

    options = Options()
    options.headless = True

    options.add_argument("--remote-debugging-port=9222") #
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-gpu")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--disable-extensions")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

    driver.get(URL)
    print(f"Scraping {driver.current_url}")
    try:
        medias = WebDriverWait(driver,timeout=5,).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'result-row')))
        for media_idx, media_elem in enumerate(medias):
            outer_html = media_elem.get_attribute('outerHTML')
            result = scrap_newspaper(outer_html) # some external functions
            SEARCH_RESULTS[f"result_{media_idx}"] = result

    except exceptions.StaleElementReferenceException as e:
        print(f">> {type(e).__name__}: {e.args}")
        return
    except exceptions.NoSuchElementException as e:
        print(f">> {type(e).__name__}: {e.args}")
        return
    except exceptions.TimeoutException as e:
        print(f">> {type(e).__name__}: {e.args}")
        return
    except exceptions.WebDriverException as e:
        print(f">> {type(e).__name__}: {e.args}")
        return
    except exceptions.SessionNotCreatedException as e:
        print(f">> {type(e).__name__}: {e.args}")
        return
    except Exception as e:
        print(f">> {type(e).__name__} line {e.__traceback__.tb_lineno} of {__file__}: {e.args}")
        return
    except:
        print(f">> General Exception: {URL}")
        return

    return SEARCH_RESULTS

redpajama_set_name: RedPajamaStackExchange


text:
Q: Route 53 Subdomains and API Gateway I have a domain hosted through Route 53 called foo.com and all is good.  I have both NS and SOA records created in Route 53:
foo.com. NS
ns-1609.awsdns-09.co.uk.
ns-431.awsdns-53.com.
ns-1071.awsdns-05.org.
ns-662.awsdns-18.net.

foo.com. SOA
ns-1609.awsdns-09.co.uk. awsdns-hostmaster.amazon.com.

We also segment our platforms by account.  So, we have an AWS subaccount that supports our DEV environment (following the AWS document: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-routing-traffic-for-subdomains.html).  So, within our foo.com hosted zone, we also have an entry:
devapi.foo.com. NS
ns-3476.awsdns-09.co.uk.
ns-2341.awsdns-76.com.
ns-3245.awsdns-56.org.
ns-294.awsdns-67.net.

Within our AWS DEV account, we have a devapi.foo.com hosted zone with the exact same NS record:
devapi.foo.com. NS
ns-3476.awsdns-09.co.uk.
ns-2341.awsdns-76.com.
ns-3245.awsdns-56.org.
ns-294.awsdns-67.net.

along with a SOA record and an A record that points at the DEV API Gateway:
devapi.foo.com. A  ALIAS f-8wdjr4hvgh.execute-api.us-east-2.amazonaws.com.

where f-8wdjr4hvgh.execute-api.us-east-2.amazonaws.com. is the domain name of the API Gateway.
I have a custom domain mapping for devapi.foo.com
Unfortunately, in all of this, devapi.foo.com is not pingable/routable.  If you ping it, it returns an IP address but a Request timeout for icmp_seq* ...
If I use https://www.whatsmydns.net/#A/ for devapi.foo.com, I get green check marks but I believe that all that is telling me is that the domain name is resolvable.
Thoughts on what I am missing?
Followup: The issue was with the Custom Domain Mapping and Base Path.

A: I ran into a problem where I went to setup a record that mapped my custom sub-domain to my API Gateway. When I went to select the actual endpoint I got a red warning/error message saying "cannot retrieve endpoint suggestions"
The instructions for setting everything up are here:
https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html
Before doing what I was trying to do, the prerequisites (stated on the linked page) were:

*

*An API Gateway API that has a custom domain name, such as api.example.com, that matches the name of the Route 53 record that you want to create.

*A registered domain name. You can use Amazon Route 53 as your domain registrar, or you can use a different registrar.

*Route 53 as the DNS service for the domain. If you register your domain name by using Route 53, we automatically configure Route 53 as the DNS service for the domain.

I realized I had not done step #1. This needs to be done via the API Gateway interface, not the Route 53 interface. If you haven't done this for the domain yet (not the sub-domain, but the domain) you may need to do some work to setup a certificate for the domain. This involves placing what looks to be a sort of magic key entry in your domain registry (using Route 53 or whatever you used to register your domain) so that Amazon knows you own the domain.
Once this custom domain has been setup (again, in the API Gateway section, not Route 53), then I was able to create a record in Route 53 and my API Gateway endpoint was now detected for selection.


text:
Q: FINDSTR and REGEX returns more numbers than I need I need FINDSTR to return only a number that I specify, say 2, and not 20, 21, 22, 200, 201, 202 etc.. but my code cycles through any numbers that start with the number I specify. If I specify 13, it will grab 13 AND 130 - 139.
Why does the regex expression FINDSTR /b /r /c:"13[^0-9]" elabs.txt return 13 AND 130 - 139?
My code:
@echo off
setlocal enabledelayedexpansion enableextensions

set "_RunlistName=ELabs.tab"
set /p "Begin=Begin is:"
set /p "End=end is:"

:forloop
REM Find event time and convert to seconds, then output start time and time between two runs into new config file.
For /F "tokens=1,2,3,4 delims=-:." %%a in ('Findstr /B /R /C:"%Begin%[^0-9]" !_RunlistName!') do (
    set /A "hr1=1%%b-100, min1=1%%c-100, sec1=1%%d-100"
    set /A "BS=(hr1 * 3600) + (min1 * 60) + sec1"
    )
For /F "tokens=1,2,3,4 delims=-:." %%a in ('Findstr /B /R /C:"%End%[^0-9]" !_RunlistName!') do (
    set /A "hr2=1%%b-100, min2=1%%c-100, sec2=1%%d-100"
    set /A "ES=(hr2 * 3600) + (min2 * 60) + sec2"
    )

REM For testing...
set /A "delta=ES-BS"
Echo delta = !ES! - !BS! = !delta!
echo.
echo begin=!begin!, !hr1!:!min1!:!sec1!
Echo end=!end!, !hr2!:!min2!:!sec2!
pause

endlocal
exit /B

Example text from source file:
1   000-00:01:13.221408 6.687540    DATA    RUN_BIT
2   000-00:01:28.533108 6.057900    Zbin    RUN_BIT
3   000-00:01:41.879568 7.632000    Rbin    RUN_BIT
4   000-00:01:55.521768 7.078680    Xbin    RUN_BIT
5   000-00:02:09.841308 7.269480    DATA    RUN_BIT
6   000-01:02:15.702138 39.419280   DATA    RUN_BIT
7   000-01:04:10.840398 70.643700   DATA    RUN_BIT
8   000-01:05:21.741678 16.952262   DATA    RUN_BIT
9   000-01:06:08.897580 228.587940  DATA    RUN_BIT
10  000-01:12:14.890140 17.191080   DATA    RUN_BIT
11  000-01:13:38.126640 59.157540   DATA    RUN_BIT
12  000-01:14:37.551300 47.337480   DATA    RUN_BIT
13  000-01:15:25.155900 66.579024   DATA    RUN_BIT
14  000-01:16:32.002044 58.326924   DATA    RUN_BIT
15  000-01:17:30.596088 42.328980   DATA    RUN_BIT
16  000-01:18:13.182648 13.794840   DATA    RUN_BIT
17  000-01:18:27.235068 16.990740   DATA    RUN_BIT
18  000-01:18:44.483388 27.179460   DATA    RUN_BIT
19  000-01:19:11.929968 34.143660   DATA    RUN_BIT
20  000-01:23:00.689628 206.025840  DATA    RUN_BIT
21  000-01:26:26.973048 28.791084   DATA    RUN_BIT
22  000-01:26:56.021712 58.479564   DATA    RUN_BIT
23  000-01:27:54.758856 13.556340   DATA    RUN_BIT

A: Following this set of rules your problem is that the delayed expansion phase is consumming the ^ character in the command being executed by the for /f. Double the ^ (one caret will be consummed to escape the other) or remove the delayed variable expansion phase from the command.
Use (keep delayed expansion, double caret)
For /F "tokens=1,2,3,4 delims=-:." %%a in ('
    Findstr /B /R /C:"%Begin%[^^0-9]" !_RunlistName!
') do (

Or (keep caret, remove delayed expansion)
For /F "tokens=1,2,3,4 delims=-:." %%a in ('
    Findstr /B /R /C:"%Begin%[^0-9]" %_RunlistName%
') do (

A: The command
%SystemRoot%\System32\findstr.exe /B /R /C:"13[^0-9]" ELabs.tab

works and outputs just the line beginning with 13 and ignoring the lines beginning with 130 to 139, 1300 to 1399, ...
This command is used within a FOR loop as command to execute of which output to STDOUT should be captured and processed by FOR which results in implicitly running this command line in another command process in background.
But before the command line
Findstr /B /R /C:"%Begin%[^0-9]" !_RunlistName!

is executed with %SystemRoot%\System32\cmd.exe /c in a background command process, it is twice parsed by the command process executing the batch file.
On first parsing done already before executing entire FOR command block, the environment variable reference %Begin% is replaced by the entered number like 13. The caret character ^ is kept on this parsing step. So before running FOR, the command line to later execute becomes for example
Findstr /B /R /C:"13[0-9]" !_RunlistName!

But because of !_RunlistName! referencing environment variable _RunlistName with delayed expansion, this command line is parsed once again immediately before executing the command line in another command process. And on this second parsing step ^ is interpreted as escape character and therefore removed. For that reason the background command process is started with the command line
C:\Windows\System32\cmd.exe /c Findstr /B /R /C:"13[0-9]" ELabs.tab

The lines found by FINDSTR are now not correct anymore because ^ which should mean NOT in the character class definition was before interpreted as escape character and therefore removed which changes the meaning of the regular expression.
One solution is using within FOR command line:
Findstr /B /R /C:"%Begin%[^0-9]" %_RunlistName%

By using %_RunlistName% there is no second parsing step by command process executing the batch file and therefore the caret character is kept on running this command line later for example with
C:\Windows\System32\cmd.exe /c Findstr /B /R /C:"13[0-9]" ELabs.tab

A second solution is escaping the caret with one more caret, i.e. using
Findstr /B /R /C:"%Begin%[^^0-9]" !_RunlistName!

This results also in executing FINDSTR for example with /C:"13[^0-9]".
These two solutions were offered also by MC ND.
Another solution is using within FOR command line:
Findstr /B /R /C:"%Begin%\>" %_RunlistName%

\> means end of a word as explained in help output by running findstr /? from within a command prompt window. As the searched number must be found at beginning of a line, usage of \> results in finding only the two lines starting with exactly the two entered numbers.

How to find out what is going on here on batch file execution?
There is the great, free Windows Sysinternals tool Process Monitor.
After downloading the ZIP file and extracting the files to any local directory like "%ProgramFiles%\Sysinternals" with administrator privileges or "%USERPROFILE%\Desktop\Sysinternals" with current user permissions, the executable file Procmon.exe must be executed with Run as administrator.
On first start of this free tool offered by Microsoft it is necessary to accept the license agreement.
Then the Process Monitor Filter dialog is opened and it is advisable for the investigation of this batch file execution to add two filters:

*

*Process Name is cmd.exe then Include and clicking on button Add.

*Process Name is findstr.exe then Include and clicking on button Add.

Next a look on the last 5 symbols on right side of the toolbar should be made which indicate and on click toggle the state of the general display filters. The filing cabinet symbol with tooltip Show File System Activity should be enabled as the only one because getting displayed only file system activities is all needed for investigation of this batch process.
Press Ctrl+X or click on fifth symbol from left side of the toolbar to clear already made record and execute the batch file from within a command prompt window (preferred on debugging a batch file) or with a double click on the batch file.
After batch file execution finished and input focus is back on Process Monitor, press Ctrl+E or click on third symbol from left side of the toolbar to stop capturing which takes some seconds.
Now look on the record. The batch file is executed with process cmd.exe with a specific PID (process identifier).
On scrolling down it can be seen that there is suddenly one more process cmd.exe with a different PID. This is the background command process executed to run the FINDSTR command line.
The command line used to start this second cmd.exe process can be seen after a secondary (right) mouse button click on the line with second cmd.exe to open the context menu, a primary (left) mouse button click on first context menu item Properties and a primary (left) mouse button click on tab Process.
On using Findstr /B /R /C:"%Begin%[^0-9]" !_RunlistName! in batch file and entering 13 for Begin the command line is:
C:\Windows\system32\cmd.exe /c Findstr /B /R /C:"13[0-9]" ELabs.tab

And this makes it clear that the caret character was removed from the command line already before execution of this background command process for executing FINDSTR.
For that reason it is no surprise that the command line of process findstr.exe is in this case:
Findstr /B /R /C:"13[0-9]" ELabs.tab

With modifying the batch file as suggested and running it each time after clearing Process Monitor log with Ctrl+X and enabling capturing again with Ctrl+E, it can be seen how the background command process for execution of the command line specified in FOR command line is really executed resulting in finally executing FINDSTR with the right parameters.
Free Process Monitor is really a great tool to find out the reason for an unexpected behavior of an application or script.

A: I'm struggling to understand the need for findstr anyhow.
For /F "UseBackQ Tokens=1,3,4,5 Delims=-:. " %%a In ("%_RunlistName%") Do If "%%a"=="%Begin%" (...

And
For /F "UseBackQ Tokens=1,3,4,5 Delims=-:. " %%a In ("%_RunlistName%") Do If "%%a"=="%End%" (...


text:
Q: SQL statement takes huge amount of time, is it possible optimize it? This is my SQL query with which I get all the duplicates, but one(the newest one):
SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM duplicates as d
WHERE d.C_DateCreated !=(select max(d2.C_DateCreated)
FROM duplicates d2
WHERE d2.C_DataSourceId = d.C_DataSourceId)

Is it possible to optimize it somehow? Unfortunately in 300 000 records it takes +- 40minutes.
Method where the query is:
public ArrayList<Record> get() throws SQLException,
        ClassNotFoundException {
    Statement st = DBConnect.DBC.con.createStatement();
    String sql = ("select d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID,
d.C_DateCreated "
            + "from duplicates as d "
            + "where d.C_DateCreated !=(select max(d2.C_DateCreated) "
            + "from duplicates d2 where d2.C_DataSourceId = d.C_DataSourceId)");
    ResultSet rs = st.executeQuery(sql);
    DBConnect.DBC.con.commit();
    while (rs.next()) {

        int contactID = rs.getInt("C_ContactID");
        String email = rs.getString("C_EmailAddress");
        String dataSourceID = rs.getString("C_DataSourceID");
        String dateCreated = rs.getString("C_DateCreated");
        duplicate = new Record(contactID, email, dataSourceID, dateCreated);
        duplicates.add(duplicate);
    }
    rs.close();
    st.close();

    return duplicates;
}

A: You would start by creating an index on duplicates(C_DataSourceId, C_DateCreated):
create index duplicates_DataSourceId_DateCreated on duplicates(C_DataSourceId, C_DateCreated);

If you are using a database that supports window functions, then I would rephrase this as:
SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM (select d.*, max(C_DateCreated) over (partition by C_DataSourceId) as maxdc
      from duplicates d
     ) d
WHERE d.C_DateCreated <> maxdc;

It is worth doing the comparison, because sometimes window functions have efficient implementations.
And, if you have the index, a slightly more efficient version of your query is:
SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM duplicates d
WHERE EXISTS (select 1
              from duplicates 2
              where d2.C_DataSourceId = d.C_DataSourceId and
                    d2.C_DateCreated > d.C_DateCreated
             );

This says to get all rows from duplicates where there is another row (with the same source) that has a bigger date created.  The slight advantage is that this doesn't have to look at all the values to get the max().  It only has to find the first one.  The major performance improvement will be the composite index.

A: Create index for the columns C_DateCreated and C_DataSourceId. This will reduce the time to execute the query. Refer this link to know how to create indices.
 http://www.tutorialspoint.com/mysql/mysql-indexes.htm

A: In T-SQL the answer would look like this, but I don't think SQLite supports window functions (leaving the answer intact for posterity though):
You can use a window function to label each row with it's position in the group of common C_DataSourceIDs, then with a CTE select the rows that aren't in position 1 like this.
with ordered as (
    select
        d.C_ContactID,
        d.C_EmailAddress,
        d.C_DataSourceID,
        d.C_DateCreated,
        row_number() over (
            partition by
                d.C_DataSourceID
            order by
                d.C_DateCreated
        ) as rownum
    from
        duplicates
) select
    C_ContactID,
    C_EmailAddress,
    C_DataSourceID,
    C_DateCreated
from
    ordered
where
    rownum != 1;

With an index on (C_DataSourceID, C_DateCreated) this will only need a single pass over the table instead of a self join that you have in your query.


text:
Q: Are there docblox in R? When writing PHP in Netbeans, as long as I provide my functions and classes with "docblox", Netbeans will show what parameters a function expects, what it will return, and a short description whenever I go to call it somewhere else. There is also the benefit of using it for automatically generated API documentation with a tool such as PHPDocumentor2. Is there any kind of equivalent in R? Currently I'm developing in RStudio.
Example of a docblox in PHP:
/**
 * This is the description of some function
 *
 * @param string $foo A foo string
 * @return string Foo string in all caps
 */
 function cap_foo($foo) { return strtoupper($foo); }

A: Is docblox the commented part? If so, check roxygen2


text:
Q: Boolean comparaison between a series and a dataframe (element-wise) Here the series and dataframe to be compared element-wise (AND condition):
import pandas as pd

se = pd.Series(data=[False, True])

df = pd.DataFrame(data=[[True, False], [True, True]],
                  columns=['A','B'])

Desired result:
df2 = pd.DataFrame(data=[[False, False], [True, True]],
                  columns=['A','B'])

I could achieve that using a slow for loop but I am sure there is a way to vectorise that.
Many thanks !

A: Convert Series to numpy array and compare with broadcasting:
print (df & se.to_numpy()[:,None])
       A      B
0  False  False
1   True   True

A: You can use conversion to numpy array to benefit from broadcasting:
out = np.logical_and(df, se.to_numpy()[:,None])

output:
       A      B
0  False  False
1   True   True

intermediate:
se.to_numpy()[:,None]

array([[False],
       [ True]])

A: Another possible solution:
(df & np.vstack(se))

Output:
       A      B
0  False  False
1   True   True

A: df.mul(se,0)

Output:
       A      B
0  False  False
1   True   Tru


text:
Q: git pull results in conflict I did git pull origin newbranch:newbranch ... but for some reason.. this tried merging newbranch in my origin with master in local.. and it resulted in conflict ..  1)how do i undo the half done merge?  2)how do i pull newbranch in origin to a new branch in local repo named "newbranch"

A: Use this to reset back to your pre-merge state:
git reset --merge

(Or if you're using a version of git before --merge was available, use --hard.)
Then create and checkout your branch, and pull, merging into it:
git checkout -b newbranch
git pull origin newbranch

Of course, you'll get the exact same conflicts as before, because you're merging into the same commit...


text:
Q: Custom hibernate criteria (one-to-many relationship) I need to create custom Hibernate query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> criteria = builder.createQuery(User.class);
    Root<User> user = criteria.from(User.class);
    List<Predicate> restrictions = new ArrayList<>();
    restrictions.add(builder.equal(user.get("firstname"), user.getFirstName()));
    List<User> users = (List<User>) entityManager.createQuery(criteria).getResultList();

I need to add to restrictions additional criteria. I have additional model Photo, which connected to model User with foreign key user_id.
I need to find users, which has any photos.
User model contains:
 private List<Photo> photos;

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "photo", cascade = CascadeType.ALL)
 @Fetch (FetchMode.SELECT)
 @JsonIgnore
 public List<Photo> getPhotos() {
     return photos;
 }

Photo model contains:
private User user;

@ManyToOne
@JoinColumn(name="user_id")
public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

UPDATED
I need something like this:
restrictions.add(builder.isNotNull(user.get("photos")));

but it's not working.
Problem is not with how to combine 2 restrictions, problem with how to add restriction isNotNull... User know nothing about photos. Photos know about user as they has user_id.
UPDATED2:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "."

SQL:
select * from User user0_ cross join Photo photos1_ where user0_.id=photos1_.user and (. is not null)

I need follow SQL:
 SELECT DISTINCT user.* FROM user
 LEFT JOIN photo
 ON user.id = photo.user_id;

A: Try this:
restrictions.add(Restrictions.and(Restrictions.eq(user.get("firstname"), user.getFirstName()),Restrictions.isNotNull(user.get("photos")));

UPDATE: The bidirectional relationship you are looking for is something like this:
Photo class:
@ManyToOne
@JoinColumn(name="user")
private User user;

User class:
@OneToMany(mappedBy="user")
private Set<Photo> photos;

In this one you have it mapped both ways so you can access photos from the user and user from photos.

A: I found solution myself. Full code:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> user = criteria.from(User.class);
Root<Photo> photo = criteria.from(Photo.class);
List<Predicate> restrictions = new ArrayList<>();
restrictions.add(builder.equal(user.get("firstname"), user.getFirstName()));
restrictions.add(builder.equal(user.get("id"), photo.get("user")));

List<User> users = (List<User>) entityManager.createQuery(criteria).getResultList();


text:
Q: Android socket io event and Channel How to add event and channel?
private void initSocketConnection() {
    try {
        mSocket = IO.socket("URL");
        connectSocket();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

private void connectSocket() {
    try {
        mSocket.connect();
        mSocket.on(Socket.EVENT_CONNECT, onConnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onError);
        mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Emitter.Listener onDisconnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("SOCKET_TEST", "DISCONNECTION SUCCESSFULL");
    }
};

/**
 * Receiver class for socket connected event
 */
private Emitter.Listener onConnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("SOCKET_TEST", "CONNECTION SUCCESSFULL");
    }
};

/**
 * Receiver for socket failed events
 */
private Emitter.Listener onError = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Log.e("SOCKET_TEST", "CONNECTION FAIL " + args.toString());
    }
};

I send a request, returns 32:44/socket.io,"Invalid namespace"
need to send event and channel
I use the library https://github.com/socketio/socket.io-client-java I do everything according to the documentation but nothing works.

A: Instead of creating a socket with just:
val socket = IO.socket("https://something.com/socket.io")

try the next code:
val opts = IO.Options()
opts.path = "/socket.io"

val socket = IO.socket("https://something.com", opts)

I had the same issue getting 4/socket.io, "Invalid namespace" trying to connect to the socket, and the code above fixed it.


text:
Q: The Matrix of an Equivalence Relation Perhaps I'm missing something from just the definition of an equivalence relation but wouldn't a matrix representing an equivalence relation on any set be only ones and anything less than that is just an equivalence class? If someone can clarify this for me that'd be great.

A: For $n\gt1$, there is more than one possible equivalence relation on a set with $n$ elements. Obviously they can't all be represented by the same matrix. In particular, the "minimal" equivalence relation on $S$ is $R=\{(x,x) \mid x\in S\}$. This relation is represented by the $n\times n$ identity matrix.
It's a worthwhile exercise to work out what properties the representative matrix must have. The reflexive and symmetric properties are pretty easy to translate into statements about the matrix, but transitivity might be a bit tricky.


text:
Q: How many integer solutions of "a" exist for this equation? $a\times b = 8 \times (a + b)$
I have used Wolfram Alpha and it has given me 14 integer solutions.
But how can we find those solutions ? Which method ?
edit: integer solutions are as following:
$a = [-56, -24, -8, 0, 4, 6, 7, 9, 10, 12, 16, 24, 40, 72]$
$ b = [7, 6, 4, 0, -8, -24, -56, 72, 40, 24, 16, 12, 10, 9]$

A: Hint:
$$ab-8(a+b)=0 \iff (a-8)(b-8)=64$$

A: So, $$a=\frac{8b}{b-8}=\frac{8(b-8)+64}{b-8}=8+\frac{64}{b-8}\iff (b-8)\mid64$$
Now, $64=2^6$ has $6+1=7$ positive divisors
So, we have $7$ solutions if we consider the only the positive values of $b-8$.
So, if we include all the non-zero integers, we shall have $2\cdot7=14$ divisors.
Clearly, $b-8\ne0$ else $a$ will be infinite.
So, the values of $b-8$ are $\pm 2^i$ for integer $i\ge0$ and $\le6$
Hence,
if $i=0,b-8=\pm1,b=9,7;$
if $i=1,b-8=\pm2,b=10,6;$
if $i=2,b-8=\pm4,b=12,4;$
if $i=3,b-8=\pm8,b=16,0;$
if $i=4,b-8=\pm16,b=24,-20;$
if $i=5,b-8=\pm32,b=40,-24;$
if $i=6,b-8=\pm64,b=72,-56;$


text:
Q: Parallel or Event driven functions in Python? I'm fairly new to Python, so maybe my whole concept of how this should Work is wrong:
I'm building a RFID Reader for time managing purposes. E.g. User logs in with RFID chip -> Timer Starts counting and updating a Google  spreadsheet every Minute. The updating part works fine, but takes a little while. But I want to Check for RFID Logins all the time. Somewhere  I read that Event driven Programming is what I'm looking for.
Currently I'm doing everything in a while true loop, which feels like a hack itself. Can i somehow just execute my code when the RFID reader sends a signal? And then time my update to run every minute or so parallel? I'd like to know whats best practice here.

A: Parallel and Event Driven are basically orthogonal, although it is generally "easy" to parallelize events. I'll first cover the event driven and then the parallelisation, although you may only want to use the later.
The "normal" controlflow in python is iterative.
That means you define the instructions the code should do and then the pc executes these step for step.
There are different ways to organize your code (functional, event driven, object oriented, although I don't want to say that these are absolute categories where you can only do X or Y). Event driven normally means you define events and how to handle them.
There is nothing you could program with event driven which you couldn't program iterativly and vice versa.
Python mainly got support for asyncronuos stuff with version 3.4 when the asyncio library was introduced.
With 3.5 you also got syntactic sugar await and async. Because you are on 2.7 this is not available for you.
There is a backport from asyncio named trollius but this is overkill if you only have a "low amount of events". Also it's not hard to "roll your own basic event loop" (of course asyncio and trollius do much more, but if we are not going to use these features, why bother?).
The basic workflow is waiting for events and then handling them as they occur:
events = []

while waiting_for_events:
    if events:
        event = events.pop()
        handle_event(event)

You somehow need to know how to differentiate between events and how to handle them.
For a "full featured event loop" you would probably use different classes with inheritance, but lets just use a name for each event.
Also we probably need some kind of data like which RFID we encountered.
from collections import namedtuple
Event = namedtuple("Event", ["name", "data"])

Then we simply need to map events to how to handle them:
def handle_rfid(data):
    ...

def handle_timer(data):
    ...

event_handler_mapping = {"rfid": handle_rfid, "timer": handle_timer}

def handle_event(event):
    event_handler_mapping[event.name](event.data)

We still need to generate events, so lets rewrite the eventloop to get events:
timer = 0
current_time = time.perf_counter()

while waiting_for_events:

    rfid = get_rfids()
    if rfid:
        events.append(Event("rfid", rfid))

    if timer > 1:
        events.append(Event("timer", timer))
        timer = 0
    else:
        timer += time.perf_counter() - current_time
        current_time = time.perf_counter()

    if events:
        event = events.pop()
        handle_event(event)

And now we are "event driven". The nice thing is that we can easily extend this to more events.
The bad thing is that it still does the same thing you probably already have, but it's more complicated.
Also if the event handling needs a lot of time (which seems to be the case with updating the spreadsheet) the other events will not
be generated and handled. This is were parallelism comes into play.
Parallelism basically means we can use multiple cores.
Here we actually only need "concurrency" which means two things can happen at once.
This is "easier" than true parallelism, we can just switch between different things but still do all the things sequentially.
In python this basically boils down to multiprocessing (parallelism) and threads ("only" concurrency) (in other programming languages threads actually do parallelism, but in python this is for reasons I don't want to go into not the case).
The problem with concurrency is always syncronisation. If things can happen at the same time, bad things can happen
if two threads try to change the same variable. In general as long as you only use thread-safe functions to access variables shared between threads, you are safe.
In python threads are created by the threading module.
I personally find it hard to understand if you don't already know threads from somewhere else, but the gist is the following:
To run a function in a thread use threading.Thread(target=function) and then thread.start().
You could use it the following:
def run_in_thread(f, *args, **kwargs):
    thread = Thread(target=f, args=args, kwargs=kwargs)
    thread.start()

def _update_spreadsheet(data):
    # logic here

# when using the event driven approach from above
def handle_timer(data):
    run_in_thread(_update_spreadsheet(data))

Note that if you access variables from within _update_spreadsheet you need to be carefule to only use thread safe function.
It is "best" to use as little inter-thread communication as possible.
A queue is often a good choice.
You can use parallelism/concurrency without the event driven organisation.
Because we already divided the code into event handlers we can call long running event handlers in a seperate thread.
If we have lots of events and event handlers running everything in threads is a bad idea (because thread switching has an overhead).
Thus asyncio (and probably all other event loops) implement some kind of "wait until atleast one event can be handled".
This is most interesting for internet input and output, because these need "a long time".
Often something like select is used.
Other events (timers, read from disk, wait for some hardware events, ...) need other mechanisms for "wake me up when something happens". Integrating all of these is one of the features asyncio offer for you.


text:
Q: Passing Parameters using jetty contextHandler I'm wanting to make some custom endpoints that point to another endpoint in my jetty setup. For example, I already have and endpoint like http://myserver.com/app that serves up a help page. Further, if I pass certain arguments, I get different pages. So for example http://myserver.com/app?app_id=56 might serve one app and http://myserver.com/app?app_id=48 might serve a static html page that documents functions.
For the sake of some of the users, I'd like to set up simple endpoints for a few of the commonly used apps. So if a user went to http://myserver.com/docs, they'd should see the same thing as http://myserver.com/app?app_id=48.
I've been trying to accomplish this with .xml Configuration files. So far I've got it almost working.
<?xml version="1.0"  encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.eclipse.org/configure.dtd">

<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
  <Set name="contextPath">/docs</Set>
  <Set name="resourceBase">http://localhost:8080</Set>
  <Set name="handler">
    <New class="org.eclipse.jetty.server.handler.ResourceHandler">
      <Set name="welcomeFiles">
        <Array type="String">
          <Item>app</Item>
        </Array>
      </Set>
      <Set name="cacheControl">max-age=3600,public</Set>
    </New>
  </Set>
</Configure>

Using this config file going to /docs serves the aforementioned help page which I would normally see by loading http://myserver.com/app, my hangup is I can't figure out how to pass the appropriate app_id.
I think I may end up creating some sort of custom handler but I'm not exactly sure how to go about implementing it.
And just to complicate the issue, I also want to be able to pass some arbitrary parameter to my endpoint and have it passed along. So http://myserver.com/docs?foo=bar would display http://myserver.com/app?app_id=48&foo=bar.
Should I be going about this another way or can this all be accomplished through the config xml files?

A: If using Jetty 9.2+ you can just use the built-in static resource serving (magic provided by the deploy module)
Eg:
$ cd /path/to/my.base
$ ls -l webapps
total 4
lrwxrwxrwx. 1 joakim joakim 84 Oct 27 17:24 docs -> /opt/my/docs
$ java -jar /path/to/jetty-dist/start.jar

But if you really want to handle static resources with an XML ...

*

*Don't use ContextHandler and ResourceHandler they are only for the most simplistic and naive of file serving scenarios.

*Use an anonymous WebAppContext

*Set resourceBase to the directory where your documents are

Here's how you setup a static file serving XML (done right)
$ cd /path/to/my.base
$ cat webapps/docs.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/docs</Set>
  <Set name="resourceBase">/opt/my/docs</Set>
  <Set name="defaultsDescriptor"><Property name="jetty.base" default="."/>/etc/docs-web.xml</Set>
</Configure>

$ cat etc/docs-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
   metadata-complete="false"
   version="3.1">

  <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
    <init-param>
      <param-name>aliases</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>acceptRanges</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>dirAllowed</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>welcomeServlets</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>redirectWelcome</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>maxCacheSize</param-name>
      <param-value>256000000</param-value>
    </init-param>
    <init-param>
      <param-name>maxCachedFileSize</param-name>
      <param-value>200000000</param-value>
    </init-param>
    <init-param>
      <param-name>maxCachedFiles</param-name>
      <param-value>2048</param-value>
    </init-param>
    <init-param>
      <param-name>gzip</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>etags</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>useFileMappedBuffer</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>cacheControl</param-name>
      <param-value>max-age=3600,public</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
</web-app>
$ java -jar /path/to/jetty-dist/start.jar


text:
Q: in powershell, [Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [Text.RegularExpressions.RegexOptions]::Multiline Trying to take a vhdl or ada source file, match the keywords, and replace them with keywords in the list.  However, my regex isn't work with ignorecase and multiline, subsituting of $1 and $2.
Here's my code below.  Any ideas?  Thanks.
$ErrorActionPreference = 'Stop'

$script:regop_gi = [Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [Text.RegularExpressions.RegexOptions]::Multiline

function ReplaceKeyWords {
    param(
        [string]$text,
        [string[]]$keywords
    ) #returns string

    for ($k = 0; $k -lt $keywords.Length; $k++) {
        $r0 = "([^a-zA-Z0-9_@]|^)" + $keywords[$k] + "([^a-zA-Z0-9_]|$)"
        $r1 = [regex]::new($r0, $script:regop_gi)
        $text = $text.replace($r1, "$1" + $keywords[$k] + "$2")
    }

    return $text
}

$vhdl = @()
$vhdl += "library ieee;"
$vhdl += "use ieee.std_logic_1164.all;"
$vhdl += "   use std.textio.all;"
$vhdl += ""
$vhdl += ""
$vhdl += "entity mydesign is"
$vhdl += "    port("
$vhdl += "      clk:in std_logic;"
$vhdl += "  rst:in std_logic;"
$vhdl += "         xyz  : in    std_logic_vector(7 downo 0);"
$vhdl += "   abc:out std_logic_vector(7 downto 0)"
$vhdl += "    )"
$vhdl += "end entity"
$vhdl += ""
$vhdl += "architecture beh of mydesign is"
$vhdl += "begin"
$vhdl += "    process(clk,           rst)"
$vhdl += "  begin"
$vhdl += "        if (rst) then"
$vhdl += "           abc        <=             (others=>'0');"
$vhdl += " else (rising_edge(clk)) then"
$vhdl += "    abc        <=             xyz;"
$vhdl += "       end if;"
$vhdl += "                  end process;"
$vhdl += "end architecture;"
$vhdl += ""

$vhdl_lines = $vhdl -join "`n"

$KeyWords = @(
    "BEGIN"
    "END"
    "ENTITY"
    "ARCHITECTURE"
)

$newtext = ReplaceKeyWords -text $vhdl_lines -keywords $Keywords

write-host $newtext

A: The following statement is wrong on multiple levels:

$text = $text.replace($r1, "$1" + $keywords[$k] + "$2")

*

*Given that $text is of type [string], .replace() refers to the System.String.Replace() method, which operates on verbatim strings, not on regexes.

*Using an expandable (interpolating) strings such as "$1" and "$2" causes $1 and $2 to be interpreted a PowerShell variable references.

You were probably looking for the following, using the regex-based -replace operator:
$text = $text -replace ('\b{0}\b' -f $keywords[$k]), $keywords[$k]

PowerShell's regex operations are case-insensitive by default, and, given that your replacements do not straddle lines, neither the IgnoreCase nor the MultiLine regex options are needed.

Also, in PowerShell (Core) 7+, you can simplify your code as follows, taking advantage of being able to pass a script block as the replacement operand:
# Use a here-string to define your string.
$vhdl_lines = @'
library ieee;
use ieee.std_logic_1164.all;
   use std.textio.all;

entity mydesign is
    port(
      clk:in std_logic;
  rst:in std_logic;
         xyz  : in    std_logic_vector(7 downo 0);
   abc:out std_logic_vector(7 downto 0)
    )
end entity

architecture beh of mydesign is
begin
    process(clk,           rst)
  begin
        if (rst) then
           abc        <=             (others=>'0');
 else (rising_edge(clk)) then
    abc        <=             xyz;
       end if;
                  end process;
end architecture;
'@

# The array of keywords to upper-case.
$keyWords = @(
    "BEGIN"
    "END"
    "ENTITY"
    "ARCHITECTURE"
)

# Replace the keywords with their uppercase versions.
$vhdl_lines -replace ('\b(?:{0})\b' -f ($keyWords -join '|')),
                     { $_.Value.ToUpper() }


text:
Q: Road Name windows form application I will sound like absolutely a noob, but I am so stressed out that I am not able to do any research properly.
Basically I got 127 road names in a list, and I want to display them one by one in a random sequence in a label and I will answer them if its right one increment to green box if its wrong then increment to yellow box but at same time it will display me right answer in a label and then on pressing submit button it will take me to next road name, here is what I have done until now,
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RL = RoadLocationNames();
        i = 1;
        red = 1;
        y = 1;
    }

    List<KeyValuePair<string, string>> RL;
    int i,red, y;

    private void button1_Click(object sender, EventArgs e)
    {
        Random random = new Random();
        int r = random.Next(RL.Count);

        lbLocation.Text = RL.ElementAt(r).Key;

        if (tbRoad.Text.ToLower() == RL.ElementAt(r).Value.ToLower())
        {
            Green.Text = i.ToString();
            i++;
            RL.Remove(RL.ElementAt(r));
        }
        else
        {
            label3.Text = RL.ElementAt(r).Value.ToString();
            Red.Text = i.ToString();
            i++;
        }

        Yellow.Text = y.ToString();
        y++;

    }

    public List<KeyValuePair<string, string>> RoadLocationNames()
    {
        List<KeyValuePair<string, string>> RLNs = new List<KeyValuePair<string,string>>();
        RLNs.Add(new KeyValuePair<string, string>("Road Name", "Location Name"));

        return RLNs;
    }

Now My internet is so slow that I barely can upload any screenshot of my form but I will try to.. I got exam tomorrow and I want to do preparation using this app, but I am not sure about,

*

*How to display a road name instead of (road name and its answer which is what my code is doing now) it could be because I am doing everything in buttton submit, I need help with logic and code (sorry but am in rush)

A: Yes, it's because you're doing everything in your submit. I suggest you split your code into the following:

*

*Initialisation - create the list of road names and locations, then run setup (next step).

*Setup - Clear the user's current answer, pick a road name/location pair randomly and display the question part on the form.

*User submission - check answer, increment appropriate counter, if the answer is right run setup again, otherwise display what the answer should have been.

Initialisation can be done in your form constructor. Setup should be a private method. User submission should be your click handler.
(It looks like you're incrementing i for both right and wrong answers which is probably incorrect. This is why you pick better variable names than a single letter to make mistakes like that more obvious.)


text:
Q: Remove specific words or letters from a String May i ask, how do i remove words and letters from a string?
Example: is, are
Example: -ing.
A sentence:  A wolf is eating a sheep.
becomes: A wolf eat a sheep.
Thanks!

A: Use replace method
String str = "A wolf is eating a sheep.";

str = str.replace("ing","");

or
str = str.replace("eating","eat");


text:
Q: What is Conexant D400 External USB 56K Modem .Do I need it to create dial up connection in ubuntu14.04 I want to know what is Conexant D400 External USB 56K Modem and why it is "external usb"

A: This is an old type of modems kept for legacy support. It's practically no longer used. It allows to make a dial-up connection with a speed of no more than 56Kbps which means 7KB/s. It's also used as a fax interface for the computer which means you may plug in the phone cable and send/receive fax documents.
why it is "external usb"?
Well, some devices have "PCI" parent address which means like if that device is connected to the PCI slot. The same way, some device have "USB" parent address which means like if they have a USB plug connected to a USB port BUT internally.

A: Its a legacy modem - in Win10 its recognised a USB-Com-Port i.e. Com3. If you like to send a fax you use the windows-fax-printer. It tells you there should be a modem for sending the fax, you tell him it is on Com3 and the modem-type is a legacy 56k Faxmodem. Connected to the telephone-line it will send your fax without any problems.


text:
Q: Using icons with django-select2 I would like to set an icon in front of the selectable items in a multiple choice field I'm rendering with django-select2.
Per the documentation, it looks like I'll need to use templateResult, but not sure how in my case.
My HTML (simplified below) is rendered with django-crispy-forms and django-select2 as follows:
<form class="form-horizontal" method="post" >
    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" type="text/css" media="screen" rel="stylesheet" />

    Recipient(s)*
    <select multiple="multiple" class="select2multiplewidget form-control django-select2" data-allow-clear="false" data-minimum-input-length="0" data-placeholder="Select one or more recipients" id="id_recipients" name="recipients">
        <optgroup label="Groups">
            <option value="group_6">Group 6</option>
            <option value="group_2">Group 2</option>
            <option value="group_8">Group 8</option>
        </optgroup>
    </select>
</form>

I thought  I'd be able to use JS like on the Example page, with the below, but the function is never called.
$(".select2multiplewidget").select2({
    templateResult: formatState
});


text:
Q: Cannot Center Text in CSS block using Text-Align I am trying to center the words on my page. Everything is working except the text is on the left side of the screen, not the center.
styling{
     color: white;
     background-color: aqua;
     font-family: 'Hachi Maru Pop', cursive;
     font-size: 18px;
     font-weight: bold;
     margin: o auto;
     text-align: center;
  }

A: Probably your text element is not 100% wide. It is centering the text inside of itself already.

.text {
  background-color: limegreen;
  border: 1px solid green;
  text-align: center;
}

.text--100 {
  display: block;
}
This is not 100%. It's an inline element.

This is 100%. Block element fills parent width.

Paragraphs are block elements.


text:
Q: В отдельном классе записать ресурсы в массив строк Есть отдельно вынесенный класс по работе с базой данных:
public class DB
{
private final Context mCtx;
private DBHelper mDBHelper;
private SQLiteDatabase mDB;

public DB(Context ctx)
{
    mCtx = ctx;
}

Во вложенном классе по созданию и управлению БД
private class DBHelper extends SQLiteOpenHelper {

присутствует метод
public void onCreate(SQLiteDatabase db)
    {

в котором создаются таблицы и вносятся первоначальные данные из объявленных и заполненных здесь же массивов. С целью возможности перевода я вынес строковые названия в файл ресурсов strings.xml
// значения первоначальных данных в БД
<string name="task_1">Сон</string>
<string name="task_2">Еда</string>

Теперь архангелы Андроида не дают мне получить доступ к ресурсам:
 String Arr_NAME[] = {getResources().getString(R.string.task_1), "Еда", "Прогулка", "Дорога"};

При попытке заменить первый пункт ссылкой на ресурсы - гетРесурсы - выделено красным и не могут они, дескать, реализовать этот метод. Так же не работает и просто getString(R.string.task_1) и R.string.task_1. Естественно, в обычном public class MainActivity extends AppCompatActivity таких сложностей не возникает, и строковое значение можно получить String X = getString(R.string.task_1).
Как же правильно по святым письменам взять ресурсы и поместить в массив в отдельно стоящем классе?

A: Методы getResourses() и getString() относятся к классу Context.
Так что вам надо получить ссылку на контекст (например передав её через конструктор вашего класса) и на нём эти методы вызывать.
В вашем конкретном случае Context содержится в переменной вашего класса с именем  mCtx. Значит надо писать так:
mCtx.getResources(); и mCtx.getString(R.string.SOME_STRING);

A: И правильно.
если вы хотите обратиться к ресурсам из любого места в приложении, Создайте класс по примеру
public class App extends Application {

    private static App mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static App getInstance() {
        return mInstance;
    }
}

и добавьте в манифест
 <application
        android:name=".App"
          ...
        <activity
         ........

после чего можно обратиться к ресурсам так App.getInstance().getResources().getString(R.string.task_1)
Либо передавайте Context в конструкторе.


text:
Q: Enhance code to run on all sheets in a workbook How can I change this code so it runs on all sheets of a workbook? It works well, just need it to run on all sheets. =)
Option Explicit
Option Compare Text

Sub HideColumns()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Data")
Dim MyCell As Range
Dim HideMe As Range

Application.ScreenUpdating = False
    For Each MyCell In ws.Range("A2:EA2")
        If MyCell <> "First Name" And MyCell <> "Age" And MyCell <> "Gender" Then
            If HideMe Is Nothing Then
                Set HideMe = MyCell
            Else
                Set HideMe = Union(HideMe, MyCell)
            End If
        End If
    Next MyCell

    If Not HideMe Is Nothing Then
        HideMe.EntireColumn.Hidden = True
    End If
Application.ScreenUpdating = True

End Sub

A: Loop through sheets using For Each loop & reset HideMe to Nothing before moving to next sheet.
Option Explicit
Option Compare Text

Sub HideColumns()

Dim ws As Worksheet 'Change made here
Dim MyCell As Range
Dim HideMe As Range

Application.ScreenUpdating = False
For Each ws in Worksheets 'and here
    For Each MyCell In ws.Range("A2:EA2")
        If MyCell <> "First Name" And MyCell <> "Age" And MyCell <> "Gender" Then
            If HideMe Is Nothing Then
                Set HideMe = MyCell
            Else
                Set HideMe = Union(HideMe, MyCell)
            End If
        End If
    Next MyCell

    If Not HideMe Is Nothing Then
        HideMe.EntireColumn.Hidden = True
    End If

Set HideMe = Nothing 'and here
Next ws 'and here

Application.ScreenUpdating = True

End Sub


text:
Q: In how many ways can a 3-officer slate can be chosen? The 4-member group has to elect officers. In how many ways can they choose a slate of 3 officers?
I tried to answer it. I used permutation without repetition and I got 24 ways. Is this correct? the word slate makes me doubt my answer. I'm wondering if that means I need to use combination formula.

A: The word slate makes me believe that the positions for the officers are not different. Hence, I would use the combination formula and say the answer is 4 choose 3. That would be 4!/3! and give you an answer of 4 different ways.
You can also think of this question less combinatoricsy. Lets say there are 4 people: A,B,C,D. Then the group of officers you can have is ABC, ABD, ACD, or BCD. Since it does not matter the order in which you choose the officers, ABC=BAC, and there are only 4 possibilities.

A: If the positions are different (e.g. you have a president, a secretary, and a treasurer), then there are $4 \cdot 3 \cdot 2=24$ possible slates
If the positions are all the same, then there are just $4$ possible slates, since there are $4$ persons and $1$ person won't get on the slate.


text:
Q: How do I disable csrf protection for springfox Swagger UI without Spring Security or Spring Boot? We have a REST API using Spring MVC that doesn't use Spring Security or Spring Boot. The rest API url is {domain}/product/rest/v1/{controller}. We also have a regular web GUI using Struts2 that is just at {domain}/product/{action}.
We're currently researching autogenerating API documentation using Springfox-swagger and springfox-swagger-ui. It was fairly easy to get Swagger to work using minimal configuration, but the problem is that Springfox by default tries to do a CRSF token request, which we don't use in the rest API. I've googled how to disable this, but every article I can find talks about how to disable it using the Spring Security WebSecurityConfigurationManager. We don't use Spring Security and would rather not have to add it.
Is there a way to disable the Springfox Swaggger UI CSRF token check without using Spring Security or Spring Boot?

A: For disable the csrf () you need to add spring security in your project follows these link how to disable csrf() in spring.
https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html


text:
Q: Have we that $\ell\ell({_{A}N})=\ell\ell(_{B}{N}) \;?$ Let $A$ and $B$ be two artin algebras.
Let $_{A}M_{B}$ be a bimodule.
 We denote ${\rm rad}({_{A}M})$ by the radical of $M$ as left $A$-module,
 We denote ${\rm rad}({M}_{B})$ by the radical of $M$ as rigtht $B$-module,
 We denote ${\rm rad}({_{A}M}_{B})$ by the radical of $M$ as bimodule.
We denote $\ell\ell(_{A}M)$ by the Loewy length of a left module $_{A}M$,
$\ell\ell(M_{B})$ by the Loewy length of a right module $M_{B}$, and
$\ell\ell(_{A}M_{B})$ by the Loewy length of a bimodule module $_{A}M_{B}$.
Problem:
$(1)$ Have we that ${\rm rad}({_{A}M})={\rm rad}({M}_{B})={\rm rad}
({_{A}M}_{B})$ as abelian groups?
$(2)$ $\ell\ell({_{A}M})=\ell\ell({M}_{B})=\ell\ell
({_{A}M}_{B})$ ?
$(3)$ If $f:A \longrightarrow B$ is a homomorphism of algebras $A$ and $B$, for a left $B$-module $_{B}N$, it also has a left $A$-module structure, that is, for $a\in A , x\in N$, we define $a.x=f(a)x$.
$$\ell\ell({_{A}N})=\ell\ell(_{B}{N}) \;?$$

A: The answer is no, in all 3 cases. For example take $A=k[x]/(x^2)$ and $B=k$ and $M=A$.
Then $\operatorname{rad}(_A M)=(x)$ and $\operatorname{rad}(_B M)=0$. Thus, the Loewy length is 2 in the first case and 1 in the second. The same example works for the embedding $B\to A$ in (3).


text:
Q: advice to find interface down I'm working to build a Python script. my target is first show the description of interface, then check if the interface has ( up  up ) or (up  down ) no action need else if the interface is ( down down) then print the interface name .. So Plz any advice .. Thanks in advance
my output before apply the script
Switch# show int description | section ABC
Hu1/0/14                       up             up       ABC
Hu1/0/30                       up             down     ABC
Hu1/0/31                       down           down     ABC

The OutPut after apply the script should be
Hu1/0/31

A: There are multiple ways to talk to a network device like telnet, ssh, netconf etc and module available for each of those methods.

*

*telnet - telnetlib

*ssh - paramiko, netmiko
Sample code which should do what you need
import re
from netmiko import ConnectHandler

username = "test"
password = "test"
enablePwd = "test"

verification_cmd = 'show int description | section ABC'

net_connect = ConnectHandler(device_type="cisco_ios",ip=host,username=userName,password=passWord,secret=enablePwd)
net_connect.enable()
sh_command_output = net_connect.send_command(verification_cmd)

for line in sh_command_output.split('\n'):
    if re.findall(r'down.*down', line):
        print(line.split(' ')[0])


text:
Q: MS Word Insert > Pictures (from Ribbon) Stopped Working In MS Word (2016) I am trying to insert an image (usually a trivial thing) using the insert tab on the ribbon.  I click the Pictures button expecting a browse dialogue to appear but nothing happens.
On a side note, the VBA application.Dialogs(wdDialogInsertPicture).Show also fails to produce the insert picture dialogue.
Thoughts?

A:
EITHER of these settings prevent users from adding images


text:
Q: Rails sorting gem I'd like to create a gem that modifies ActiveRecord::Base select methods. For instance, when I include my gem and type:
Somemodel.all

it should return an array ordered by id as normally but in descending order instead of ascending. I have no clue how it should look. I would not like to create additional methods like:
Somemodel.where(name: "John").revert_it

but simply do:
Somemodel.where(name: "John")

I was wondering about modifying ActiveRecord::Base methods, but it does not make any sense. IMO the best way is to callback after every ActiveRecord::Base method that will do it.

A: You can use the ActiveRecord method default_scope to achieve this:
class MyModel < ActiveRecord::Base

  default_scope { order("id DESC") }

end

MyModel.all
# => SELECT * FROM my_models ORDER BY id DESC

A: It's not advisable to modify any core ActiveRecord methods (unless you have a really good reason), because that will make lot of confusion in future.
Even if you are thinking of modifying the select , you have make sure that you always return an ActiveRecord relation , so that it can be chained with as the standard way,
For your example, AR already has a method
User.all.reverse

A: I got fully valid answer:
  def self.included(base)
    base.class_eval do
     default_scope { order(id: 'desc') }
    end
  end

Above method should be inside some module and then module included within some model class


text:
Q: Java POJO xml annotation for attributes I am currently using a Spring Batch application to call an API and parse out the entire JSON response into an XML to be consumed by another application.  Currently we are using a rather large expand query with the API which sometimes times out on elements.  The required output format for the results is
<?xml version...?>
<RECORDS>
    <RECORD>
        <PROP NAME="json.path.to.element.name">
            <PVAL>The value for the element</PVAL>
        </PROP>
        <PROP NAME="json.path.to.element2.name">
            <PVAL>The value for the element2</PVAL>
        </PROP>
        ...
    </RECORD>
    <RECORD>
        ...
    </RECORD>
    ...
</RECORDS>

This was being created using a DOMSource and a Transformer. This unfortunately does not take advantage of the Spring Batch chunk processing. I am updating this to extend StaxEventItemWriter and passing a list of mapped objects.  My mapped entities are
@XmlElement
public class Record implements Serializable {

    private List<Prop> prop;
}

@XmlElement
public class Prop implements Serializable {

    @XmlAttribute
    private String name;

    @XmlValue
    private String pVal;
}

My Spring Batch XML config for my marshaller is
<bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="aliases">
        <map>
            <entry key="RECORD" value="com...Record"/>
            <entry key="PROP" value="com...Prop" />
        </map>
    </property>
</bean>

The problem I am getting is my output format is not working. I am getting
<?xml version...?>
<RECORDS>
    <RECORD>
        <prop>
            <PROP>
                <name>json.path.to.element1.name"</name>
                <pVal>The value for the element1</pVal>
            </PROP>
                <name>json.path.to.element2.name"</name>
                <pVal>The value for the element2</pVal>
            </PROP>
            ...
        </prop>
    </RECORD>
    <RECORD>
        <prop>
            ...
        </prop>
    </RECORD>
    ...
</RECORDS>

The two things that need to happen is 1) the <prop> entity needs to be removed as directly under the Record are all the <PROP> entities. and 2) the <PROP> needs to be <PROP NAME...>
I have tried messing with the annotations but can't seem to change the output. I am not even sure what the XSD would be for the desired structure.

A: For the second part of your question, the correct annotation for the name field should be as below if you want it to be an attribute.
@XStreamAsAttribute
private String name;

Following the XStream annotation documents , the first part should be:
@XStreamImplicit(itemFieldName="PROP")
private List<Prop> prop;


text:
Q: What's magical about MTU and packet drops? With default MTU as shown below:
hosta$ ifconfig eth0 | grep mtu
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500

I can ping from a different server using a 1500 payload
hostb$ ping -s 1500 -c 2 hosta
PING hosta (hosta) 1500(1528) bytes of data.
1508 bytes from hosta: icmp_seq=1 ttl=64 time=0.273 ms
1508 bytes from hosta: icmp_seq=2 ttl=64 time=0.314 ms

--- hosta ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1025ms
rtt min/avg/max/mdev = 0.273/0.293/0.314/0.020 ms

tcpdump on hosta is all good
12:01:40.237047 IP hostb > hosta: ICMP echo request, id 3052, seq 1, length 1480
12:01:40.237048 IP hostb  > hosta: icmp
12:01:40.237116 IP hosta > hostb: ICMP echo reply, id 3052, seq 1, length 1480

I can lower the MTU on hosta up to 1488 and the 1500 payload ping works.
The magic number is MTU=1487
hosta $ ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1487
<snip>

When I send the 1500 byte ping (not messing with fragmentation flag) there is no response
hosb $ ping -s 1500 -c 2 hosta
PING hosta (hosta) 1500(1528) bytes of data.

--- hosta ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1032ms

tcpdump on hosta looks like this:
12:01:07.421196 IP hostb > hosta: icmp
12:01:08.443698 IP hostb > hosta: icmp

hosta shows
net.ipv4.ip_forward_use_pmtu = 0
net.ipv4.ip_no_pmtu_disc = 0
net.ipv4.route.min_pmtu = 552
net.ipv4.route.mtu_expires = 600
net.ipv4.tcp_mtu_probe_floor = 48
net.ipv4.tcp_mtu_probing = 0
net.ipv4.icmp_echo_ignore_all = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_errors_use_inbound_ifaddr = 0
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.icmp_msgs_burst = 50
net.ipv4.icmp_msgs_per_sec = 1000
net.ipv4.icmp_ratelimit = 1000
net.ipv4.icmp_ratemask = 6168

Note I replaced the ip address with the correct hostname if the output looks a bit wonky.
I'm beat trying to understand why lowering the MTU to any number below a certain threshold results in ping not getting any responses. Inspite of me not messing with the fragmentation bit.
If I use the -M option of do/want/dont for the 1500 byte packet I get a response till hosta MTU stays above 1488 but once it's set to 1487 or below, do/want/dont all get no response.
Following up a bit more on this..
With MTU=1487 tcpdump on that host(=10.50.107.129) shows this incoming 1 IP packet
1   2023-02-15 22:40:24.095129  10.50.107.83    10.50.107.129   IPv4    562 Fragmented IP protocol (proto=ICMP 1, off=1480, ID=1fb9)

That's the only line. Says it's fragmented but shows 562 bytes as the length which is the same length as the one shown below in #3 below.
Next I change MTU=1500 where I see the payload fragmented and acknowledged which is shown below.
2   2023-02-15 22:40:42.093639  10.50.107.83    10.50.107.129   IPv4    1514    Fragmented IP protocol (proto=ICMP 1, off=0, ID=2c62) [Reassembled in #3]
3   2023-02-15 22:40:42.093639  10.50.107.83    10.50.107.129   ICMP    562 Echo (ping) request  id=0x1004, seq=1/256, ttl=64 (reply in 5)
4   2023-02-15 22:40:42.093698  10.50.107.129   10.50.107.83    IPv4    1514    Fragmented IP protocol (proto=ICMP 1, off=0, ID=fe1a) [Reassembled in #5]
5   2023-02-15 22:40:42.093717  10.50.107.129   10.50.107.83    ICMP    562 Echo (ping) reply    id=0x1004, seq=1/256, ttl=64 (request in 3)

I checked the data in #1 and compared with the data in #4, they are not +/- 3 bytes (ping stuffs hex 00 to ff as the payload). So either the sender didn't send the first fragment or the receiver didn't read the first fragment or something else is going on.
Both servers are built identically as vm's running Ubuntu. So eliminated one side by .
If I run a ping from my laptop through the vpn/firewall/etc/etc, I can ping the host with MTU=1487.
Stumped and would appreciate if someone has any suggestions.


text:
Q: play 2 different package for views I am trying to move my views out of the default views package into mynewpackage.view.xyz. It was not a problem with the controllers.
It seems like they are not compiled at all.
Play 2.0 doc says:

... Note that in Play 2.0, the controllers, models and views package name conventions are now just that and can be changed if needed (such as prefixing everything with com.yourcompany). ...

What am I doing wrong?

A: *

*Create new package in /app let's call it com.mycompany.views

*Create new view in it: myView.scala.html

*Return it in action: return ok(com.mycompany.views.html.myView.render());
As can you see there's important html part between package name and view name, to get views compiled without reloading the page start Play with command: play ~run

A: 1) clone views to your new package.
2) clean and compile.
3) change import references


text:
Q: Как двигать спрайт в направление куда он смотрит? Есть такой код управления спрайтом:
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
    {
        player.move(0, -Speed * time);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
    {
        player.move(0, Speed * time);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        player.rotate(-Speed * time);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        player.rotate(Speed * time);
    }

Спрайт вращается вокруг своей оси, но кпонки w,s перемещают спрайт не так как надо. Как его перемещать в то направление куда он смотрит? Какие формулы применять? Чтоб было наподобие танков с видом сверху.

A: Вперед - вот так:
player.move(Speed * time * cos(угол), Speed * time * sin(угол));

Назад - аналогично, только с -Speed вместо Speed.
Здесь угол - это тот угол, который меняется вызовом player.rotate.

Использовать одну и ту же скорость Speed для поворота и движения - слегка странно. Может иметь смысл использовать две отдельные константы.


text:
Q: Creating Drupal 7 Field Groups Programmatically I am trying to automatically group fields created by my custom module, but it's not quite working.  My expectation is that a field group will be created and existing fields would be assigned to it.  I'm using the Field Groups module, as it appears to be pretty standard.
As advised on http://drupal.org/node/1606758, I have used ctools bulk export to generate the code.  I have moved the following code into my module.  Not sure why this isn't working:

*

*My hook_field_group_info() and hook_ctools_plugin_api() are both being hit; the debugging flags I've added are being logged.

*The specified fields are named correctly and do exist in the database.

What I might be doing wrong?
========== From Ctools Bulk Exporter: ===========
Place this in nmc_directory.info
name = nmc_directory export module
description = Export objects from CTools
dependencies[] = field_group
package = Chaos tool suite
core = 7.x

Place this in nmc_directory.module
<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function nmc_directory_ctools_plugin_api($module, $api) {
  if ($module == 'field_group' && $api == 'field_group') {
    return array('version' => 1);
  }
}

Place this in nmc_directory.field_group.inc
<?php

/**
 * Implements hook_field_group_info().
 */
function nmc_directory_field_group_info() {
  $field_groups = array();

  $field_group = new stdClass();
  $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
  $field_group->api_version = 1;
  $field_group->identifier = 'group_dir_phys_consumer_info|node|dir_physicians|form';
  $field_group->group_name = 'group_dir_phys_consumer_info';
  $field_group->entity_type = 'node';
  $field_group->bundle = 'dir_physicians';
  $field_group->mode = 'form';
  $field_group->parent_name = '';
  $field_group->data = array(
    'label' => 'Online Medical Providers Directory: Website (Consumer Information)',
    'weight' => '0',
    'children' => array(
      0 => 'dir_phys_gender',
      1 => 'dir_phys_category',
      2 => 'dir_phys_title',
      3 => 'dir_phys_fname',
      4 => 'dir_phys_lname',
      5 => 'dir_phys_suffix',
      6 => 'dir_phys_medfield_1',
      7 => 'dir_phys_medfield_2',
      8 => 'dir_phys_phone_public',
    ),
    'format_type' => 'fieldset',
    'format_settings' => array(
      'label' => 'Online Medical Providers Directory: Website (Consumer Information)',
      'instance_settings' => array(
        'required_fields' => 1,
        'classes' => '',
        'description' => '',
      ),
      'formatter' => 'collapsed',
    ),
  );
  $field_groups['group_dir_phys_consumer_info|node|dir_physicians|form'] = $field_group;

  return $field_groups;
}

A: For future reference - this code (and the approach) works perfectly.
My problem was that this module is getting so large (4 content types, 60+ fields, 6 vocabularies, etc) that it runs pretty slowly on my localhost.  When I ran it on my staging server, it worked very nicely.  I bumped up the max execution time on my localhost php.ini and its working fine locally now too.
FWIW: I was able to use /devel/reinstall (from the Devel module) to reinstall the module a little faster than going through the module admin page.  Not sure why this didn't timeout too, but it didn't.
Edit:
hmm.. so several days later, I'm not as certain that the problem was entirely due to the php execution time.  That played a part (some fields were never created + plus other problems), but now uninstalling & reinstalling my module produces scattered results with the field groups.

*

*some field groups do not appear at all (there is no record in the {field_group} table in the DB)

*however, the Bulk Exporter module does list my groups as being available for export

*field groups that are added don't necessarily apply the specified weights to their children

*field groups appear to be removed when uninstalling my module (which follows this methodology)


text:
Q: Angularjs - how to get ng-message required error to display and disable input button at the same time I want an error message to appear if the user clicks submit with no content, and I want the submit button to be disabled.
I can get either one working, but not both at the same time.
The code below brings up the message but allows an empty todo item.
<form name="todoForm" novalidate >

Add Your Item Below...

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" >Add To List</button>

</form>

This version disables the submit button but doesn't bring up the message
<form name="todoForm" novalidate >

Add Your Item Below...

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" data-ng-disabled="todoForm.$invalid" >Add To List</button>
</form>

I presume this is because the message can't be displayed when the input button is disabled because nothing has been submitted?
I've tried using $disabled and $invalid instead but they haven't worked.

A: I removed the conflicting ng-if on the ng-message element. Here is a working plunk showing the fixed code.
http://plnkr.co/edit/gL0GoFT47mSeydKReLuD
My assumption is that you forgot to inject the 'ngMessages' module as an external dependency.
You can fix your code like this:
var app = angular.module('plunker', ['ngMessages']);


text:
Q: Multiple UICollectionViewCells to segue to separate UIViewController I have two separate UICollectionViewCells with identifiers MY_CELL and MY_CELL_2
I then wrote this:
#import "MyCollectionView"
#import "Cell.h"
#import "VC1.h"
#import "VC2.h"

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {

            Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];

        Cell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL_2" forIndexPath:indexPath];

    }

I then have two UIVCs, UIVC1 and UIVC2 I want MY_CELL to segue to UIVC1 and MY_CELL_2 to segue to UIVC2 so I wrote:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ([[segue identifier] isEqualToString:@"cell_to_vc1"])
    {

    UICollectionViewCell *cell = (UICollectionViewCell *)sender;
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];

    UIVC1 *vc1 = (VC1 *)segue.destinationViewController;

    }

    if ([[segue identifier] isEqualToString:@"cell2_to_vc2"])
    {

      UICollectionViewCell *cell2 = (UICollectionViewCell *)sender;
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];

    UIVC2 *vc2 = (VC2 *)segue.destinationViewController;

    }

}

However, I can't even see the second cell being displayed. Only MY_CELL is visible.
Anyone know what I'm doing incorrectly and why I cannot see the second cell?

A: You must have a single identifier for cell. In didselect method, you have to check which cell is clicked and and inprpare segue just check the segue identifier you have mapped to and perform segue.