text:
Q: {{block type="core/template" column_count="4" category_id="50" template="catalog/product/list.phtml"}} is not working in magento2 I am new to magento2. I want to show a particular category products in my home page. I am using this code:
{{block type="core/template" column_count="4" category_id="50" template="catalog/product/list.phtml"}}

But it's not working.
Thanks in advance,
rani

A: You need to change your code like this :
{{block class="Magento\Catalog\Block\Product\ListProduct" category_id="50" name="home.products.list" template="Magento_Catalog::product/list.phtml"}}

A: If you want to display product of particular category. Just add line of code in pages.
 {{block class="Magento\Catalog\Block\Product\ListProduct"
 name="category.products.list" as="product_list" category_id="51"
 template="product/list.phtml"}}

A: If You want to add the products on home then follow the few steps.

*

*Edit your home page -> click on Insert Widget-> select catalog product list->
Select category in Conditions


text:
Q: Convert Counters to Hash Table with Linked List values I have 3 counters with total count for word frequency on different strings.
Counter({u'childhood': 3, u'waiting': 2}) #counter1
Counter({u'childhood': 5}) #counter2
Counter({u'waiting': 2}) #counter 3

Atm I am able to perform counter addition to get the total word count for all words in all counters.
Counter({u'childhood': 8, u'waiting': 4})

I however need to take each counter and insert them on a hash table with the word as key and a linked list as value where each linked entry has the count per string per Counter.
Example
[childhood] : [1,3] -> [2,5] #counter 1 - 3 times | counter 2 - 5 times
[waiting] : [1,3] -> [3,2]

How do I achieve this in Python? I was thinking of a dictionary with a deque inside? Or extend the counter addition function?
I'n trying to use existent python data structures without extending or creating custom data structure implementations.

A: Assuming you have some sequence counters
total = sum(counters, Counter())

table = {word: [counter[word] for counter in counters] for word in total}

will give you a dictionary like
{
 'childhood': [3, 5, 0],
 'waiting': [2, 0, 2]
}

A: You could use a defaultdict(list) to store each of the entries as a tuple:
from collections import Counter, defaultdict

counters = [
    Counter({u'childhood': 3, u'waiting': 2}), #counter1
    Counter({u'childhood': 5}),                #counter2
    Counter({u'waiting': 2})]                  #counter3

combined = defaultdict(list)

for number, counter in enumerate(counters, start=1):
    for word, count in counter.items():
        combined[word].append((number, count))

print(combined['childhood'])
print(combined['waiting'])

Which would give you:
[(1, 3), (2, 5)]
[(1, 2), (3, 2)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: It's impossible to operate with state after installed package react I have react application and for display photo slider i installed tiny-slider-react package,
i installed it and configured it works fine till i try to do something with state even when i try to do something like this:
const [count, setCount] = useState(0)
  useEffect(() => {
    setCount(23)
  },
[])

this error i get each time
i cannot void using state. Please how can i figure out what is happening and how can i solve it ?
UPD:
 <BackgroundLayer theme="lightPink2">
  <PageContent paddingTop marginTop>
    <Chapter title={title} description={description} className="logos" />

      <TinySlider settings={settings} onTouchMove={(event) => setIndex(event.index)}>
        {renderLogos(logos, "slider-padding", "slider__image")}
      </TinySlider>

        {aaaaaaa.map(a => (

        ))}

  </PageContent>
</BackgroundLayer>

UDP2 Settings:
const settings = {
  nav: false,
  mouseDrag: true,
  controls: false,
  loop: false,
  }

UPD3:That's how RenderLogos method looks like
  const renderLogos = (logos, firstClass, secondClass) => {
   return (
    <>
      {logos.map(s => (

          {s.map(({ logo: { title, file: { url } } }) => (
            <Logo
              url={url}
              title={title}
              key={guuid()}
              styleClass={secondClass}
            />
          ))}

      ))}
    </>
  )
}

A: The problem is you are rendering a React.Fragment (1 element) while the library assumes you will render multiple elements as children for TinySlider.
Try changing renderLogos to this:
const renderLogos = (logos, firstClass, secondClass) => {
  // render a list directly, not a list inside a fragment
  return logos.map((s) => (

      {s.map(({ logo: { title, file: { url } } }) => (
        <Logo url={url} title={title} key={guuid()} styleClass={secondClass} />
      ))}

  ));
};


text:
Q: How to get Celery to load the config from command line? I am attempting to use celery worker to load a config file at the command line:
celery worker --config=my_settings_module
This doesn't appear to work.  celery worker starts and uses its default settings (which include assuming that there is a RabbitMQ server available at localhost:5672) In my config, I would like to point celery to a different place.  When I change the amqp settings in the config file to something,  Celery didn't appear to care.  It still shows the default RabbitMQ settings.
I also tried something bogus
celery worker --config=this_file_does_not_exist
And Celery once again did not care.  The worker started and attached to the default RabbitMQ.  It's not even looking at the --config setting
I read about how Celery lazy loads.  I'm not sure that has anything to do with this.
How do I get celery worker to honor the --config setting?

A: If you give some invalid module name or a module name which is not in PYTHONPATH, say celery worker --config=invalid_foo, celery will ignore it.
You can verify this by creating a simple config file.
$ celery worker -h

--config=CONFIG       Name of the configuration module

As mentioned in celery worker help, you should pass configuration module. Otherwise it will raise an error.
If you just run
celery worker

it will start worker and its output will be colored.
In the same directory, create a file called c.py with this line.
CELERYD_LOG_COLOR = False

Now run
celery worker --config=c

it will start worker and its output will not be colored.
If you run celery worker --config=c.py, it will raise an error.
celery.utils.imports.NotAPackage: Error: Module 'c.py' doesn't exist, or it's not a valid Python module name.
Did you mean 'c'?

A: I had the exact same error, but I eventually figured out that I had made simple option naming mistakes in the configuration module itself which were not obvious at all.
You see, when you start out and follow the tutorial, you will end up with something that looks like this in your main module:
app = Celery('foo', broker='amqp://user:pass@example.com/vsrv', backend='rpc://')

Which works fine, but then later as you add more and more configuration options you decide to move the options to a separate file, at which point you go ahead and just copy+paste and split the options into lines until it looks like this:
Naïve my_settings.py:
broker='amqp://user:pass@example.com/vsrv'
backend='rpc://'
result_persistent=True
task_acks_late=True
# ... etc. etc.

And there you just fooled yourself! Because in a settings module the options are called broker_url and result_backend instead of just broker and backend as they would be called in the instantiation above.
Corrected my_settings.py:
broker_url='amqp://user:pass@example.com/vsrv'
result_backend='rpc://'
result_persistent=True
task_acks_late=True
# ... etc. etc.

And all of a sudden, your worker boots up just fine with all settings in place.
I hope this will cure a few headaches of fellow celery newbies like us.
Further note:
You can test that celery in fact does not ignore your file by placing a print-statement (or print function call if you're on Py3) into the settings module.


text:
Q: Ruby on Rails can't save image src scraped with Nokogiri I'm trying to get the src value of an image (which is located on another website) with Nokogiri, save it in my database and use it to display this image in my view. But Rails raiseS this error message:

Nil location provided. Can't build URI.

here is my code in controller:
def scrape

doc = Nokogiri::HTML(URI.open(page_url))
items = doc.css("j-wrapper-content")
images = doc.css("div.j-img")

images.each do |image|
  link = image.css("img").attr('src').to_s
  @product.image_url = "https://www.jacadi.fr#{link}"
end

items.each do |item|
  @product.name = item.css("h1").text
  @product.price = item.css("j-prd-price p").text.to_f
end

@product.save! end

and my code in view:
<% if product.picture.attached? %>
  <%= image_tag(product.picture, class: "card-pict") %>
<% elsif %>
  <%= image_tag(product.image_url, class: "card-pict") %>
<% else %>
  <%= image_tag("gift.png", class: "card-pict mini") %>
<% end %>

A: Finally found the solution ! There were two issues :

*

*In the controller : The . were missing in front of the css selector so Nokogiri was unable to find them.

*In the view I've added the .present? behind my product.image_url in my elsif statement.


text:
Q: loop through column and add other row EDIT: I've made some progress. So I read up on subsets, and was able to break down my dataframe under a certain condition. Let's say titleCSV[3] consists of file names ("file1", "file2", "file3", etc) and titleCSV[13] contains values (-18, -8, -2, etc). Code below:
titleRMS <- data.frame(titleCSV[3], titleCSV[13])

for(x.RMS in titleRMS[2]){
    x.RMS <- gsub("[A-Za-z]","",r)
    x.RMS <- gsub(" ","",r)
    x.RMS = abs(as.numeric(r))
}

x.titleRMSJudge <- data.frame(titleRMS[1], x.RMS)
x.titleRMSResult <- subset(x.titleRMSJudge, r < 12)

My question now is, what's the best way to print each row of the first column of x.titleRMSResult with a message saying that it's loud? Thanks, guys!
BTW, here is the dput of my titleRMS:
dput(titleRMS)
structure(list(FILE.NAME = c("00-Introduction.mp3", "01-Chapter_01.mp3",
"02-Chapter_02.mp3", "03-Chapter_03.mp3", "04-Chapter_04.mp3",
"05-Chapter_05.mp3", "06-Chapter_06.mp3", "07-Chapter_07.mp3",
"08-Chapter_08.mp3", "09-Chapter_09.mp3", "10-Chapter_10.mp3",
"11-Chapter_11.mp3", "12-Chapter_12.mp3", "Bonus_content.mp3",
"End.mp3"), AVG.RMS..dB. = c(-14, -10.74, -9.97, -10.53, -10.94,
-12.14, -11, -9.19, -10.42, -11.51, -14, -10.96, -11.71, -11,
-16)), .Names = c("FILE.NAME", "AVG.RMS..dB."), row.names = c(NA,
-15L), class = "data.frame")

ORIGINAL POST BELOW
Newb here! Coding in R. So I am trying to analyze a csv file. One column has 10 rows with different file names, while the other has 10 rows with different values. I want to run the 2nd column into a loop, and if it's greater/less than a certain value, I wanted it to print the associating file name as well as a message. I don't know how to have both columns run in a loop together so that the proper file name prints with the proper value/message. I wrote a loop that ends up checking each value for as many rows as there are in the other column. At the moment, all 10 rows meet the criteria for the message I want to print, so I've been getting 100 messages!
titleRMS <- data.frame(titleCSV[3], titleCSV[13])

for(title in titleRMS[1]){
    title <- gsub(" ","",title)
}

for(r in titleRMS[2]){
    r <- gsub("[A-Za-z]","",r)
    r <- gsub(" ","",r)
    r = abs(as.numeric(r))

    for(t in title){
        for(f in r){
            if (f < 18 & f > 0) {
                message(t, "is Loud!")
            }
        }
    }
}

And this line of code only prints the first file name for each message:
for(r in titleRMS[2]){
    r <- gsub("[A-Za-z]","",r)
    r <- gsub(" ","",r)
    r = abs(as.numeric(r))
    for(f in r){
        if (f < 18 & f > 0) {
            message(t, "is Loud!")
        }
    }
}

Can someone throw me some tips or even re-write what I wrote to show me how to get what I need? Thanks, guys!

A: You're making things hard on yourself. You don't need regex for this, and you probably don't need a loop, at least not through your data frame. Definitely you don't need nested loops.
I think this will do what you say you want...
indicesToMessage <- titleRms[, 2] > 0 & titleRms[, 2] < 18
myMessages <- paste(titleRms[indicesToMessage, 1], "is Loud!")

for (i in 1:length(myMessages)) {
  message(myMessages[i])
}

A more R-like way (read: without an explicit loop) to do the last line is like this:
invisible(lapply(myMessages, message))

The invisible is needed because message() doesn't return anything, just has the side-effect of printing to the console, but lapply expects a return and will print NULL if there is none. invisible just masks the NULL.
Edits: Negative data
Since your data is negative, I assume you actually want messages when the absolute value abs() is between 0 and 18. This works for that case.
indicesToMessage <- abs(titleRms[, 2]) > 0 & abs(titleRms[, 2]) < 18
myMessages <- paste(titleRms[indicesToMessage, 1], "is Loud!")
invisible(lapply(myMessages, message))

A: I've figured out my own issue. Here is what I wrote to come to the conclusion I wanted:
titleRMS <- data.frame(titleCSV[3], titleCSV[13])

filesHighRMS <- vector()
x.titleRMSJudge <- data.frame(titleCSV[3], titleCSV[13])
x.titleRMSResult <- subset(x.titleRMSJudge, titleCSV[13] > -12 & titleCSV[15] > -1)

    for(i in x.titleRMSResult[,1]){
    filesHighRMS <- append(filesHighRMS, i, 999)
    }

emailHighRMS <- paste(filesHighRMS, collapse=", ")
blurbHighRMS <- paste("" ,nrow(x.titleRMSResult), " file(s) (" ,emailHighRMS, ") have a high RMS and are too loud.")

Being new to code, I bet there is a simpler way, I'm just glad I was able to work this out on my own. :-)


text:
Q: Lenovo T540p, Nvidia GeForce GT 730M, 19.10 Eoan, 4K second monitor problem, 3840x2160 mode not autodetected I just want my 4K monitor to work as a 4K monitor when it is plugged in. Pixels help, FPS not so much.
Basically what the title says, the screen in my office gets plugged in with an HDMI to Mini Display Port cable. The monitor does show up in the video settings for position and resolution and the other settings. But, 3840x2160 is not an option for the resolution without sending an xrandr command or fiddling with a /etc/X11/xorg.conf file.
The monitor edid information does have a mode I find acceptable in the factory embedded list of modes. It is using HDMI 1.4 (and not 2.0).
Anyhoo, here is my workaround-- can you see a better way to handle it?
That is my question, is there a better built-in way to do this if the hardware isn't going to automatically configure all the things?
#!/usr/bin/env bash

apt update

apt -y upgrade

apt -y autoremove

#ubuntu-drivers devices

##  Output:
##  == /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
##  modalias : pci:v000010DEd00001290sv000017AAsd0000221Ebc03sc00i00
##  vendor   : NVIDIA Corporation
##  model    : GK208M [GeForce GT 730M]
##  driver   : nvidia-340 - distro non-free
##  driver   : nvidia-driver-390 - distro non-free recommended
##  driver   : xserver-xorg-video-nouveau - distro free builtin
##
##  == /sys/devices/pci0000:00/0000:00:1c.1/0000:04:00.0 ==
##  modalias : pci:v00008086d000008B2sv00008086sd0000C270bc02sc80i00
##  vendor   : Intel Corporation
##  model    : Wireless 7260 (Dual Band Wireless-AC 7260)
##  manual_install: True
##  driver   : backport-iwlwifi-dkms - distro free

ubuntu-drivers autoinstall

apt install -y get-edid

get-edid

##  Output:
##  This is read-edid version 3.0.2. Prepare for some fun.
##  Attempting to use i2c interface
##  No EDID on bus 1
##  No EDID on bus 2
##  No EDID on bus 3
##  No EDID on bus 4
##  No EDID on bus 6
##  No EDID on bus 8
##  No EDID on bus 9
##  3 potential busses found: 0 5 7
##  Will scan through until the first EDID is found.
##  Pass a bus number as an option to this program to go only for that one.
##  Bus 0 doesn't really have an EDID...
##  256-byte EDID successfully retrieved from i2c bus 5
##  ������N�▒�
##ץ�YJ�$PT�������@��t0�pZ��X�Ď!f!P�Q@p6?C!�LP
##        �W55
##           �5tS�_^] &     Pm
##                            < `�`a�rQ� n(UĎ!�▒q X,%Ď!��
##  Њ �->��!▒�
##  Looks like i2c was successful. Have a good day.
##  А @1
##       @U�!▒5

### <!> As it turns out, I wanted the info on bus 5.
### <!> Let's get the Modelines

get-edid -b5 | parse-edid

##  Output:
##  5
##  This is read-edid version 3.0.2. Prepare for some fun.
##  Attempting to use i2c interface
##  Only trying 5 as per your request.
##  256-byte EDID successfully retrieved from i2c bus 5
##  Looks like i2c was successful. Have a good day.
##  Checksum Correct
##
##  Section "Monitor"
##          Identifier "W55"
##          ModelName "W55"
##          VendorName "SPT"
##          # Monitor Manufactured week 24 of 2018
##          # EDID version 1.3
##          # Digital Display
##          # Display Physical Size not given. Normal for projectors.
##          Gamma 1.00
##          Option "DPMS" "false"
##          Horizsync 30-80
##          VertRefresh 30-76
##          # Maximum pixel clock is 300MHz
##          #Not giving standard mode: 1920x1080, 60Hz
##          #Not giving standard mode: 1680x1050, 60Hz
##          #Not giving standard mode: 1280x800, 60Hz
##          #Not giving standard mode: 1280x1024, 60Hz
##          #Not giving standard mode: 1280x960, 60Hz
##          #Not giving standard mode: 1280x720, 60Hz
##
##          #Extension block found. Parsing...
##  #WARNING: I may have missed a mode (CEA mode 95)
##  #WARNING: I may have missed a mode (CEA mode 94)
##  #WARNING: I may have missed a mode (CEA mode 93)
##          Modeline        "Mode 18" 74.25 1280 1390 1430 1650 720 725 730 750 +hsync +vsync
##          Modeline        "Mode 0" 297.00 3840 4016 4104 4400 2160 2168 2178 2250 +hsync +vsync
##          Modeline        "Mode 1" 85.50 1360 1424 1536 1792 768 771 777 795 +hsync +vsync
##          Modeline        "Mode 2" 148.500 1920 2008 2052 2200 1080 1084 1089 1125 +hsync +vsync
##          Modeline        "Mode 3" 74.250 1920 2008 2052 2200 1080 1082 1087 1125 +hsync +vsync interlace
##          Modeline        "Mode 4" 74.250 1280 1390 1420 1650 720 725 730 750 +hsync +vsync
##          Modeline        "Mode 5" 27.027 720 736 798 858 480 489 495 525 -hsync -vsync
##          Modeline        "Mode 6" 27.027 1440 1478 1602 1716 480 484 487 525 -hsync -vsync interlace
##          Modeline        "Mode 7" 27.027 720 736 798 858 480 489 495 525 -hsync -vsync
##          Modeline        "Mode 8" 27.027 1440 1478 1602 1716 480 484 487 525 -hsync -vsync interlace
##          Modeline        "Mode 9" 25.200 640 656 752 800 480 490 492 525 -hsync -vsync
##          Modeline        "Mode 10" 148.500 1920 2448 2492 2640 1080 1084 1089 1125 +hsync +vsync
##          Modeline        "Mode 11" 74.250 1920 2448 2492 2640 1080 1082 1089 1125 +hsync +vsync interlace
##          Modeline        "Mode 12" 74.250 1280 1720 1760 1980 720 725 730 750 +hsync +vsync
##          Modeline        "Mode 13" 27.000 720 732 796 864 576 581 586 625 -hsync -vsync
##          Modeline        "Mode 14" 27.000 1440 1464 1590 1728 576 578 581 625 -hsync -vsync interlace
##          Modeline        "Mode 15" 27.000 720 732 796 864 576 581 586 625 -hsync -vsync
##          Modeline        "Mode 16" 27.000 1440 1464 1590 1728 576 578 581 625 -hsync -vsync interlace
##          Modeline        "Mode 17" 74.250 1920 2558 2602 2750 1080 1084 1089 1125 +hsync +vsync
##          Modeline        "Mode 19" 74.25 1920 2008 2052 2200 540 542 547 562 +hsync +vsync interlace
##          Modeline        "Mode 20" 27.00 720 736 798 858 480 489 495 525 -hsync -vsync
##          Modeline        "Mode 21" 27.00 720 732 796 864 576 581 586 625 -hsync -vsync
##          Option "PreferredMode" "Mode 18"
##  EndSection

### <!> It did not work for me, but you can try generating Modelines with cvt

#cvt 3840 2160
##  Output:
##  # 3840x2160 59.98 Hz (CVT 8.29M9) hsync: 134.18 kHz; pclk: 712.75 MHz
##  Modeline "3840x2160_60.00"  712.75  3840 4160 4576 5312  2160 2163 2168 2237 -hsync +vsync

### <!> 60Hz is the default for cvt refresh rate parameter-- my screen is 60Hz...
### <!> A more specifica cvt refresh rate is the optional third parameter

### <!> The only line I see that is 4K is "Mode 0"
### <!> Modeline        "Mode 0" 297.00 3840 4016 4104 4400 2160 2168 2178 2250 +hsync +vsync
### <!> The quoted part of the Modeline is just a label
### <!> Changing "Mode 0" to "3480x2160" for my own nitpicky self

xrandr --newmode "3840x2160" 297.00 3840 4016 4104 4400 2160 2168 2178 2250 +hsync +vsync

### <!> cvt generated mode
#xrandr --newmode "3840x2160_60.00"  712.75  3840 4160 4576 5312  2160 2163 2168 2237 -hsync +vsync

xrandr --addmode HDMI-1-1 "3840x2160"

### <!> cvt generated mode
#xrandr --addmode HDMI-1-1 "3840x2160_60.00"

### <!> To see what's what and the available modes for each
#xrandr -q

### <!> Used arandr for help with xrandr bash command that follows
#apt install arandr && arandr
#  ...save output file as xrandr-example.sh from GUI application
#tail xrandr-example.sh
##  Output:
##  #!/bin/sh
##  xrandr --output HDMI-1-2 --off --output HDMI-1-1 --mode 1920x1080 --pos 1920x0 --rotate normal --output eDP-1-1 --primary --mode 1920x1080 --pos 0x0 --rotate normal --output VGA-1-1 --off --output DP-1-2 --off --output DP-1-1 --off

### <!> I took that "template" and substituted my own mode and positions

xrandr --output HDMI-1-1 --mode 3840x2160 --pos 0x0 --rotate normal --output HDMI-1-2 --off --output eDP-1-1 --primary --mode 1920x1080 pos 960x2160 --rotate normal --output VGA-1-1 --off --output DP-1-2 --off --output DP-1-1 --off

### <!> Now I want it to happen when I plug in my monitor
### <!> If W55 is seen, then run my xrandr command

#udevadm monitor

##  Output:
##  monitor will print the received events for:
##  UDEV - the event which udev sends out after rule processing
##  KERNEL - the kernel uevent
##
##  KERNEL[10928.549817] change   /devices/pci0000:00/0000:00:02.0/drm/card1 (drm)
##  UDEV  [10928.551102] change   /devices/pci0000:00/0000:00:02.0/drm/card1 (drm)
##  KERNEL[10939.083981] change   /devices/pci0000:00/0000:00:02.0/drm/card1 (drm)
##  UDEV  [10939.085367] change   /devices/pci0000:00/0000:00:02.0/drm/card1 (drm)

### <!> So, it is a drm UDEV change
### <!> We can use the change to trigger a script

echo "SUBSYSTEM==\"drm\", ACTION==\"change\", RUN+=\"/usr/local/bin/xrandr-for-W55-monitor.sh\"" > /etc/udev/rules.d/xrandr-for-W55-monitor.rules

### <!> Create the script and make it executable

### <!> There's a second way to get edid info

ls -1 /sys/class/drm/*/edid

##  Output:
##  /sys/class/drm/card1-DP-1/edid
##  /sys/class/drm/card1-DP-2/edid
##  /sys/class/drm/card1-eDP-1/edid
##  /sys/class/drm/card1-HDMI-A-1/edid
##  /sys/class/drm/card1-HDMI-A-2/edid
##  /sys/class/drm/card1-VGA-1/edid

### <!> To get the bash script "heredoc" to respect indent spacing below, the indents must be tabs...

cat <<-EOF > /usr/local/bin/xrandr-for-W55-monitor.sh
#!/usr/bin/env bash

if [[ $(xrandr | grep "HDMI-1-1 connected" | wc -l) -gt 0 ]]
    then
        #echo $(date) "drm event HDMI-1-1 changed" >> /tmp/checkin.txt
        if [[ $(parse-edid < /sys/class/drm/card1-HDMI-A-1/edid | grep "Identifier \"W55\"" | wc -l) -gt 0 ]]
            then
                #echo "IT'S W55!!!" >> /tmp/checkin.txt

                xrandr --newmode "3840x2160" 297.00 3840 4016 4104 4400 2160 2168 2178 2250 +hsync +vsync

                xrandr --addmode HDMI-1-1 "3840x2160"

                xrandr --output HDMI-1-1 --mode 3840x2160 --pos 0x0 --rotate normal --output HDMI-1-2 --off --output eDP-1-1 --primary --mode 1920x1080 --pos 960x2160 --rotate normal --output VGA-1-1 --off --output DP-1-2 --off --output DP-1-1 --off
            else
                xrandr --output HDMI-1-1 --mode 1920x1080 --above eDP-1-1
        fi
    else
        xrandr --output HDMI-1-1 --off
fi
EOF

chmod 550 /usr/local/bin/xrandr-for-W55-monitor.sh

### <!> That ought to do it...

A: As a partial data point, I have connected a Samsung 40" TV (which supports 4k60Hz at 4:4:4 over HDMI 2.0) to a MacBookPro11,3 (mid-2014 15" Macbook Pro) with Nvidia GT 750m at your resolution 3840-by-2160 ("4k") on Ubuntu, using an HDMI to HDMI cable.  I did not have to fiddle with command line beyond getting the correct nvidia driver installed.   I was able to use Ubuntu's Gnome display setting tool as well as nvidia-settings (to play with 4:4:4).  Since I am not currently using it, I cannot consult exact versions although I believe it was Ubuntu 18.04.x with 38x or 4xx nvidia drivers (I vaguely recall suspend problems at higher nvidia versions).  The GT 750m doesn't support HDMI 2.0, only 1.4, and thus 4k60Hz at 4:4:4 is not possible, although 4:2:0 (with poorer rendering of small colored text) may be possible.  On a specific HDMI input of the TV (I had to consult its documentation), I was able to get 4k at 30Hz with 4:4:4, and only 24Hz on the other ports.
Clearly it would be best for auto-detection to work for you.  As to why it's not auto-detecting in your case, I speculate that it's due to the HDMI-to-DisplayPort conversion.  It may be worth testing your laptop with another display that avoids the conversion.

A: So, apparently all the inputs of my TV work as 4k inputs... but, HDMI2 is supposedly special per the user manual. And HDMI2 works by default where I have to force all the shenanigans above for inputs HDMI1, HDMI3, and HDMI4.
I was able to repeat the exact same failure on a completely different laptop and resolve the exact same problem by simply connecting to HDMI2.
I still think it was neat to get a deeper understanding of xrandr and the video subsystem. (I could have died happy enough without knowing it too though... So, meh.)


text:
Q: Return n value of array Function and list in while loop PHP I'm trying to show list of countries by the use of PHP function.
Here's the database value that I'm retrieving on. (cropped)

Here's the function that I'm retrieving the data.
Code:
public function get_countries() {

    $list_country = array();
    $query = $this->db->prepare("SELECT name FROM country");
    $query->execute();

    while($r = $query->fetch(PDO::FETCH_ASSOC)) {
        $list_country[] = $r['name'];
    }

    return $list_country;
}

Then here's the code where I echo all the data.
<?php
    while (list($country) = $general->get_countries()) {
        echo $country;
    }
?>

Unfortunately, it just all echo the same value over and over again.

Any solution for this? Like echo-ing all the data instead of the same data over and over again?

A: <?php
    $country_array = $general->get_countries();
    foreach ($country_array as $country) {
        echo $country;
    }
?>

You don't need the while() as you already fetched all countries with get_countries() function. Moreover, with list() you retrieve only the n array elements where n is the number of variables inside list() function.
So, why are you getting every time the same value?
Because you're calling every time a db function for read country content and every time you're retrieving the same value (the first)

A: $query = $PDO->prepare("SELECT blah FROM table");
$country = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        $country[] = $row['blah'];
 }
That code worked for me. You can set some exception if the query returns null this would suppress your warnings in the while loop.
Hope that helps


text:
Q: Best way to avoid timeout in Java Selenium TestNG when I have multiple tests in one class? I have multiple tests in one class in Selenium TestNG. Problem is that nearly every time I get some timeout exception in different test or in a different step in a test. So is hard to catch exact element causing the timeout.
org.openqa.selenium.ElementNotVisibleException: element not visible
OR
org.openqa.selenium.WebDriverException: unknown error: Element  is not clickable at point (1887, 68). Other element would receive the click:
...

What is the best way to avoid timeout in Selenium TestNG when I have multiple tests in one class?
Is there some code which I can put for instance to
@BeforeClass or @Beforetest

Which will apply for all tests in the class?
For a better understanding, I am sharing my code.
 public class BothApprovalCockpitLighting   {

  private static WebDriver driver;
  public static WebDriverWait wd;

  @BeforeTest
  public void setUp()
  {
      System.out.println("*******************");
      System.out.println("launching Chrome browser");
      System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver_win32\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

  }

  @BeforeClass
  public void login() throws Exception
  {
       driver.get("https://test.com/");

       wd = new WebDriverWait(driver, 30);
        wd.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='username']")));

        // Enter username in textbox
        System.out.println("Enter username in textbox");
        driver.findElement(By.xpath("//input[@id='username']")).sendKeys("USERNAME" ); //Batcon

        //Enter Password in texbox
        System.out.println("Enter Password in texbox");
        driver.findElement(By.xpath("//input[@id='password']")).sendKeys("PASSWORD");

        //Click on Login button
        System.out.println("Click on Login button");
        driver.findElement(By.xpath("//input[@id='Login']")).click();

        System.out.println("Login Sucessfully");
  }

  @Test(priority=1)
  public void test1DontCointainApprovalCockpit() throws Exception
  {

      driver.findElement(By.xpath("//img[@alt='All Tabs']")).click();
      String pageSource = driver.getPageSource();

      boolean b1 = pageSource.contains("Approval");
      boolean b2 = pageSource.contains("Cockpit");

      System.out.println("Page should not cointain - Approval Cockpit. This is a negative test.");
      System.out.println("Page cointain Approval: " + b1);
      System.out.println("Page cointain Cockpit: " + b2);

      if(b1 || b2)
      {
          System.out.println("Test 1 is fail - Page cointain Approval Cockpit.");
      }
      else
      {
          System.out.println("Test 1 is past - Page doesn´t cointain Approval Cockpit.");
      }

      Assert.assertFalse(b1,"Failed test 1 page cointain Approval");
      Assert.assertFalse(b2,"Failed test 1 page cointain Cockpit");

  }

  @Test(priority=2)
  public void test2SwitchCointain() throws Exception
  {
      String actualText1 =  driver.findElement(By.xpath("(//a[contains(text(),'Switch')])[2]")).getAttribute("innerHTML");

      Assert.assertTrue(actualText1.contains("Switch to Lightning Experience"), "Failed test 2 page doesn´t cointain Switch");

  }

  @Test(priority=3)
  public void test3Switch() throws Exception
  {

       driver.findElement(By.xpath("//*[text()[contains(.,'John')]]")).click();
       driver.findElement(By.linkText("Switch")).click();

  }

  @Test(priority=4)
  public void test4FMIRApprovalCokpit() throws Exception
  {
      driver.findElement(By.className("slds-icon-waffle")).click();
      String actualText1 =  driver.findElement(By.xpath("//*[text()[contains(.,'FIR')]]")).getAttribute("innerHTML");

      System.out.println("FIR text: " + actualText1);

      Assert.assertTrue(actualText1.contains("FMIR"), "Failed test 4 page doesn´t cointain FMIR");

  }

  @Test(priority=5)
  public void test4ApprovalCokpit() throws Exception
  {

      String actualText2 =  driver.findElement(By.xpath("//*[text()[contains(.,'Cockpit')]]")).getAttribute("innerHTML");

      System.out.println("Cockpit text:" + actualText2);

      Assert.assertTrue(actualText2.contains("Approval Cockpit"), "Failed test 4 page doesn´t cointain Cockpit");

  }

  @Test(priority=6)
  public void test6Link() throws Exception
  {
      driver.findElement(By.xpath("//img[@alt='FIR']")).click();
  }

  @Test(priority=7)
  public void test7backToSalesforce() throws Exception
  {
      Thread.sleep(10000);
      driver.findElement(By.xpath("//img[@alt='User']")).click();
      driver.findElement(By.linkText("Switch to Classic")).click();
  }

  @AfterClass
  public void backToClassic() throws Exception
  {

        //driver.findElement(By.xpath("//img[@alt='User']")).click();
        //driver.findElement(By.linkText("Switch to Classic")).click(); //Not working

  }

  @AfterTest
  public void tearDown()
  {

      if(driver!=null)
      {
          System.out.println("Closing Chrome browser");
          driver.quit();
      }

  }
}

A: My suggestion here would be to implement a Page Object Model, and have a method that abstracts driver.findElement(By).
Then instead of calling driver.findElement directly, always call your method that is abstracting it.
E.g.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

    public abstract class BasePage {
        protected WebDriver driver;
        protected WebDriverWait wait;

        public BasePage(WebDriver driver) {
            this.driver = driver;
            wait = new WebDriverWait(driver, 30);
        }

        public void clickElement(By by) {
            wait.until(ExpectedConditions.elementToBeClickable(by));
            driver.findElement(by).click();
        }
    }

For each of the pages on your website, have a concrete page that extends BasePage.  Use BasePage for all your interactions through WebDriver, and you'll have a much easier time implementing "error handling" throughout your tests.


text:
Q: Cypher creates number as a long. How do I create an integer? I have a problem with types in Neo4j. I am trying with the following query to create a node with a variable number with the integer value 1:
Create (n:Test{numer:1})

When I am getting the node from the Java api I am getting an error telling me that it is of type long.
How can I see of what type a variable is saved in Neo4J? How can I save an integer?

A: If you use Cypher or REST API then Neo4j (internally) use Java's Long for integer values and Java's Double for floating point values.
In Java API you can use following datatypes

*

*boolean

*byte

*short

*int

*long

*float

*double

*char

*String

http://neo4j.com/docs/stable/property-values-detailed.html


text:
Q: Is the reciprocal of $\cfrac {-(2x-1)}{2}$ $\cfrac{-2}{(2x-1)}$?
I want to see if I'm not forgetting reciprocals. And that I'm correct and not misremembering.
It's the negative in front of the parentheses that's throwing me off.

A: The definition of reciprocal is, "the reciprocal of a number $ u $ is a number $ v $ with the property that $ u \cdot v = 1 $."  So if $ u = \frac{-(2x-1)}{2} $, then does your proposed $ v = \frac{-2}{2x-1} $ satisfy this definition?  Try multiplying it out and decide for yourself if it does.

A: The reciprocal of a fraction is simply found by swapping the denominator with the numerator, and also by swapping the numerator for the denominator.
eg the reciprocal of
$$\frac{a}{b}=\frac{b}{a}$$


text:
Q: Sharing data between cucumber scenarios using guice I have this scenario where a data is been set and I want to use that data across different scenarios. I would like to do it using guice
Scenario: set data
Given user with data <sharedData>
Then user set sharedData

Scenario: get and verify data
Given user gets <sharedData>
Then user verify sharedData

I like to use this sharedData in all other scenarios. I was not able to fine a clear example with this arrangement using guice

A: A way to do this is to not define the data in the scenario. Instead give the date a name and refer to it in the scenario. Then each of your steps can use this name to refer to the data, you can write a method in your step definitions to define the data, and you can use this method to provide the data in other step definitions to do comparisons, fill in forms etc.

A: You can share this common data in an object injected by Guice. This object would be updated by the step that is triggered by user with data <sharedData>
Your problem is then transformed into how you share state between steps using Guice. I just released a blog post describing one solution.


text:
Q: Best practices for designing a FSM for long running processes I'm primarily a c# developer and looking for some guidance (theory and/or code samples) on designing a finite state machine for a series of long running processes.  Each operation defined can run for several minutes.  I'm simply using the Windows Task Scheduler to manage scheduling and instancing.
Below is a simplified outline of what I'm looking at.  So far, I've built the Op Status FSM using Stateless.  Now, I'm trying to figure out the best way to handle the sequencing of the operations with some conditions thrown in, such as item #3 shows.  These conditions are based on data resulting from Op2.
Options I've consider so far:

*

*Create a FSM for the operation sequence (seems overly complex, but maybe I'm missing a fundamental somewhere)

*Create an operation manager for each operation and let each manager worry about what state(s) it's interested in along with what the next state should be

OPERATIONS -> NEXT OPERATION IN SEQUENCE

*

*None -> Op1

*Op1 -> Op2

*Op2 -> Op3 or Op4 conditionally

*Op3 -> Op4

*Op4 -> Op5

*Op5 -> None

OP STATUS

*

*Idle

*

*Trigger: Scheduled -> Pending

*Constraint: Operation must be set

*Pending

*

*Trigger: Run -> Running

*Running

*

*Trigger: Failed -> Error

*Trigger: Success -> Idle

*Trigger: NotReady -> Pending

*Error

*

*Trigger: Retry -> Pending

*Trigger: Cancel -> Idle (remove assigned operation)

A: This really sounds like the specific use case intended for Windows Workflow Foundation.  It provides all of the required plumbing to handle this type of scenario, including the ability to persist the workflows, restart them, etc.


text:
Q: Converting dates in R My dates in my data set in a CSV file are in the format yyyy/mm/dd. When inputted to R they are factors and are in the format "01-Aug-12".
I've tried the following:
as.Date(x=df$Date.of.Visit, format="%d %b %Y")

All I get returned is NA. Could this be because the year R sees is not 4 digits? ('12 rather than 2012).

A: In R documentation for as.Date:
## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")
## Sys.setlocale("LC_TIME", lct)
z

In your case just do:
lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
as.Date(x=df$Date.of.Visit, format="%d-%b-%y")
Sys.setlocale("LC_TIME", lct)

A: Or, using lubridate:
library(lubridate)
df$realdate <- ymd(df$Date.of.Visit)

Then the format is unimportant.


text:
Q: How can I change logfile path of phantomjs with selenium? When using phantomjs with selenium, I would like to change the default --webdriver-logfile parameter, that selenium passes to phantomjs. How can I do it?
The corresponding line in selenium log:
11:06:06.960 INFO - arguments: [--webdriver=14380, --webdriver-logfile=<ROOT PATH DELETED HERE>/phantomjsdriver.log]

Firing up phantomjs in coffeescript:
webdriverio = require 'webdriverio'

module.exports.World = World = (next) ->
  @browser = webdriverio.remote({ desiredCapabilities: {
    browserName: 'phantomjs'
    "phantomjs.binary.path": "node_modules/phantomjs/bin/phantomjs"
  }})
  .init()

next()

A: I was looking for few hours and could not find the answer, therefore I have hacked it in the phantomjs file that is called by selenium. This is not a proper solution but does the job.
args = args.map(function(str) {
 if(str.search('-webdriver-logfile') != -1 ) {
    console.log('Replacing default webdriver log with null in phantomjs');
    return str.replace(/--webdriver-logfile=.*$/i,"--webdriver-logfile=/dev/null")
 }
 return str;
 });


text:
Q: HttpContext null in WCF service? here is my line of code and it throws me error on HttpConext.Current
string postData = "username=" + HttpContext.Current.Server.UrlEncode(USERNAME);

A: If you want to enable the HttpContext you can set the aspNetCompatibilityEnabled flag in web config.
<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

A: That's normal. There is no HTTP Context in a WCF web service. A WCF service might not even be hosted inside a web server. You could host in inside a console application. There's a trick that allows you to set the ASP.NET Compatibility Mode:
<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

but it is not something that I would recommend you doing.
I would do this instead:
var postData = "username=" + HttpUtility.UrlEncode(USERNAME);

And because I have a 7th sense about where you are going with this code (sending it as an HTTP request to a remote web server) let's get straight to the point:
using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "username", USERNAME }
    };
    var result = client.UploadValues("http://foo.com", values);
}


text:
Q: How to create new SQL Server 2008 R2 login using C# I am using Visual Studio 2012 and C#
I use the below code to create a login and a user for my SQL Server database using C#
It works well for SQL Server 2012 but doesn't work on SQL Server 2008 R2.
Here's my code:
var serverName = "."; // Your SQL Server Instance name
var databaseName = "Test"; // Your database name
var loginName = "testuserY"; // Your login name (should not exist - or you should add code to check if the login exists)
Server svr = new Server(serverName);
var db = svr.Databases[databaseName];
if (db != null)
{
 Login login = new Login(svr, loginName);
 login.DefaultDatabase = "master"; // Logins typically have master as default database
 login.LoginType = LoginType.SqlLogin;
 login.Create("foobar", LoginCreateOptions.None); // Enter a suitable password
 login.Enable();
 User user = new User(db, loginName);
 user.UserType = UserType.SqlLogin;
 user.Login = login.Name;
 user.Create();
 user.AddToRole("db_owner");
 Server svr = new Server(serverName);

This code and other code after it doesn't run in SQL Server 2008 R2.
Help me please.

A: I found the Problem.
for solve this problem you should copy this dlls in your app folders:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SqlClrProvider.dll
Microsoft.SqlServer.SqlEnum.dll


text:
Q: How to combine two Ruby collections? A user is given two inputs, A and B (collections), and a number, X, and must create an output. The output starts with the first value from A, then takes X units from B, then the second value of A, and continuing like that until both A and B have been exhausted. You can assume 1 < X < sizeof(B). However, if either A or B runs out, you should loop back to the beginning of the short collection, and continue until the other runs out. The looping back should continue until both collections have hit their end.
What is an elegant way to do this in Ruby? I have some half-broken code and can't seem to find a good way to do this. No, it's not a homework problem. I have strange hobbies.
Here's some sample tests of the behavior I want:
# SomeModule.copy(A, B, X)
SomeModule.copy(%w(a1 a2 a3),    %w(b1 b2 b3),       1) == %w(a1 b1 a2 b2 a3 b3))
SomeModule.copy(%w(a1),          %w(b1),             1) == %w(a1 b1))
SomeModule.copy(%w(a1),          %w(b1 b2 b3),       1) == %w(a1 b1 a1 b2 a1 b3))
SomeModule.copy(%w(a1 a2),       %w(b1 b2 b3 b4 b5), 2) == %w(a1 b1 b2 a2 b3 b4 a1 b5 b1))
SomeModule.copy(%w(a1 a2),       %w(b1 b2 b3 b4 b5), 2) == %w(a1 b1 b2 a2 b3 b4 a1 b5 b1))
SomeModule.copy(%w(a1 a2 a3 a4), %w(b1 b2 b3 b4 b5), 3) == %w(a1 b1 b2 b3 a2 b4 b5 b1 a3 b2 b3 b4 a4 b5 b1 b2))

A: Here is something, the idea is to iterate every array until both of them reach their max index:
def custom_combine(a,b,x)
  max_index_a = a.count - 1
  max_index_b = b.count - 1
  a_run_out = false
  b_run_out = false

  output = []

  a.cycle.each_with_index do |elem_a, index_a|
    output << elem_a
    # base on a index get x elements from b
    x.times do |i|
      index_b = ((index_a * x) + i) % (max_index_b + 1)
      output << b[index_b]
      b_run_out = true if index_b == max_index_b
    end
    a_run_out = true if index_a == max_index_a
    break if a_run_out && b_run_out
  end

  output
end

a = %w(a1 a2 a3 a4)
b = %w(b1 b2 b3 b4 b5)
x = 3

custom_combine(a,b,x)
# => ["a1", "b1", "b2", "b3", "a2", "b4", "b5", "b1", "a3", "b2", "b3", "b4", "a4", "b5", "b1", "b2"]

A: Enumerable has an each_slice method that'll let you iterate over an enumerable object N items at a time. Using it, you can do something like this:
a1 = [1, 2, 3, 4, 5, 6]
a2 = [10, 11, 12, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, 60]

a1.each_slice(1).zip(a2.each_slice(3)).flatten

# => [1, 10, 11, 12, 2, 20, 21, 22, 3, 30, 31, 32, 4, 40, 41, 42, 5, 50, 51, 52, 6, 60]

A: Here's what finally jumped out of my brain at 4.30am:
class InfiniteArray
  private
  attr_reader :collection
  attr_accessor :index, :wrapped_count
  public

  def initialize(collection)
    @collection = collection
    reset
  end

  def next
    value = collection[index]
    if index < collection.length - 1
      self.index = index + 1
    else
      self.index = 0
      self.wrapped_count = wrapped_count + 1
    end
    value
  end

  def wrapped?
    wrapped_count > 0
  end

  def reset
    @index = 0
    @wrapped_count = 0
  end
end

class IntervalCopier
  private
  attr_reader :source_collection, :destination_collection, :interval
  public

  def initialize(source_collection, destination_collection, interval)
    @source_collection = InfiniteArray.new(source_collection)
    @destination_collection = InfiniteArray.new(destination_collection)
    @interval = interval
  end

  def copy
    final = []
    until source_collection.wrapped? && destination_collection.wrapped? do
      final << source_collection.next
      interval.times { final << destination_collection.next }
    end
    [source_collection, destination_collection].each(&:reset)
    final
  end
end

A: def copy(array1, array2, slice_length)
  iterations = [array1.length,
                (array2.length.to_f / slice_length.to_f).round
               ].max

  result = []
  enum1 = array1.cycle
  enum2 = array2.cycle

  iterations.times do
    result << enum1.next
    slice_length.times { result << enum2.next }
  end

  result
end

require 'minitest/autorun'

class TestCopy < Minitest::Test
  def test_copy
    assert_equal(%w(a1 b1 a2 b2 a3 b3),                               copy(%w(a1 a2 a3),    %w(b1 b2 b3),       1))
    assert_equal(%w(a1 b1),                                           copy(%w(a1),          %w(b1),             1))
    assert_equal(%w(a1 b1 a1 b2 a1 b3),                               copy(%w(a1),          %w(b1 b2 b3),       1))
    assert_equal(%w(a1 b1 b2 a2 b3 b4 a1 b5 b1),                      copy(%w(a1 a2),       %w(b1 b2 b3 b4 b5), 2))
    assert_equal(%w(a1 b1 b2 a2 b3 b4 a1 b5 b1),                      copy(%w(a1 a2),       %w(b1 b2 b3 b4 b5), 2))
    assert_equal(%w(a1 b1 b2 b3 a2 b4 b5 b1 a3 b2 b3 b4 a4 b5 b1 b2), copy(%w(a1 a2 a3 a4), %w(b1 b2 b3 b4 b5), 3))
  end
end


text:
Q: Is NFS hard- or soft-mounted to Kubernetes Pods? Is NFS hard- or soft-mounted when making a Pod in Kubernetes with an NFS-volume?
As I understand this might have an impact on how it handles a timeout?
Example yaml:
apiVersion: v1
kind: Pod
metadata:
  name: nfs-web
spec:
  containers:
- name: web
  image: nginx
  ports:
    - name: web
      containerPort: 80
  volumeMounts:
      - name: nfs
        mountPath: "/usr/share/nginx/html"
  volumes:
    - name: nfs
      nfs:
        server: nfs-server.default.kube.local
        path: "/"

A: I believe that the NFS mounts inside of a POD will use the defaults provided by the implementation of NFS in the container OS. I can't be 100% certain (I'm not deeply familiar with the code), but in my experience the NFS mounts are mounted with the hard option, which is default in most implementations of NFS (see man nfs for more details on your OS; soft is often considered dangerous.)
The NFSVolumeSource struct doesn't appear to have the ability to know about mount settings (except read-only) and I don't see any hard-coded options in the NFS volume code.
You can check on your own PODs with something like this to gather the NFS options in use:

$ kubectl exec  nfs-web-<XXXXX> -c web -- mount|grep nfs

A: its always "hard" mounted by default...however you can change it to soft by explicitly passing the additional annotation in PV definition.
volume.beta.kubernetes.io/mount-options: soft


text:
Q: variable keeps returning NULL, php protected $_name = 'usertable';  //table name for database [Impt] Please change accordingly
protected $_temp;

function resetPass($userid)
{
    $pass = new Application_Model_Register();
    $salt = $pass->generateSalt();
    $temp = $pass->generatePass();
    $this->_temp = (string) $temp;

    $data = array(
            'password' => hash("sha256", ($salt. $temp)),
            'salt' => $salt, //get salt from generateSalt()
    );

    //$auth= Zend_Auth::getInstance(); //declare zend_auth to get instance
    //$user= $auth->getIdentity(); //get identity of user
    //$userid   = $user->userid; //get userid of user

    echo $temp;

    $this->update($data, 'userid = '. (int)($userid));
    return $this;
}

function getTemp()
{
    return parent::$this->_temp;
}

This is my code in Model. I am trying to return $_temp therefore I made  $this->temp = $temp. My problem is that it returns NULL.
public function sendEmail($email)
{

    $email = $_POST['email'];

    $userid = '30';

    $reset = new Application_Model_DbTable_Register();
    $reset->resetPass($userid);

    $pswd = new Application_Model_DbTable_Register();
    $pswd = $pswd->getTemp();
    var_dump($pswd);

    $mail = new Zend_Mail();

    $mail->setFrom('swap.test@yahoo.com.sg', 'Inexorable Beauty');
    $mail->addTo($email, $email);
    $mail->setSubject('Inexorable Beauty: Password Reset');
    $mail->setBodyText('Dear Customer,

            You have requested to reset your password.
            This is the temporary password: '.$pswd.'

            Please log in immediately and change your password.
            Thank You.

            Yours Sincerely,
            Inexorable Beauty');

    $mail->send();

    if($mail->send())
    {
        echo "Email successfully sent!";
    }
    else
    {
        echo "Email was not sent";
    }

}

This is my controller code. I am trying to send the temporary passwd to the customer's email. I call the getTemp() function from my model to get the passwd string but as you can see I did var_dump($pswd) and it keeps returning NULL. Any solutions?

A: You're using
 return parent::$this->_temp;

Does $_temp exist in the parent object? It would appear you're definining it in THIS object, and it doesn't exist in the parent object you're (hopefully) inheriting from.

A: It looks like you are creating two DbTable_Register objects, calling reset on the first one, but not the second, and then you are trying to get the temp password from the second object.  The second one wont have temp because you have not called resetPass on the second object.
Try changing:
$reset = new Application_Model_DbTable_Register();
$reset->resetPass($userid);

$pswd = new Application_Model_DbTable_Register();
$pswd = $pswd->getTemp();
var_dump($pswd);

To:
$reset = new Application_Model_DbTable_Register();
$reset->resetPass($userid);
$pswd  = $reset->getTemp();

var_dump($pswd);

See if that works.

A: First : Check Application_Model_Register::generatePass(); function
Second : on resetPass function remove this:
$this->_temp = (string) $temp;

and add :
if (empty($temp)){
    $this->_temp = (string) $temp;
}

is it return a value of something? If it doesn't then the generatePass() function is wrong.
Third : on Your controller
$reset = new Application_Model_DbTable_Register();
$reset->resetPass($userid);
$pswd = new Application_Model_DbTable_Register();
$pswd = $pswd->getTemp();
var_dump($pswd);

don't make a double object like $reset and $pswd.
try to :
$reset = new Application_Model_DbTable_Register();
$pswd = $reset->resetPass($userid)->getTemp();
echo "<pre>";
print_r($pswd);

correct me if i'm wrong.


text:
Q: ReasonML vs TypeScript What are the tradeoffs between ReasonML (https://reasonml.github.io/) and TypeScript (https://www.typescriptlang.org/)?

A: The are very different.

*

*ReasonML is a distinct language from JavaScript that compiles down to JavaScript

*TypeScript is a strict superset of JavaScript that compiles down to JavaScript

If you want to write typesafe code both are excellent choices.

*

*If you want to write typesafe JavaScript, then TypeScript is the option.

*If you want to write typesafe some language that compiles down to JavaScript then ReasonML is one of many options. The some language in ReasonML's case is OCAML.
More
My biased opinion : https://medium.com/@basarat/typescript-won-a4e0dfde4b08

A: There are lot of languages nowadays that target JavaScript.
Choosing one of them depends on your needs and the idioms you're comfortable with.
JavaScript has a dynamic type system. Some developers prefer a static one.

*

*TypeScript or Haxe solves this with a new language that is statically typed and only transpiles to JavaScript.

*Flow is a JavaScript preprocessor that targets the same issue but without the need to learn a new language. I prefer this approach if you only need a type system.
Some JS developers want more and use more functional programming idioms (algebraic data structures, immutability, pattern matching, ...). A lot of programming languages can do it (OCaml, Haskell, ReasonML, F#, Scala, ...).

*

*ReasonML is a syntax for OCaml that can compile to either native or JavaScript through BuckleScript. All you can achieve with Reason can also be achieved with OCaml, except that the ReasonML syntax accepts JSX. ReasonML can easily target node.js app, react.js app or native app.

TypeScript is easy to learn if you come from the Java or C# world.
ReasonML is harder to learn if you never developed with an ML language (OCaml or F#)
My advice:

*

*If you just need a static type system, you should consider TypeScript

*If you need a type system to do a react.js or react-native app, you should consider ReasonML because ReasonReact is a huge improvement over react.js

*If you need a functional programming language that compiles to js, you should consider ReasonML

A: There are many trade-offs, many of them stemming from ReasonML technically just being OCaml and therefore inheriting most of the design decisions from OCaml's 25-year old history of being a natively compiled language with little regard for this strange JavaScript niche on the web.
But as it is I think the biggest trade-off is between ReasonML's sound and flexible type system, and TypeScript's ability to easily "sneak" comprehensive static checks into an existing JavaScript code base.
TypeScript's type system is explicitly designed to not be sound, and so while it will give you a hand most of the time, it won't be able to give you many guarantees. You really can't fully trust the type system to have your back, which is one the biggest advantages of having a proper static type system.
TypeScript is also limited by its decision of avoiding runtime type information, which is necessary for features such as pattern matching and a major benefit of working with typed data in ReasonML.
ReasonML on the other hand requires that the boundary between itself and existing JavaScript code is explicitly defined. Types can to some extent be inferred, but they must still be determined at compile-time. This makes JavaScript interoperation more laborious, especially if the boundary gradually moves as an existing JavaScript code base is converted. It's also not always obvious how to type some of the weird stuff that goes on In JavaScript, but it's usually possible, and hopefully just temporary until everything has been converted to ReasonML anyway :)
Obviously I'm biased, but I hope this doesn't come across as picking a clear winner at least because there really isn't. This is a major trade-off, at least as long as the world's not perfect.

A: In a large application you will need a lot of features, which are provided by default in ReasonML: strict types, runtime validation if you encode/decode JSON, fast compilation time, immutable data.
In TypeScript you will have to add:

*

*ImmutableJS + its typings.

*Runtime validators like json-schema + its typings. Then you will have to write types in TypeScript, and also defined a schema in json-schemas. They can become out of sync very soon.

*Some crazy hacks to tell the difference if variable is of specific type (like in official docs of TS: https://www.typescriptlang.org/docs/handbook/advanced-types.html, Paragraph "User-Defined Type Guards"). This checks are done using side effects like a.swim !== undefined. In 6 months this 'if' statement will contain more and more checks.

*You are lucky if a package you use has official and maintained type definitions. Or you will end up with custom typings.

*If you develop hybrid app in JS + TS, then TS Compiler cannot create a bundled final d.ts file which you can import in other parts of your project. You will have to write separate d.ts files, which are bundled by tools like dts-bundle. If you have everything in TS, then this issue is not applicable.

*Large apps take a lot of time to be compiled by TypeScript.

With ReasonML:

*

*Immutable data is in the language.

*Runtime validators are present (bs-json has them by default)

*Pattern matching saves you from these crazy checks.

*You are lucky if npm package you want to use has BuckleScript bindings.

*N/A.

*ReasonML compilation is very fast.

A: Reason ML comes with functional first School, If you are in that mind set that's the way to Go. Whereas typescript can do fp and also has good community support. Almost all popular libraries has typescript typings. I prefer using fpts (https://github.com/gcanti/fp-ts/blob/master/README.md). It provides all the goodness of fp in typescript that includes runtime check as well. Although type constructor is a big miss in ts. Choose ts if you are okay to live with it.

A: (just a note)
Putting all practical aspects aside;
The ML family of languages are based on a type theory called System-F, which is also used by Purescript and Haskell, for instance.
Typescript lacks such a well established foundation and instead uses a new experimental type system with many special bits (I am not even sure if it's "formalised").
So on the surface, TS's approach might seem "practical", but it introduces more complexity that necessary. System F has a small number of rules that make up the system and it is very general, yet easier to reason about that TS's "theory". Less is more.
Also, effort put into learning System-F is rather timeless and translates to other, more powerful languages, such as Purescript.


text:
Q: how to check whether a inputted value is a character or not so we are working on a mastermind game and whenever someone inputs a string, it freaks.
    //INVALIDS
if (space1!='a' && space1!='b' && space1!='c' && space1!='d' && space1!='e' && space1!='f')
    {
    printf("Invalid entry.\n");
    goto label;
    }
if (space2!='a' && space2!='b' && space2!='c' && space2!='d' && space2!='e' && space2!='f')
    {
    printf("Invalid entry.\n");
    goto label;
    }
if (space3!='a' && space3!='b' && space3!='c' && space3!='d' && space3!='e' && space3!='f')
    {
    printf("Invalid entry.\n");
    goto label;
    }
if (space4!='a' && space4!='b' && space4!='c' && space4!='d' && space4!='e' && space4!='f')
    {
    printf("Invalid entry.\n");
    goto label;
    }

A: Simply get the input in an char array and then process it for single character. If there are more than one alphaneumeric characters then show error or do whatever you want.
Note: This is not the way you should write code and avoid goto it generates some really-annoying-bugs.
Some snippet
char s[100];
do
{
scanf("%s",s);
...
}while(strlen(s)>1..)
process s[100]

As mentioned by iharob a better way to use it is to %n specifier. The %n format specifier,when used in a scanf() is expected to store the count of the number of characters of the format string already processed by the function into an argument of type int*.
  So you can have
 int len;
 scanf("%s%n",s,&len);
 //process len

chux mentioned a better solution: use fgets().
For example..
fgets(s,len+1,stdin);
//process s[]

A: Separate the validation logic into its own function.  You can take advantage of the strchr function in the standard library for this particular test:
int isValid( int c )
{
  static const char *validChars = "abcdef";
  return strchr( c, validChars ) != NULL;
}

If the value of c is one of the characters in validChars, strchr will return a pointer to that character, otherwise it will return NULL.  So if c is not one of a, b, c, d, e, or f, the isValid function will return 0 (false), otherwise it will return 1 (true).
Now, I am assuming that your spaceN variables are all separate inputs, not part of the same input.  Probably the simplest (if not most intuitive) approach to guarantee a single-character input is the following:
char c;
if ( scanf( " %c%*[^\n]", &c ) == 1 ) // note leading blank in format string!
  // valid single-character input

This will tell scanf to skip over any leading whitespace (including newlines), read and store the first non-whitespace character to c, and then consume but not store everything up to the next newline.
NOTE - anytime you find yourself creating a bunch of variables of the same type with the same name and an ordinal like space1, space2, space3, space4, then you're usually better off using an array.
Putting this all together, we get:
int space[4];

/**
 * Get the number of elements in the space array; this way we
 * don't have to hardcode a size in our loop
 */
size_t numElements = sizeof space / sizeof space[0];

for ( i = 0; i < numElements; i++ )
{
  int done = 0;
  do
  {
    printf( "Gimme an input (0 to quit): " );
    fflush( stdout );
    if ( scanf( " %c%*[^\n]", &space[i] ) != 1 )
    {
      fprintf( stderr, "Error reading input, bailing...\n" );
      exit( 0 );
    }
    done = isValid( space[i] );
    if ( !done && space[i] != '0' )
      fprintf( stderr, "Invalid input, try again\n" );
  } while ( !done && space[i] != '0' );

  if ( space[i] == '0' )
  {
    fprintf( stderr, "Got a '0' for input, quitting...\n" );
    exit( 0 );
  }
}

Without seeing more of your code, I don't know if this is useful or not.


text:
Q: SOFTWARE_TOKEN_MFA fails if try to use Custom Auth Challenge Lambda Triggers I have a question with AWS Cognito:
Initially, the UserPool and the UserPool Client were configured by default to:
authenticationFlowType: 'USER_SRP_AUTH'
users were also allowed to use MFA
Right now we decided to switch to Custom Auth Challenge Lambda Triggers
authenticationFlowType:  'CUSTOM_AUTH'
to add specific logic for authentication
and unfortunately faced with the fact that SOFTWARE_TOKEN_MFA falls off, the answer from AWS Cognito is now different
(instead of information about device comes next step for CUSTOM_AUTH) and Amplify throws an error:
Cannot read properties of undefined (reading 'NewDeviceMetadata')
Is it even possible to use SOFTWARE_TOKEN_MFA with Custom authentication challenge Lambda triggers and if yes, how to do this correct?
UPD: I created issue/bug report at Amplify repo with full description


text:
Q: How to run a makefile - Python - Speciteller I have a large database of text which i want to analyze on it's sentence specificity. I want to use the tool 'Speciteller' for that, using Python. Link to the tool:
https://github.com/wjko2/Domain-Agnostic-Sentence-Specificity-Prediction/tree/master/python
One of the dependencies is to make sure to have liblinear.so. in the python/ directory. If not, i can execute a makefile - 'type make in /python' . I opened my Anaconda Prompt to execute this command,  but it doesn't work. It says it is not recognized as a command, operable program or batch file.
I have already been looking how to specifically execute makefiles in Python, but i have a hard time finding the answer. Does anyone has some advice?
Note: i am still a beginner concerning Python.
Thanks in advance!
EDIT: Bump - anyone has any idea?
Edit: Operating on a Windows system

A: In the meantime this problem has been solved. A new update was released and additional code was provided to run it in Python smoothly. See the following repository:
https://github.com/wjko2/Domain-Agnostic-Sentence-Specificity-Prediction

A: A Makefile is a way to  describe to a computer the steps of the compilation process of a program. To use a Makefile, on an Unix-like system (Linux, MacOS, etc.) one need to have the program make installed on their computer, and then, in a unix-shell (and not powershell like the anaconda prompt), run the command make.
However Windows does not know natively how to process those files, as the program make is not available by default on Windows. You can use a tool like WSL that let you run command designed for GNU/Linux on Windows. (I recommend installing Ubuntu 18.04). Going this route means that you will probably need to reinstall anaconda inside WSL though.


text:
Q: jQuery Forms post with $.ajax I have this vote system on a wordpress installation everything works fine if I have only one post if I have more, the AJAX posts only for the first form.
So every post has a HTML form:
<form method="post" id="vote_<?php the_ID(); ?>" class="vote" name="vote">
    <input type="hidden" id="vote_post_id" name="vote_post_id" value="<?php the_ID(); ?>" />
    <input type="hidden" id="vote_count" name="vote_count" value="1" />
    <?php echo get_post_meta($post->ID, 'votes', true); ?>
    <input type="submit" name="vote_up" class="vote_up" value="+1" />
</form>

And here's the jQuery:
$(function() {
    $('form.vote').submit(function() {
        var url = 'http://bla-bla.com/lib/';
            post_id = $('input#vote_post_id').attr('value');
            count = $('input#vote_count').attr('value');
            form_id = $('form.vote').attr('id');
            cast_vote = 'post_id=' + post_id + '&count=' + count;
            original_count = $('span.votes_count').html();
            new_value = parseInt(original_count) + 1;

        //alert (cast_vote);return false;
        $.ajax({
            type: 'POST',
            url: url + 'cast.php',
            cache: false,
            timeout: 10000,
            data: cast_vote,
            success: function(data){
                $('form.vote').find('span.votes_count').fadeIn(1500, function() {
                    $(this).html(new_value);
                });
                $('form.vote').removeClass('vote').addClass('user_voted disabled');
            }
        });
        return false;
    });

});

So I want this to work, only on the form that have been submited. How do I achieve that?
.each() will work?

A: If I am understanding this correctly(if not just ignore me lol)...
You can use the .live function to hold a reference to every submit button on the page...
$('.vote-up').live('click', function(){

      //do your ajax calls here...

});

this will essentially create a click event for each vote up button...


text:
Q: How can I concisely display a list of table columns in sorted order in postgres? I know I can get the list of columns for a table displayed in sorted order by executing this long sql command (in this case from the table 'orders'):
select column_name from information_schema.columns
where table_schema = 'public' and table_name = 'orders'
order by column_name;

How can this be done most concisely? For example, if the built-in \d command accepted a flag, it could be:
\d -s orders
Naturally, this doesn't work, but I'd like something similar to avoid having to type in the entire original query above repeatedly. Maybe defining a function that can be invoked concisely that's parameterized by table name?

A: The raw query is about as terse as it can be. To minimise the typing effort of using it, create a view (with a short name):
create view cols as
select column_name, table_name tab
from information_schema.columns
where table_schema = 'public'
order by column_name

Then to use it:
select * from cols where tab = 'mytable'

Note how (with postgres) you can define a view with an order (saving you from typing the order by every time).

A: This may not be what you want, but it is my current solution to the problem. I use the shell:
psql -t db_name -c '\d table_name' | sort

This prints out a sorted list of columns which makes discovering schema easier on that random remote system. With the added benefit of not having to remember any arbitrary sql.


text:
Q: nesting inside css :not() selectors Is it possible to have nested values inside the :not selector? For eg:
:not(div > div)

Whenever I tried it, it does not seem to work.
Perhaps you need to use it another way which I have not figured out?
So far, in all the examples I see, you can only use one value inside this selector.

A: :not() only accepts one simple selector at a time; this is mentioned in the Selectors 3 spec:

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

The simple selectors in your example would be the two div tokens that you have. Other simple selectors include class selectors, ID selectors, attribute selectors and pseudo-classes. It does not accept more than one simple selector, nor does it accept combinators like > or space.
Depending on which elements you're trying to select exactly, there may not be a way to exclude div > div:

*

*If you only want to select elements that are children of a div, that are themselves not div, use this instead:
div > :not(div)

*If you only want to select div elements whose parent element is not a div, use this instead:
:not(div) > div

If you want to use this negation by itself, selecting all other elements, then there isn't a way using just a selector.
The only other viable workaround in CSS that I can think of is to apply styles to the elements you want without the :not() expression, then undo them for div > div. This works for any set of elements you're trying to target; the disadvantage is that not all properties can be easily reset.
Alternatively, if you're using jQuery, which does support :not(div > div) unlike the CSS version, you can place the selector in a script and, for instance, have jQuery apply a class name to those elements then target that class in your CSS.

A: It should work now thanks to Selectors Level 4 which allows :not() to take a list of complex selectors.
You can now also nest :not()... like :not(:not()) which wasn't allowed in Selectors Level 3. Not sure why you'd want to do that but you can.


text:
Q: How can I use mod_rewrite to rewrite a query string working with W3 Total Cache? I'm using WordPress with W3 Total Cache. W3 Total Cache is set to cache requests with query strings, which is working just fine.
However, I have a couple of pages with very different queries that I still want to cache as one request, since the query string is just used by Javascript on the page to create dynamic content based on the query.
So, let's say I have the requests:
www.site.se/foo/bar/?token=78843743&baz=no
and
www.site.se/foo/bar/?token=87232310&baz=yes
At the moment, those requests are cached by W3TC separately, so the second request does not hit the cache.
How can I strip the query string using mod_rewrite so that W3TV will see them as one request and cache them as one?

A: So, you want to proxy the request without the query string.
This should do the trick.  Make sure mod_proxy module is loaded and active in Apache.
RewriteEngine On
RewriteRule ^/foo/bar/$ /foo/bar/? [P]

The bare ? at the end should clear the query string.  Just don't use the QSA flag and you should be fine.


text:
Q: "uninitialized constant Cucumber::Rb_Support (NameError)" when running Cucumber for Ruby & Watir After installing Ruby, Cucumber and Watir using gem I get the following error:
uninitialized constant Cucumber::Rb_Support (NameError)
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/constantize.rb:41:in `constantize_name'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/constantize.rb:13:in `block in constantize'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/constantize.rb:12:in `each'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/constantize.rb:12:in `constantize'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:87:in `load_programming_language'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:242:in `programming_language_for'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:226:in `load_file'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:97:in `block in load_files!'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:96:in `each'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime/support_code.rb:96:in `load_files!'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime.rb:242:in `load_step_definitions'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/runtime.rb:65:in `run!'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/lib/cucumber/cli/main.rb:38:in `execute!'
W:/Programme/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-2.0.2/bin/cucumber:9:in `<top (required)>'
W:/Programme/Ruby193/bin/cucumber:23:in `load'
W:/Programme/Ruby193/bin/cucumber:23:in `<main>'**

Anyone got any idea why this is not working?
I copied the exact example from the github page.

A: I finally found a solution myself.
If anyone runs into this problem it is most likely caused by Ruby versions that are not compatible with Gherkin/Cucumber and/or Watir.
Although there are newer version of Ruby, the only versions that worked on my Windows 7 (Win64) machine were a combination of:

*

*Ruby: rubyinstaller-2.0.0-p645.exe

*DevKit: DevKit-mingw64-32-4.7.2-20130224-1151-sfx.exe

Then I followed the installation instructions on http://www.spritecloud.com/2015/04/complete-setup-guide-for-ruby-cucumber-and-watir-on-windows/
And I used the example on https://github.com/spriteCloud/cucumber-watir-example which worked.
Following this did not create any errors and the example worked.
Good luck!


text:
Q: Uncaught Syntax Error: Invalid or unexpected token in PHP My code is syntactically correct but then also I am facing the error when I console log.
My PHP ,HTML , javascript code goes like this :
<html>

<body>
<form action="" method="post">
    <select name="Fees">
        <option value="" disabled selected>Choose option</option>
      <option value="500">Above $500</option>
  <option value="9000">Above $9000</option>
  <option value="1500">Below $1500</option>
    </select>
    <input type="submit" name="submit" values="Choose options">
</form>
<?php
    if(isset($_POST['submit'])){
    if(!empty($_POST['Fees'])) {
        $selected = $_POST['Fees'];

    } else {
        echo 'Please select the value.';
    }
    }
?>
<script>
spge = '<?php echo $selected ;?>';
fee_selected=parseInt(spge);
console.log("Fees Selected : "+fee_selected);
</script>
</body>
</html>

I get the error

Uncaught Syntax Error: Invalid or unexpected token in PHP

A: As mentioned, $selected is not always defined. And you have two if statements indented but only one echo of "Please select the value".  One way to fix it is
<html>

<body>
<form action="" method="post">
    <select name="Fees">
      <option value="" disabled selected>Choose option</option>
      <option value="500">Above $500</option>
  <option value="9000">Above $9000</option>
  <option value="1500">Below $1500</option>
    </select>
    <input type="submit" name="submit" values="Choose options">
</form>
<?php
    $selected = 0;  //<----------------
    if(isset($_POST['submit'])){
      if(!empty($_POST['Fees'])) {
        $selected = $_POST['Fees'];
      }
      else {
        echo 'Please select the value.';
      }
    }
    else {
       echo 'Please select the value.'; //<--------------
    }
?>
<script>
spge = '<?php echo $selected ;?>';
fee_selected=parseInt(spge);
console.log("Fees Selected : "+fee_selected);
</script>
</body>
</html>


text:
Q: R - Line Chart axis overlap I am trying to draw a plot (I have no idea how this one could be called) and I have trouble with axis labels overlapping.

I was wondering if you have any advices to add some spaces between labels.
Thanks.
Because the 3rd value is higher than the others I gave it a value of 30 and then labelled it with the real value 115.
dta$freqOri = dta$freq
dta$freq[3] <- 30

The plot loops
par(mar = c(0, 10.1, 0, 10.1))

for(i in 1:nrow(dta)){
  plot(0, ylim = c( min(dta$freq) - 5, max(dta$freq) + 2), bty = 'n', type = 'n', axes = F, ylab = '',  xlab = '')
  abline(h = dta$freq[i])
  axis(2, at = dta$freq[i], labels = dta$freqOri[i], las=2, tick = F, line = 7, cex.axis=0.6)
  axis(2, at = dta$freq[i], labels = dta$nameFrom[i], las=2, line = 0.5, tick =  F, cex.axis=0.6)
  axis(4, at = dta$freq[i], labels = dta$nameTo[i], las=2, line = 0.5, tick = F, cex.axis=0.6)
  par(new = T)
}

The data
dta = structure(list(freq = structure(c(8.5, 9, 30, 3.2, 13.4, 1.3,
0.3, 4.1, 5.3, 6.7, 18.3, 5, 17.7, 2.1, 0.2, 4.5, 5.6, 8.5, 18.3
 ), .Dim = 19L, .Dimnames = structure(list(aaaa = c("a alone->b partner",
"b partner->a alone", "b partner->b partner", "b partner->c child",
"b partner->d nuclear", "b partner->e nuclear and acquaintance",
"b partner->f children and acquaintance", "b partner->g partner and acquaintance",
"b partner->h acquaintance", "b partner->i True Missing", "b partner->j work study sleep",
 "c child->b partner", "d nuclear->b partner", "e nuclear and acquaintance->b partner",
"f children and acquaintance->b partner", "g partner and acquaintance->b partner",
"h acquaintance->b partner", "i True Missing->b partner", "j work study sleep->b partner"
)), .Names = "aaaa")), name = c("a alone->b partner", "b partner->a alone",
"b partner->b partner", "b partner->c child", "b partner->d nuclear",
"b partner->e nuclear and acquaintance", "b partner->f children and acquaintance",
"b partner->g partner and acquaintance", "b partner->h acquaintance",
"b partner->i True Missing", "b partner->j work study sleep",
"c child->b partner", "d nuclear->b partner", "e nuclear and acquaintance->b partner",
"f children and acquaintance->b partner", "g partner and acquaintance->b partner",
 "h acquaintance->b partner", "i True Missing->b partner", "j work study sleep->b partner"
 ), nameFrom = c("a alone", "b partner", "b partner", "b partner",
"b partner", "b partner", "b partner", "b partner", "b partner",
"b partner", "b partner", "c child", "d nuclear", "e nuclear and acquaintance",
"f children and acquaintance", "g partner and acquaintance",
"h acquaintance", "i True Missing", "j work study sleep"), nameTo = c("b partner",
"a alone", "b partner", "c child", "d nuclear", "e nuclear and acquaintance",
"f children and acquaintance", "g partner and acquaintance",
"h acquaintance", "i True Missing", "j work study sleep", "b partner",
"b partner", "b partner", "b partner", "b partner", "b partner",
"b partner", "b partner"), freqOri = structure(c(8.5, 9, 115.2,
 3.2, 13.4, 1.3, 0.3, 4.1, 5.3, 6.7, 18.3, 5, 17.7, 2.1, 0.2,
 4.5, 5.6, 8.5, 18.3), .Dim = 19L, .Dimnames = structure(list(
aaaa = c("a alone->b partner", "b partner->a alone", "b partner->b partner",
"b partner->c child", "b partner->d nuclear", "b partner->e nuclear and acquaintance",
"b partner->f children and acquaintance", "b partner->g partner and acquaintance",
"b partner->h acquaintance", "b partner->i True Missing",
"b partner->j work study sleep", "c child->b partner", "d nuclear->b partner",
"e nuclear and acquaintance->b partner", "f children and acquaintance->b partner",
"g partner and acquaintance->b partner", "h acquaintance->b partner",
"i True Missing->b partner", "j work study sleep->b partner"
)), .Names = "aaaa"))), .Names = c("freq", "name", "nameFrom",
"nameTo", "freqOri"), row.names = c(NA, 19L), class = "data.frame")

A: It seems that the overlapping has two separate causes: lines plotted at the same location and lines plotted close together. When the lines are plotted at the same location (e.g. 18.3 or 8.5) you could manually specify a rotation using the srt parameter in text() so that both labels are visible and terminate at the same location. You might need to change the adj parameter to control text justification as well.
When the lines are separate but the labels overlap, there are a few possibilities. First, the text size could be adjusted until the labels do not overlap, but they may not be readable. Second, the labels could be plotted horizontally off-set (not all justified to the same x location), which might entail extending some of the lines so that they terminate at the label. Thirdly, it might be possible to use the rotation method described above to separate these labels. Lastly, the lines could be plotted farther apart but labeled in the original units.


text:
Q: Scikit learn DLL load failed in anaconda I am getting an import error while trying to import sklearn package in anaconda jupyter notebook. The import statement is
from sklearn.model_selection import train_test_split

The stack trace of the error is
    ImportError                               Traceback (most recent call last)
<ipython-input-2-fc66e67e2be3> in <module>
      2 import numpy as np
      3 import matplotlib.pyplot as plt
----> 4 from sklearn.model_selection import train_test_split
      5 from sklearn.preprocessing import LabelEncoder
      6 from keras.models import Model

~\Anaconda3\lib\site-packages\sklearn\__init__.py in <module>
     62 else:
     63     from . import __check_build
---> 64     from .base import clone
     65     from .utils._show_versions import show_versions
     66

~\Anaconda3\lib\site-packages\sklearn\base.py in <module>
     11 from scipy import sparse
     12 from .externals import six
---> 13 from .utils.fixes import signature
     14 from . import __version__
     15

~\Anaconda3\lib\site-packages\sklearn\utils\__init__.py in <module>
     14 from . import _joblib
     15 from ..exceptions import DataConversionWarning
---> 16 from .fixes import _Sequence as Sequence
     17 from .deprecation import deprecated
     18 from .validation import (as_float_array,

~\Anaconda3\lib\site-packages\sklearn\utils\fixes.py in <module>
     90     from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr
     91 else:
---> 92     from scipy.sparse.linalg import lsqr as sparse_lsqr  # noqa
     93
     94

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\__init__.py in <module>
    115 from .dsolve import *
    116 from .interface import *
--> 117 from .eigen import *
    118 from .matfuncs import *
    119 from ._onenormest import *

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\__init__.py in <module>
      9 from __future__ import division, print_function, absolute_import
     10
---> 11 from .arpack import *
     12 from .lobpcg import *
     13

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\arpack\__init__.py in <module>
     20 from __future__ import division, print_function, absolute_import
     21
---> 22 from .arpack import *

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py in <module>
     43 __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence']
     44
---> 45 from . import _arpack
     46 import numpy as np
     47 import warnings

ImportError: DLL load failed: The specified procedure could not be found.

Can anyone help.

A: I also faced this error and solved it through a lot of trial and error. It was strange that I could import sklearn.metrics successfully in the python shell, but not in the Jupyter Notebook.
Finally, I was able to resolve the issue by simultaneously reinstalling scipy and related packages with anaconda: conda install numpy numpy-base scipy scikit-learn mkl --force-reinstall
I found this StackOverflow post useful: Python scipy module import error due to missing ._ufuncs dll

A: This thread is older, but maybe someone runs into the same issue. In my case removing (or renaming them to .bak) all MKL-libraries from Windows/system32 helped:
mkl_core.dll
mkl_def.dll
mkl_intel_thread.dll
libiomp5md.dll
libmmd.dll

Also check Windows/SysWOW64 for these files.
In my case I deleted the first 4 files, like some posts in other forums suggest, but still got the "DLL load failed: The specified procedure could not be found"-Error. Using dependencywalker I figured out, that the libmmd.dll also had to be removed.


text:
Q: How to load image from a url without image extension The following image url
https://via.placeholder.com/150/771796
Its working in browser, but from picasso and glide i am not able to load the image into my imagview.

A: You have to resize image in this size load failed.


text:
Q: Proving that $\frac{6n^2+3n}{2n^2-5}$ converges to 3. Prove the following:
$$\lim_{n\to \infty}\frac{6n^2+3n}{2n^2-5}=3$$
Here's my solution:
Consider the function $\frac{6n^2+3n}{2n^2-5}$.
Then $$|\frac{6n^2+3n}{2n^2-5}-3|= |\frac{6n^2+3n}{2n^2-5}-\frac{6n^2+15}{2n^2-5}|=|\frac{3n-15}{2n^2-5}|$$
The upper bound for the numerator is $3n-15 \le 3n$ for all $n$ and the lower bound for the denominator is $2n^2-5 \le 4n^2$ if $n \le 2$.
It follows that
$|\frac{3n-15}{2n^2-5}| \le \frac{3n}{4n^2}$. Meaning $|\frac{3n-15}{2n^2-5}| \le \frac{3}{4n}$.
By the Archimedean Property, $\frac{3}{4n} \le \frac{3}{4N} \lt \epsilon$
Therefore $(\frac{6n^2+3n}{2n^2-5})\rightarrow 3$.
$\blacksquare$
I feel like I'm missing a step after showing that $\frac{3}{4n} \le \frac{3}{4N} \lt \epsilon$.
Can $\frac{3}{4n} \le \frac{3}{4N} \lt \epsilon$ be simplified more so that it resembles $\frac{1}{n} \le \frac{1}{N} \lt \epsilon$ or is it fine how it is?
Please advise.

A: $$\left|\frac{6n^2+3n}{2n^2-5}-3\right|= \left|\frac{6n^2+3n}{2n^2-5}-\frac{6n^2\color{red}-15}{2n^2-5}\right|=\left|\frac{3n\color{red}+15}{2n^2-5}\right|$$
Hence upper bound for the numerator when $n> 15$, is $|3n+15| \leq 4n.$
A lower bound for the denominator for $n \geq 3$, is $|2n^2-5| \geq n^2$
It follows that $\left|\frac{3n+15}{2n^2-5}\right|\leq \frac4n$ for $n>15$.
Now, by archimedian property, $\forall \epsilon>0 , \exists N>0, \frac{4}{N}<\epsilon$, now let $n>\max(N, 15)$. and we have
$$\left|\frac{3n+15}{2n^2-5}\right|\leq \frac4n \leq \frac4N<\epsilon$$

A: To get an upper bound, you want to replace the numerator by something big and the denominator by something small. So instead of $2n^2-5\lt4n^2$, you should use $2n^2-5\gt2n^2$ (or even just $n^2$). Aside from that, everything is basically OK.


text:
Q: Subthemes in Drupal How we can display a subtheme in a specific page in drupal, such as a taxonomy page?

A: Do you mean you want to use a subtheme  of your main theme for certain pages?
Have a look at the Sections module, which lets you specify a theme for pages or groups of pages matching a pattern on their URL.
It doesn't matter whether the theme you want to apply is a theme or a subtheme.
Hope this helps,
James

A: Another option is to use themekey. Themekey lets you choose the theme based on a whole lot of different factors, one option is the path

A: Use this code in your hook_boot():
function mymodule_boot() {
  if (/* test based on the $_GET['q'] or REQUEST_URI */) {
    $GLOBALS['custom_theme'] = 'myothertheme';
  }
}

A: this sounds like a job for context and spaces. These modules will allow you to set up different themes for different sections of the site based on a set of parameters. It's very flexible and provides a framework to deal with a variety of such theming issues, not just this particular one.
Alternatively you could set up alternative .tpl.php files that are chosen in a preprocess based on the path.


text:
Q: Python open module seeing a list as a string I have a text file created from a bash script that outputs floats into a list.  The contents of the file look like this: [0.2, 0.6, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1].  I wanted to manipulate this file as a list using Python but Python seems to think its a string and not a list.  Below is a sample of my basic Python script:
#!/bin/python3

with open('CPU_Parsed.txt', 'r') as cpu:
        contents = cpu.read()
print(contents)
print(type(contents))
print(list(contents))

When executed the initial print returns: [0.2, 0.6, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1].
The second print returns 'string'.
And when I attempt to turn the entire thing into a list that Python might recognize it parses everything into mush like:
['[', '0', '.', '2', ',', ' ', '0',etc...
My question is how do I get python to read this text file.  I want Python to notice the [...] as well as the floats and see it as a list instead of seeing it as a string so that I can further manipulate the list.  I appreciate everyone's help!!! Thank you so much!!!!


text:
Q: Django Rest Framework JWT 400 Bad Request By default when credentials are wrong, DRF-JWT return a response with 400 status.
Why is it like that?
When users don't provide correct login information, bad request log gets written in the browser's console.
So I handle the error at the front but still it is not nice to have a console error message.
So how can I override the JWT to not raise a 400, instead return success, what is the correct way to do it?

A: In case of bad login credentials, your server should return HTTP 401 or 400 error. More about that:

*

*RESTful Login Failure: Return 401 or Custom Response

*Issue in DRF-JWT repo: 400 or 401
4XX stands for client-side errors. Bad credentials is the example of that case. There is nothing wrong with console error message resulted from bad request.


text:
Q: What's the relationship between renderer process and BrowserWindow? What's the relationship between renderer process and BrowserWindow?
Whether they can be considered the same thing?

A: In the context of Electron, the renderer process and BrowserWindow are closely related.
A BrowserWindow is a Chromium-based window that is displayed in the user's desktop. It is created and controlled by the main process of the Electron app. Each BrowserWindow instance has its own renderer process, which is responsible for rendering the web page displayed in the window.
The renderer process is a separate process from the main process and runs in a separate thread. It is responsible for handling the web page's JavaScript, HTML, and CSS, as well as interacting with the web page's DOM (Document Object Model). It communicates with the main process using Inter-Process Communication (IPC) to handle events such as user input and window resizing.
In summary, the renderer process is responsible for rendering the web page in a BrowserWindow, while the BrowserWindow is responsible for creating and managing the window on the user's desktop. The main process is responsible for creating and managing the BrowserWindow instances and the renderer processes associated with them.